Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save documentprocessing/1e2c28a73af94f37df3679390feb0557 to your computer and use it in GitHub Desktop.
Save documentprocessing/1e2c28a73af94f37df3679390feb0557 to your computer and use it in GitHub Desktop.
Create PDF documents, Add Images and Shapes to PDF & Create PDF Forms in JavaScript using pdfkit Library. Check for more details.
// Include pdfkit library and fs module of Node.js
const PDFDocument = require('pdfkit');
const fs = require('fs');
// Create a document
const doc = new PDFDocument();
// Pipe its output
doc.pipe(fs.createWriteStream('pdfkit.pdf'));
// Set the font size, and render some text
doc.fontSize(25)
.text('This text is added to the document using the pdfkit library', 100, 100);
// Add an image, constrain it to a given size, and center it vertically and horizontally
doc.image('js-logo.png', {
fit: [250, 300],
align: 'center',
valign: 'center'
});
// Finalize PDF file
doc.end();
// Include pdfkit library and fs module of Node.js
const PDFDocument = require('pdfkit');
const fs = require('fs');
// Create a document
const doc = new PDFDocument();
// Pipe its output
const writeStream = fs.createWriteStream('pdfkit.pdf');
doc.pipe(writeStream);
// Set the font size, and render some text
doc.fontSize(25).text('This text is added to the document using the pdfkit library', 100, 100);
// Draw the triangle
doc
.save()
.moveTo(100, 150)
.lineTo(100, 250)
.lineTo(200, 250)
.fill('blue');
// Draw the circle
doc
.save()
.circle(300, 200, 50)
.fill('#FF3300');
// Finalize PDF file
doc.end();
// Include pdfkit library and fs module of Node.js
const PDFDocument = require('pdfkit');
const fs = require('fs');
// Create a new PDF document
const doc = new PDFDocument();
// Create a writable stream to save the PDF
const stream = fs.createWriteStream('sample_form.pdf');
// Pipe the PDF document to the writable stream
doc.pipe(stream);
// Define the fields
const fields = [
{ label: 'Name:', x: 50, y: 50 },
{ label: 'Email:', x: 50, y: 100 },
{ label: 'Phone:', x: 50, y: 150 },
];
// Function to add text fields to the PDF
function createTextFields(fields) {
fields.forEach((field) => {
doc
.fontSize(14)
.text(field.label, field.x, field.y)
.rect(field.x + 100, field.y - 5, 200, 20)
.stroke();
});
}
// Add text fields to the PDF
createTextFields(fields);
// Finalize the PDF document
doc.end();
// Include pdfkit library and fs module of Node.js
const PDFDocument = require('pdfkit');
const fs = require('fs');
// Create a document
const doc = new PDFDocument();
// Pipe its output
doc.pipe(fs.createWriteStream('pdfkit.pdf'));
// Set the font size, and render some text
doc.fontSize(25)
.text('This text is added to the document using the pdfkit library', 100, 100);
// Finalize PDF file
doc.end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment