Unlocking the Potential of PDFs: A Guide to PDF-lib.js

What is PDF-lib.js?

PDF-lib.js is a JavaScript library that enables developers to create, modify and manipulate PDF documents in the browser or server-side using Node.js. It provides a range of features such as creating new PDF documents, adding text, images, and shapes, and modifying existing PDF documents.

The library is built on top of PDF.js, a popular open-source PDF viewer, and is designed to be easy to use and flexible. It provides a simple API for creating and modifying PDF documents, allowing developers to customize and automate the process of PDF generation.

Some of the key features of PDF-lib.js include:

➡️ Creating new PDF documents from scratch or merging existing ones
➡️ Adding text, images, and shapes to PDF documents
➡️ Modifying existing PDF documents by changing text, images, and other content
➡️ Encrypting and decrypting PDF documents
➡️ Adding digital signatures to PDF documents
➡️ Extracting data from PDF documents

PDF-lib.js is compatible with most modern browsers and supports both client-side and server-side PDF document manipulation. It is also available as an npm package for easy installation and integration with Node.js projects.

Overall, PDF-lib.js is a powerful and flexible library that simplifies working with PDF documents in JavaScript.

Create a PDF with React

To create a PDF document in React using PDF-lib.js, you need to follow these steps:

1. Install the library:

npm install pdf-lib

2. Import the necessary classes from the library:

import { PDFDocument, StandardFonts } from 'pdf-lib';

3. Define a function that will create the PDF document:

async function createPdf() {
const pdfDoc = await PDFDocument.create()
const timesRomanFont =
await pdfDoc.embedFont(StandardFonts.TimesRoman)

const page = pdfDoc.addPage()
const { width, height } = page.getSize()
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),
})

const pdfBytes = await pdfDoc.save()


// Create a Blob object from the Uint8Array
const pdfBlob = new Blob([pdfBytes], { type: 'application/pdf' });

// Download the PDF file
saveAs(pdfBlob, 'example.pdf');
}

4. Call the createpdf function to generate the PDF document:

<button onClick={createPdf}>Create PDF</button>

Related read: Creating PDFs with ReactJS: A Step-by-Step Guide

Modify a PDF

import { degrees, PDFDocument, rgb, StandardFonts } from 'pdf-lib';

async function modifyPdf() {
const url = 'https://pdf-lib.js.org/assets/with_update_sections.pdf'
const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer())

const pdfDoc = await PDFDocument.load(existingPdfBytes)
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica)

const pages = pdfDoc.getPages()
const firstPage = pages[0]
const { width, height } = firstPage.getSize()
firstPage.drawText('This text was added with JavaScript!', {
x: 5,
y: height / 2 + 300,
size: 50,
font: helveticaFont,
color: rgb(0.95, 0.1, 0.1),
rotate: degrees(-45),
})
const pdfBytes = await pdfDoc.save()
}

Hire Our Experienced Full Stack React.js Developers to Meet Your Business Requirements.

Filling PDF Forms

Here is an example of how you can fill in a PDF form using PDF-lib.js in React.

import { PDFDocument } from 'pdf-lib';

async function fillPdfForm() {
// Fetch the PDF file as a Uint8Array
const response = await fetch('/path/to/example.pdf');
const pdfBytes = await response.arrayBuffer();

// Load the PDF document
const pdfDoc = await PDFDocument.load(pdfBytes);

// Get the PDF form
const form = pdfDoc.getForm();

// Fill in the form fields
form.getTextField('First Name').setText('John');
form.getTextField('Last Name').setText('Doe');
form.getCheckBox('Agree').check();
form.getRadioGroup('Gender').select('Male');

// Save the PDF document
const pdfBytesFilled = await pdfDoc.save();

// Download the filled PDF document
const blob = new Blob([pdfBytesFilled], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
window.open(url);
}

This code snippet loads a PDF file, gets its form, and fills in the text fields, checkboxes, and radio buttons using the setText, check, and select methods. Finally, it saves the filled PDF document and downloads it. You can customize this code snippet to fit your specific use case.

Flattening a PDF

Flattening a PDF is the process of removing the form fields and annotations from the document and converting them into simple graphics. When a PDF document is flattened, the fields and annotations become part of the page content and can no longer be edited or interacted with.

Flattening a PDF is useful when you want to preserve the document’s appearance and prevent changes to the content. For example, if you are distributing a form or document that should not be altered by the recipient, you can flatten the PDF to ensure that the fields and annotations cannot be modified.

However, flattening a PDF also means that the form fields and annotations will no longer be accessible or editable, which may be a disadvantage if you need to modify the document in the future.

It’s important to note that flattening a PDF is a permanent change and cannot be undone. Before flattening a PDF, you should make sure that you have saved a copy of the original document in case you need to make changes later.

import { PDFDocument } from 'pdf-lib';

async function flattenPdf() {
// Fetch the PDF file as a Uint8Array
const response = await fetch('example.pdf');
const pdfBytes = await response.arrayBuffer();

// Load the PDF document
const pdfDoc = await PDFDocument.load(pdfBytes);

// Flatten the PDF document
pdfDoc.flatten();

// Serialize the flattened PDF document to a Uint8Array
const pdfBytesFlattened = await pdfDoc.save();

// Create a Blob object from the Uint8Array
const pdfBlob = new Blob([pdfBytesFlattened], { type: 'application/pdf' });

// Download the flattened PDF file
saveAs(pdfBlob, 'flattened.pdf');
}
coma

Conclusion

In conclusion, PDF-lib.js is a powerful library that unlocks a multitude of possibilities for working with PDF documents. Whether you need to create new PDFs by adding text and images, incorporate new pages into existing PDFs, or modify PDFs by adding, modifying, or removing elements like text, images, and annotations, PDF-lib.js makes the process effortless.

Furthermore, PDF forms can be easily filled out by setting field values. And when the need arises, PDF-lib.js allows you to flatten PDF documents, preserving their appearance and preventing further changes by removing form fields and annotations. With its flexibility and functionality, PDF-lib.js proves to be a valuable tool for PDF manipulation.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?