PDF Creation & Editing via Open Source JavaScript API
Open Source JavaScript Library for Creating & modifying PDF Files, add & copy pages & insert images to PDF via JavaScript.
What is PDF-Lib?
PDF-Lib is an open source JavaScript library that enables software professionals to develop powerful applications for working with PDF files. The library is very feature-rich and designed to work in any modern JavaScript runtime. It has included support for new PDF files creation, editing existing PDF documents, creating forms, adding or removing PDF pages, Copy pages between PDFs, drawing text & images, measuring the width and height of the text, splitting and merging documents, read & set PDF metadata, Draw Vector Graphics and many more.
The library is written in Typescript and compiled to pure JavaScript with no other dependencies. One great purpose of the creation of PDF-Lib library was to address the JavaScript ecosystem's lack of robust support for PDF editing or modification. There are various good JavaScript libraries that support the creation of PDF files but very few included strong support for PDF modification. The PDF-Lib has included complete support for PDF modification as well as working in all JavaScript environments (not just Node or the Browser).
Getting Started with PDF-Lib
The recommended and easiest way to get started and install PDF-Lib is via npm as well as at yarn, below is the command.
install PDF-Lib via npm
npm install --save pdf-lib
install PDF-Lib via yarn
yarn add pdf-lib
PDF Documents Creation & Modification via JavaScript
The open source PDF-Lib library has included complete functionality for PDF document creation as well as modification. Software developers can create a new PDF document from the scratch with just a couple of lines of JavaScript code inside their own applications. Once created developers can insert text, draw images or vector graphics, embed their fonts, copy and embed pages from other PDFs, apply formatting and styles of their choice, and much more.
How to Create PDF Documents via JavaScript ?
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'
// Create a new PDFDocument
const pdfDoc = await PDFDocument.create()
// Embed the Times Roman font
const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman)
// Add a blank page to the document
const page = pdfDoc.addPage()
// 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),
})
// Serialize the PDFDocument to bytes (a Uint8Array)
const pdfBytes = await pdfDoc.save()
Copy Pages between PDF Documents via JS Library
It is often very beneficial to use an existing page instead of creating a new page inside a PDF document. The open source PDF-Lib library enables computer programmers to copy pages from various PDF documents and add them to their desired PDF documents without any external dependencies. First, you need to load both PDF files, after that, you can use copyPages() command to copy the desired pages, and then use the addPage() command to add the page at the desired location inside the PDF documents.
How to Add Text to Existing PDF using JavaScript Library?
import { PDFDocument } from 'pdf-lib'
// Create a new PDFDocument
const pdfDoc = await PDFDocument.create()
const firstDonorPdfBytes = ...
const secondDonorPdfBytes = ...
// Load a PDFDocument from each of the existing PDFs
const firstDonorPdfDoc = await PDFDocument.load(firstDonorPdfBytes)
const secondDonorPdfDoc = await PDFDocument.load(secondDonorPdfBytes)
// Copy the 1st page from the first donor document, and
// the 743rd page from the second donor document
const [firstDonorPage] = await pdfDoc.copyPages(firstDonorPdfDoc, [0])
const [secondDonorPage] = await pdfDoc.copyPages(secondDonorPdfDoc, [742])
// Add the first copied page
pdfDoc.addPage(firstDonorPage)
// Insert the second copied page to index 0, so it will be the
// first page in `pdfDoc`
pdfDoc.insertPage(0, secondDonorPage)
// Serialize the PDFDocument to bytes (a Uint8Array)
const pdfBytes = await pdfDoc.save()
Parse & Read Metadata from PDF Files
The PDF-Lib library fully supports accessing and reading metadata of PDF documents. Metadata is a very important part of PDF documents and has included very significant information about the PDF and its contents such as title, subject, author, copyright information, creator, date of creation or modification, and so on. Using PDF-Lib library software developers can easily parse and extract metadata from a PDF document with just a couple of lines of JavaScript code.
How to Set & Read MetaData of a PDF Files using JavaScript API?
import { PDFDocument, StandardFonts } from 'pdf-lib'
// Create a new PDFDocument
const pdfDoc = await PDFDocument.create()
// Embed the Times Roman font
const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman)
// Add a page and draw some text on it
const page = pdfDoc.addPage([500, 600])
page.setFont(timesRomanFont)
page.drawText('The Life of an Egg', { x: 60, y: 500, size: 50 })
page.drawText('An Epic Tale of Woe', { x: 125, y: 460, size: 25 })
// Set all available metadata fields on the PDFDocument. Note that these fields
// are visible in the "Document Properties" section of most PDF readers.
pdfDoc.setTitle('🥚 The Life of an Egg 🍳')
pdfDoc.setAuthor('Humpty Dumpty')
pdfDoc.setSubject('📘 An Epic Tale of Woe 📖')
pdfDoc.setKeywords(['eggs', 'wall', 'fall', 'king', 'horses', 'men'])
pdfDoc.setProducer('PDF App 9000 🤖')
pdfDoc.setCreator('pdf-lib (https://github.com/Hopding/pdf-lib)')
pdfDoc.setCreationDate(new Date('2018-06-24T01:58:37.228Z'))
pdfDoc.setModificationDate(new Date('2019-12-21T07:00:11.000Z'))
// Serialize the PDFDocument to bytes (a Uint8Array)
const pdfBytes = await pdfDoc.save()
Add Attachments to PDF via JavaScript API
Sometimes we need to provide more detailed information about a PDF file, so we can attach another file to that file. Now the benefit of that file will be that the attachment will travel with the PDF if you move it to a different location. The open source PDF-Lib library gives software developers the capability to attach other files to their PDF documents inside their JavaScript apps. It is possible to attach various types of files to a PDF, such as Microsoft Word, Excel, images, video or even other PDFs.
How to Add Attachments to PDF using JavaScript API?
const jpgAttachmentBytes = ...
const pdfAttachmentBytes = ...
// Create a new PDFDocument
const pdfDoc = await PDFDocument.create()
// Add the JPG attachment
await pdfDoc.attach(jpgAttachmentBytes, 'cat_riding_unicorn.jpg', {
mimeType: 'image/jpeg',
description: 'Cool cat riding a unicorn! 🦄🐈🕶️',
creationDate: new Date('2019/12/01'),
modificationDate: new Date('2020/04/19'),
})
// Add the PDF attachment
await pdfDoc.attach(pdfAttachmentBytes, 'us_constitution.pdf', {
mimeType: 'application/pdf',
description: 'Constitution of the United States 🇺🇸🦅',
creationDate: new Date('1787/09/17'),
modificationDate: new Date('1992/05/07'),
})
// Add a page with some text
const page = pdfDoc.addPage();
page.drawText('This PDF has two attachments', { x: 135, y: 415 })
// Serialize the PDFDocument to bytes (a Uint8Array)
const pdfBytes = await pdfDoc.save()