Welcome folks today in this blog post we will be using the pdf-lib
library to create pdf
documents and adding
text and images
in command line using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to initialize a new node.js
project using the below command
npm init- y
After that you need to install the below libraries using the npm
command as shown below
npm i pdf-lib
Now we need to create the index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
const { PDFDocument, StandardFonts, rgb } = require("pdf-lib"); const fs = require("fs"); run().catch((err) => console.log(err)); async function run() { // Create a new document and add a new page const pdfDoc = await PDFDocument.create(); const page = pdfDoc.addPage(); const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman); // Get the width and height of the page const { width, height } = page.getSize(); // Draw a string of text toward the top of the page const fontSize = 30; page.drawText("Creating PDFs in JavaScript is awesome!", { x: 50, y: height - 4 * fontSize, size: fontSize, font: timesRomanFont, color: rgb(0, 0.53, 0.71), }); // Write the PDF to a file fs.writeFileSync("./test.pdf", await pdfDoc.save()); } |
As you can see we are importing the pdf-lib
library and then we are using the drawText()
method to insert the text inside the pdf document at x
and y
position and also we are using the custom
fonts which is called timesRomanFont
and also we are providing the custom color
of the text. And then we are saving the pdf
document using the fs
module.
Adding Images in PDF Document
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
const { PDFDocument } = require("pdf-lib"); const fs = require("fs"); run().catch((err) => console.log(err)); async function run() { // Create a new document and add a new page const doc = await PDFDocument.create(); const page = doc.addPage(); // Load the image and store it as a Node.js buffer in memory let img = fs.readFileSync("./image.jpg"); img = await doc.embedJpg(img); // Draw the image on the center of the page const { width, height } = img.scale(1); page.drawImage(img, { x: page.getWidth() / 2 - width / 2, y: page.getHeight() / 2 - height / 2, }); // Write the PDF to a file fs.writeFileSync("./test.pdf", await doc.save()); } |
As you can see we are using the drawImage()
method to add the image inside the pdf
document and then we are providing the x
and y
coordinates and then we are using the fs
module to save the image
in pdf document.