0% found this document useful (0 votes)
544 views

PDF-LIB Create and Modify PDF Documents in Any JavaScript Environment

The document provides examples of how to use the pdf-lib library to create and modify PDF documents from JavaScript. It shows how to draw text, images, embed fonts, add and remove pages, copy pages from one PDF to another, and embed entire PDF documents or pages within other PDFs. The examples include creating a new PDF from scratch, modifying text on an existing page, copying pages between documents, embedding images and PDF pages, and measuring text dimensions after embedding a custom font.

Uploaded by

Mi Sy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
544 views

PDF-LIB Create and Modify PDF Documents in Any JavaScript Environment

The document provides examples of how to use the pdf-lib library to create and modify PDF documents from JavaScript. It shows how to draw text, images, embed fonts, add and remove pages, copy pages from one PDF to another, and embed entire PDF documents or pages within other PDFs. The examples include creating a new PDF from scratch, modifying text on an existing page, copying pages between documents, embedding images and PDF pages, and measuring text dimensions after embedding a custom font.

Uploaded by

Mi Sy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

PDF-LIB Search

API Help GitHub

import { PDFDocument } from 'pdf-lib'

// PDF Creation
const pdfDoc = await PDFDocument.create()
const page = pdfDoc.addPage()
page.drawText('You can create PDFs!')
const pdfBytes = await pdfDoc.save()

// PDF Modification
const pdfDoc = await PDFDocument.load(...)
const pages = pdfDoc.getPages()
pages[0].drawText('You can modify PDFs too!')
const pdfBytes = await pdfDoc.save()

Create and modify PDF documents in any


PDF-LIB JavaScript environment. Search

API Help GitHub


EXAMPLES INSTALL

Create and Modify


Create PDF documents from scratch, or modify existing PDF documents.
Draw text, images, and vector graphics. Even embed your own fonts.

Pure JavaScript
Written in TypeScript and compiled to pure JavaScript with no native
dependencies. Works in any JavaScript runtime, including browsers, Node,
and even React Native.

Split and Merge


Add, insert, and remove pages. Split a single PDF into separate ones. Or
merge multiple PDFs into a single document.

Quick Start
<html>
PDF-LIB
<head> Search
<meta charset="utf-8" />
<script src="https://unpkg.com/pdf-lib"></script>
API Help GitHub
</head>

<body>
<iframe id="pdf" style="width: 100%; height: 100%;"></iframe>
</body>

<script>
createPdf();
async function createPdf() {
const pdfDoc = await PDFLib.PDFDocument.create();
const page = pdfDoc.addPage([350, 400]);
page.moveTo(110, 200);
page.drawText('Hello World!');
const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });
document.getElementById('pdf').src = pdfDataUri;
}
</script>
</html>

Save this snippet as an HTML file and load it in your browser to get up and
running with pdf-lib as quickly as possible.

Install

NPM Module
If you are using npm or yarn as your package manager:

# With npm
npm install --save pdf-lib
# With yarn
PDF-LIB
yarn add pdf-lib Search

API Help GitHub


UMD Module
If you aren't using a package manager, UMD modules are available on the
unpkg and jsDelivr CDNs:

https://unpkg.com/pdf-lib/dist/pdf-lib.js
https://unpkg.com/pdf-lib/dist/pdf-lib.min.js
https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.js
https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js

NOTE: if you are using the CDN scripts in production, you should
include a specific version number in the URL, for example:
https://unpkg.com/pdf-lib@1.4.0/dist/pdf-lib.min.js
https://cdn.jsdelivr.net/npm/pdf-lib@1.4.0/dist/pdf-lib.min.js

Create Document Try the JSFiddle demo

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

async function createPdf() {


const pdfDoc = await PDFDocument.create()
const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesR

const page = pdfDoc.addPage()


const { width, height } = page.getSize()
const fontSize = 30
page.drawText('Creating PDFs in JavaScript is awesome!', {
PDF-LIB
x: 50, Search
y: height - 4 * fontSize,
size:
API fontSize, Help GitHub
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
})

const pdfBytes = await pdfDoc.save()


}
PDF-LIB Search

API Help GitHub

Modify Document Try the JSFiddle demo

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

async function modifyPdf() {


const url = 'https://pdf-lib.js.org/assets/with_update_sections.pd
const existingPdfBytes = await fetch(url).then(res => res.arrayBuf

const pdfDoc = await PDFDocument.load(existingPdfBytes)


const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helveti
PDF-LIB Search
const pages = pdfDoc.getPages()
const
API firstPage = pages[0] Help GitHub
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()


}
PDF-LIB Search

API Help GitHub

Copy Pages Try the JSFiddle demo

import { PDFDocument } from 'pdf-lib'

async function copyPages() {


const url1 = 'https://pdf-lib.js.org/assets/with_update_sections.p
const url2 = 'https://pdf-lib.js.org/assets/with_large_page_count.

const firstDonorPdfBytes = await fetch(url1).then(res => res.array


const secondDonorPdfBytes = await fetch(url2).then(res => res.arra
PDF-LIB Search
const firstDonorPdfDoc = await PDFDocument.load(firstDonorPdfBytes
const
API secondDonorPdfDoc = await
Help PDFDocument.load(secondDonorPdfByt
GitHub

const pdfDoc = await PDFDocument.create();

const [firstDonorPage] = await pdfDoc.copyPages(firstDonorPdfDoc,


const [secondDonorPage] = await pdfDoc.copyPages(secondDonorPdfDoc

pdfDoc.addPage(firstDonorPage)
pdfDoc.insertPage(0, secondDonorPage)

const pdfBytes = await pdfDoc.save()


}
PDF-LIB Search

API Help GitHub

Embed PNG and JPEG Images Try the JSFiddle demo

import { PDFDocument } from 'pdf-lib'

async function embedImages() {


const jpgUrl = 'https://pdf-lib.js.org/assets/cat_riding_unicorn.j
const pngUrl = 'https://pdf-lib.js.org/assets/minions_banana_alpha

const jpgImageBytes = await fetch(jpgUrl).then((res) => res.arrayB


const pngImageBytes = await fetch(pngUrl).then((res) => res.arrayB
PDF-LIB Search
const pdfDoc = await PDFDocument.create()
API Help GitHub
const jpgImage = await pdfDoc.embedJpg(jpgImageBytes)
const pngImage = await pdfDoc.embedPng(pngImageBytes)

const jpgDims = jpgImage.scale(0.5)


const pngDims = pngImage.scale(0.5)

const page = pdfDoc.addPage()

page.drawImage(jpgImage, {
x: page.getWidth() / 2 - jpgDims.width / 2,
y: page.getHeight() / 2 - jpgDims.height / 2 + 250,
width: jpgDims.width,
height: jpgDims.height,
})
page.drawImage(pngImage, {
x: page.getWidth() / 2 - pngDims.width / 2 + 75,
y: page.getHeight() / 2 - pngDims.height + 250,
width: pngDims.width,
height: pngDims.height,
})

const pdfBytes = await pdfDoc.save()


}
PDF-LIB Search

API Help GitHub

Embed PDF Pages Try the JSFiddle demo

import { PDFDocument } from 'pdf-lib'

async function embedPdfPages() {


const flagUrl = 'https://pdf-lib.js.org/assets/american_flag.pdf';
const constitutionUrl = 'https://pdf-lib.js.org/assets/us_constitu

const flagPdfBytes = await fetch(flagUrl).then((res) => res.arrayB


const constitutionPdfBytes = await fetch(constitutionUrl).then((re
PDF-LIB
res.arrayBuffer(), Search
);
API Help GitHub
const pdfDoc = await PDFDocument.create();

const [americanFlag] = await pdfDoc.embedPdf(flagPdfBytes);

const usConstitutionPdf = await PDFDocument.load(constitutionPdfBy


const preamble = await pdfDoc.embedPage(usConstitutionPdf.getPages
left: 55,
bottom: 485,
right: 300,
top: 575,
});

const americanFlagDims = americanFlag.scale(0.3);


const preambleDims = preamble.scale(2.25);

const page = pdfDoc.addPage();

page.drawPage(americanFlag, {
...americanFlagDims,
x: page.getWidth() / 2 - americanFlagDims.width / 2,
y: page.getHeight() - americanFlagDims.height - 150,
});
page.drawPage(preamble, {
...preambleDims,
x: page.getWidth() / 2 - preambleDims.width / 2,
y: page.getHeight() / 2 - preambleDims.height / 2 - 50,
});

const pdfBytes = await pdfDoc.save();


}
PDF-LIB Search

API Help GitHub

Embed Font and Measure Text


Try the JSFiddle demo

The @pdf-lib/fontkit module must be installed to embed custom fonts.

import { PDFDocument, rgb } from 'pdf-lib'


import fontkit from '@pdf-lib/fontkit'
PDF-LIB
async function embedFontAndMeasureText() { Search
const url = 'https://pdf-lib.js.org/assets/ubuntu/Ubuntu-R.ttf'
const
API fontBytes = await fetch(url).then(res
Help => res.arrayBuffer())
GitHub

const pdfDoc = await PDFDocument.create()

pdfDoc.registerFontkit(fontkit)
const customFont = await pdfDoc.embedFont(fontBytes)

const page = pdfDoc.addPage()

const text = 'This is text in an embedded font!'


const textSize = 35
const textWidth = customFont.widthOfTextAtSize(text, textSize)
const textHeight = customFont.heightAtSize(textSize)

page.drawText(text, {
x: 40,
y: 450,
size: textSize,
font: customFont,
color: rgb(0, 0.53, 0.71),
})
page.drawRectangle({
x: 40,
y: 450,
width: textWidth,
height: textHeight,
borderColor: rgb(1, 0, 0),
borderWidth: 1.5,
})

const pdfBytes = await pdfDoc.save()


}
PDF-LIB Search

API Help GitHub

Set Document Metadata Try the JSFiddle demo

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

async function setDocumentMetadata() {


const pdfDoc = await PDFDocument.create()
const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesR

const page = pdfDoc.addPage([500, 600])


page.setFont(timesRomanFont)
PDF-LIB
page.drawText('The Life of an Egg', { x: 60, y: Search
500, size: 50 })
page.drawText('An Epic Tale of Woe', { x: 125, y: 460, size: 25 })
API Help GitHub
// Note that these fields are visible in the "Document Properties"
// 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'))

const pdfBytes = await pdfDoc.save()


}
PDF-LIB Search

API Help GitHub

Read Document Metadata Try the JSFiddle demo

import { PDFDocument } from 'pdf-lib'

async function readDocumentMetadata() {


const url = 'https://pdf-lib.js.org/assets/with_cropbox.pdf'
const existingPdfBytes = await fetch(url).then(res => res.arrayBuf

const pdfDoc = await PDFDocument.load(existingPdfBytes, {


updateMetadata: false
PDF-LIB
}) Search

console.log('Title:',
API pdfDoc.getTitle())
Help GitHub
console.log('Author:', pdfDoc.getAuthor())
console.log('Subject:', pdfDoc.getSubject())
console.log('Creator:', pdfDoc.getCreator())
console.log('Keywords:', pdfDoc.getKeywords())
console.log('Producer:', pdfDoc.getProducer())
console.log('Creation Date:', pdfDoc.getCreationDate())
console.log('Modification Date:', pdfDoc.getModificationDate())
}

This script outputs the following:

Title: Microsoft Word - Basic Curriculum Vitae example.doc


Author: Administrator
Subject: undefined
Creator: PScript5.dll Version 5.2
Keywords: undefined
Producer: Acrobat Distiller 8.1.0 (Windows)
Creation Date: 2010-07-29T14:26:00.000Z
Modification Date: 2010-07-29T14:26:00.000Z

Draw SVG Paths Try the JSFiddle demo

import { PDFDocument, rgb } from 'pdf-lib'

async function drawSvgPaths() {


const svgPath =
'M 0,20 L 100,160 Q 130,200 150,120 C 190,-40 200,200 300,150 L
PDF-LIB
const pdfDoc = await PDFDocument.create() Search

const
API page = pdfDoc.addPage()
Help GitHub
page.moveTo(100, page.getHeight() - 5)

page.moveDown(25)
page.drawSvgPath(svgPath)

page.moveDown(200)
page.drawSvgPath(svgPath, { borderColor: rgb(0, 1, 0), borderWidth

page.moveDown(200)
page.drawSvgPath(svgPath, { color: rgb(1, 0, 0) })

page.moveDown(200)
page.drawSvgPath(svgPath, { scale: 0.5 })

const pdfBytes = await pdfDoc.save()


}
PDF-LIB Search

API Help GitHub

You might also like