Pdf-lib tutorial – Generate PDF in Node.js

Welcome to this in-depth tutorial on the npm package pdf-lib. This package is a powerful tool for creating and modifying PDF documents in JavaScript. Throughout this guide, we’ll cover a wide range of examples, showcasing how to harness the features of pdf-lib to achieve various tasks. Our step-by-step instructions will help you get started with ease, and our troubleshooting tips will ensure a smooth experience.

PDF-Lib tutorial

Table of Contents

Installation of pdf-lib

To begin with, you need to install pdf-lib in your project. It’s as simple as running the following command in your terminal:

npm install pdf-lib

Once the installation is complete, you’re ready to start generating your PDF documents.

Creating a PDF

Let’s create a function that initializes a new PDF document and saves it:

async function createPdf() {
  const { PDFDocument } = require('pdf-lib');

  // Create a new PDFDocument
  const pdfDoc = await PDFDocument.create();

  // Save the blank PDF
  const pdfBytes = await pdfDoc.save();

  // Use fs to write the file to disk, browser, or return the bytes
}
createPdf();

Output: A new, blank PDF file is created.

Adding Text to a PDF

Text can be added to a pdf using pdf-lib as follows:

async function addTextToPdf() {
  const { PDFDocument, rgb } = require('pdf-lib');
  const pdfDoc = await PDFDocument.create();

  // Add a blank page
  const page = pdfDoc.addPage();
  
  // Draw a string of text diagonally across the first page
  page.drawText('Hello, World!', {
    x: 50,
    y: 450,
    size: 50,
    color: rgb(0, 0.53, 0.71),
  });

  // Save the PDF with the text
  const pdfBytes = await pdfDoc.save();

  // Write or return pdfBytes...
}
addTextToPdf();

Output: A new PDF file containing the text “Hello, World!”.

Adding Images to a PDF

This example illustrates how to add an image to a PDF:

async function addImageToPdf() {
  const { PDFDocument } = require('pdf-lib');

  const pdfDoc = await PDFDocument.create();
  const page = pdfDoc.addPage();

  // Use the 'fs' module to read the image file
  const fs = require('fs');
  // This should be the path to your image file
  const imagePath = 'path/to/image.png';
  const imageBytes = fs.readFileSync(imagePath);

  // Embed the image in the document
  const image = await pdfDoc.embedPng(imageBytes);
  const { width, height } = image.scale(0.5);

  // Add the image to the page
  page.drawImage(image, {
    x: page.getWidth() / 2 - width / 2,
    y: page.getHeight() / 2 - height / 2,
    width,
    height,
  });

  // Save the PDF with the image
  const pdfBytes = await pdfDoc.save();

  // Write or return pdfBytes...
}
addImageToPdf();

Output: A new PDF file with the specified image embedded in it.

Modifying an Existing PDF

Now let’s modify an existing PDF by adding a new page:

async function modifyExistingPdf() {
  const { PDFDocument } = require('pdf-lib');
  const fs = require('fs');

  // This should be the path to your existing PDF file
  const existingPdfPath = 'path/to/existing.pdf';
  const existingPdfBytes = fs.readFileSync(existingPdfPath);

  const pdfDoc = await PDFDocument.load(existingPdfBytes);

  // Add a new blank page to the existing PDF
  const page = pdfDoc.addPage();

  // Optionally add some text or images to the new page...

  // Save the modified PDF
  const pdfBytes = await pdfDoc.save();

  // Write or return pdfBytes...
}
modifyExistingPdf();

Output: The existing PDF with a new page added.

Troubleshooting Tips

If you encounter issues while working with pdf-lib:

  • Ensure you have the latest version of Node.js and npm installed.
  • Check the error messages for clues — they can often point you in the right direction.
  • Consult the pdf-lib documentation for additional guidance and typical use cases.

References

Conclusion

Throughout this tutorial, we’ve explored the capabilities of the pdf-lib npm package for creating and modifying PDF files with JavaScript. We’ve covered how to install the package, create a new PDF, add text and images, as well as modify an existing PDF. By now, you should be comfortable using pdf-lib in your projects. Remember to refer to the official pdf-lib documentation for more complex tasks and features. Happy coding!