Skip to content

happypdf / PDFDocument

Class: PDFDocument

Defined in: src/api/PDFDocument.ts:131

Represents a PDF document.

Properties

catalog

ts
readonly catalog: PDFCatalog;

Defined in: src/api/PDFDocument.ts:276

The catalog of this document.


context

ts
readonly context: PDFContext;

Defined in: src/api/PDFDocument.ts:273

The low-level context of this document.


isEncrypted

ts
readonly isEncrypted: boolean;

Defined in: src/api/PDFDocument.ts:279

Whether or not this document is encrypted.

Methods

addJavaScript()

ts
addJavaScript(name, script): void;

Defined in: src/api/PDFDocument.ts:1138

Add JavaScript to this document. The supplied script is executed when the document is opened. The script can be used to perform some operation when the document is opened (e.g. logging to the console), or it can be used to define a function that can be referenced later in a JavaScript action. For example:

js
// Show "Hello World!" in the console when the PDF is opened
pdfDoc.addJavaScript(
  'main',
  'console.show(); console.println("Hello World!");'
);

// Define a function named "foo" that can be called in JavaScript Actions
pdfDoc.addJavaScript(
  'foo',
  'function foo() { return "foo"; }'
);

See the JavaScript for Acrobat API Reference for details.

Parameters

ParameterTypeDescription
namestringThe name of the script. Must be unique per document.
scriptstringThe JavaScript to execute.

Returns

void


addPage()

ts
addPage(page?): PDFPage;

Defined in: src/api/PDFDocument.ts:970

Add a page to the end of this document. This method accepts three different value types for the page parameter:

TypeBehavior
undefinedCreate a new page and add it to the end of this document
[number, number]Create a new page with the given dimensions and add it to the end of this document
PDFPageAdd the existing page to the end of this document

For example:

js
// page=undefined
const newPage = pdfDoc.addPage()

// page=[number, number]
import { PageSizes } from 'pdf-lib'
const newPage1 = pdfDoc.addPage(PageSizes.A7)
const newPage2 = pdfDoc.addPage(PageSizes.Letter)
const newPage3 = pdfDoc.addPage([500, 750])

// page=PDFPage
const pdfDoc1 = await PDFDocument.create()
const pdfDoc2 = await PDFDocument.load(...)
const [existingPage] = await pdfDoc1.copyPages(pdfDoc2, [0])
pdfDoc1.addPage(existingPage)

Parameters

ParameterTypeDescription
page?[number, number] | PDFPageOptionally, the desired dimensions or existing page.

Returns

PDFPage

The newly created (or existing) page.


attach()

ts
attach(
   attachment, 
   name, 
options?): Promise<void>;

Defined in: src/api/PDFDocument.ts:1312

Add an attachment to this document. Attachments are visible in the "Attachments" panel of Adobe Acrobat and some other PDF readers. Any type of file can be added as an attachment. This includes, but is not limited to, .png, .jpg, .pdf, .csv, .docx, and .xlsx files.

The input data can be provided in multiple formats:

TypeContents
stringA base64 encoded string (or data URI) containing an attachment
Uint8ArrayThe raw bytes of an attachment
ArrayBufferThe raw bytes of an attachment

For example:

js
// attachment=string
await pdfDoc.attach('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD...', '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'),
})
await pdfDoc.attach('data:image/jpeg;base64,/9j/4AAQ...', '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'),
})

// attachment=Uint8Array
import fs from 'fs'
const uint8Array = fs.readFileSync('cat_riding_unicorn.jpg')
await pdfDoc.attach(uint8Array, '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'),
})

// attachment=ArrayBuffer
const url = 'https://pdf-lib.js.org/assets/cat_riding_unicorn.jpg'
const arrayBuffer = await fetch(url).then(res => res.arrayBuffer())
await pdfDoc.attach(arrayBuffer, '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'),
})

Parameters

ParameterTypeDescription
attachmentBinaryDataThe input data containing the file to be attached.
namestringThe name of the file to be attached.
optionsAttachmentOptions-

Returns

Promise&lt;void&gt;

Resolves when the attachment is complete.


commit()

ts
commit(options?): Promise<Uint8Array<ArrayBuffer>>;

Defined in: src/api/PDFDocument.ts:2112

Commit the current changes to the document as an incremental update. This allows you to save multiple incremental updates without reloading the PDF.

For example:

js
const pdfDoc = await PDFDocument.load(pdfBytes, { forIncrementalUpdate: true })

const page = pdfDoc.getPage(0)
page.drawText('First update')
const firstCommit = await pdfDoc.commit()

page.drawText('Second update', { y: 100 })
const secondCommit = await pdfDoc.commit()

Parameters

ParameterTypeDescription
optionsIncrementalSaveOptionsThe options to be used when committing changes.

Returns

Promise&lt;Uint8Array&lt;ArrayBuffer&gt;&gt;

Resolves with the complete PDF bytes including all updates.


convertToPDFA()

ts
convertToPDFA(options?): void;

Defined in: src/api/PDFDocument.ts:781

Convert this document into a PDF/A compliant document. PDF/A is an ISO-standardized subset of PDF designed for the long-term archiving of electronic documents. This method performs the structural changes that a PDF/A file requires:

  • A unique document identifier (/ID) is added to the trailer.
  • An OutputIntent referencing an embedded ICC color profile is added (the bundled sRGB profile is used by default).
  • An XMP metadata packet identifying the PDF/A conformance level is added and kept consistent with the document information dictionary.
  • The PDF header version is set appropriately for the targeted part.

For example:

js
const pdfDoc = await PDFDocument.load(existingPdfBytes)
pdfDoc.convertToPDFA({ conformance: '3B' })
const pdfBytes = await pdfDoc.save()

> This method does not, and cannot, guarantee full PDF/A compliance on > its own. PDF/A also forbids certain content (encryption, non-embedded > fonts, transparency for part 1, JavaScript, external references, etc.). > In particular, any text you draw must use an embedded font — the > 14 standard fonts are not embedded and are therefore not PDF/A compliant. > You are responsible for ensuring the document's content conforms. Validate > the result with a tool such as veraPDF.

> Unicode conformance ('2U' / '3U') is not verified. The U levels > additionally require every glyph in the document to have a Unicode > mapping (a ToUnicode CMap or equivalent). This method writes the > requested conformance level into the metadata but does not inspect > existing content to confirm the mappings are present — ensuring that is > the caller's responsibility.

> XMP is refreshed on save. After conversion, pdf-lib manages the > catalog /Metadata stream. On [[save]] / [[saveIncremental]] / > [[saveAsBase64]] it rebuilds the owned slice (Info-dict mirrors + > pdfaid) so Info and XMP stay equivalent as required by PDF/A, while > preserving foreign rdf:Description blocks (e.g. Factur-X / custom > schemas). Pass one-shot extras via options.extensions; they are written > into the initial packet and then preserved like any other foreign block.

> Ownership contract. After this method runs, pdf-lib owns the dc, > xmp, pdf, and pdfaid schemas. Add extra XMP with > options.extensions or by merging foreign rdf:Description elements > into the packet — those are preserved on sync. Hand-editing owned fields > in the XMP (e.g. dc:title) without going through the Info setters will > be overwritten.

Parameters

ParameterTypeDescription
optionsConvertToPDFAOptionsThe options to be used when converting the document.

Returns

void


copy()

ts
copy(): Promise<PDFDocument>;

Defined in: src/api/PDFDocument.ts:1078

Get a copy of this document.

For example:

js
const srcDoc = await PDFDocument.load(...)
const pdfDoc = await srcDoc.copy()

> NOTE: This method won't copy all information over to the new > document (acroforms, outlines, etc...).

Returns

Promise&lt;PDFDocument&gt;

Resolves with a copy this document.


copyPages()

ts
copyPages(srcDoc, indices): Promise<PDFPage[]>;

Defined in: src/api/PDFDocument.ts:1048

Copy pages from a source document into this document. Allows pages to be copied between different [[PDFDocument]] instances. For example:

js
const pdfDoc = await PDFDocument.create()
const srcDoc = await PDFDocument.load(...)

const copiedPages = await pdfDoc.copyPages(srcDoc, [0, 3, 89])
const [firstPage, fourthPage, ninetiethPage] = copiedPages;

pdfDoc.addPage(fourthPage)
pdfDoc.insertPage(0, ninetiethPage)
pdfDoc.addPage(firstPage)

Parameters

ParameterTypeDescription
srcDocPDFDocumentThe document from which pages should be copied.
indicesnumber[]The indices of the pages that should be copied.

Returns

Promise&lt;PDFPage[]&gt;

Resolves with an array of pages copied into this document.


create()

ts
static create(options?): Promise<PDFDocument>;

Defined in: src/api/PDFDocument.ts:260

Create a new [[PDFDocument]].

Parameters

ParameterType
optionsCreateOptions

Returns

Promise&lt;PDFDocument&gt;

Resolves with the newly created document.


detach()

ts
detach(name): void;

Defined in: src/api/PDFDocument.ts:1468

Parameters

ParameterType
namestring

Returns

void


embedFont()

ts
embedFont(font, options?): Promise<PDFFont>;

Defined in: src/api/PDFDocument.ts:1542

Embed a font into this document. The input data can be provided in multiple formats:

TypeContents
StandardFontsOne of the standard 14 fonts
stringA base64 encoded string (or data URI) containing a font
Uint8ArrayThe raw bytes of a font
ArrayBufferThe raw bytes of a font

For example:

js
// font=StandardFonts
import { StandardFonts } from 'pdf-lib'
const font1 = await pdfDoc.embedFont(StandardFonts.Helvetica)

// font=string
const font2 = await pdfDoc.embedFont('AAEAAAAVAQAABABQRFNJRx/upe...')
const font3 = await pdfDoc.embedFont('data:font/opentype;base64,AAEAAA...')

// font=Uint8Array
import fs from 'fs'
const font4 = await pdfDoc.embedFont(fs.readFileSync('Ubuntu-R.ttf'))

// font=ArrayBuffer
const url = 'https://pdf-lib.js.org/assets/ubuntu/Ubuntu-R.ttf'
const ubuntuBytes = await fetch(url).then(res => res.arrayBuffer())
const font5 = await pdfDoc.embedFont(ubuntuBytes)

See also: [[registerFontkit]]

Parameters

ParameterTypeDescription
fontstring | ArrayBuffer | ArrayBufferView&lt;ArrayBufferLike&gt;The input data for a font.
optionsEmbedFontOptionsThe options to be used when embedding the font.

Returns

Promise&lt;PDFFont&gt;

Resolves with the embedded font.


embedJpg()

ts
embedJpg(jpg): Promise<PDFImage>;

Defined in: src/api/PDFDocument.ts:1633

Embed a JPEG image into this document. The input data can be provided in multiple formats:

TypeContents
stringA base64 encoded string (or data URI) containing a JPEG image
Uint8ArrayThe raw bytes of a JPEG image
ArrayBufferThe raw bytes of a JPEG image

For example:

js
// jpg=string
const image1 = await pdfDoc.embedJpg('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD...')
const image2 = await pdfDoc.embedJpg('data:image/jpeg;base64,/9j/4AAQ...')

// jpg=Uint8Array
import fs from 'fs'
const uint8Array = fs.readFileSync('cat_riding_unicorn.jpg')
const image3 = await pdfDoc.embedJpg(uint8Array)

// jpg=ArrayBuffer
const url = 'https://pdf-lib.js.org/assets/cat_riding_unicorn.jpg'
const arrayBuffer = await fetch(url).then(res => res.arrayBuffer())
const image4 = await pdfDoc.embedJpg(arrayBuffer)

Parameters

ParameterTypeDescription
jpgBinaryDataThe input data for a JPEG image.

Returns

Promise&lt;PDFImage&gt;

Resolves with the embedded image.


embedPage()

ts
embedPage(
   page, 
   boundingBox?, 
transformationMatrix?): Promise<PDFEmbeddedPage>;

Defined in: src/api/PDFDocument.ts:1785

Embed a single PDF page into this document.

For example:

js
const pdfDoc = await PDFDocument.create()

const sourcePdfUrl = 'https://pdf-lib.js.org/assets/with_large_page_count.pdf'
const sourceBuffer = await fetch(sourcePdfUrl).then((res) => res.arrayBuffer())
const sourcePdfDoc = await PDFDocument.load(sourceBuffer)
const sourcePdfPage = sourcePdfDoc.getPages()[73]

const embeddedPage = await pdfDoc.embedPage(
  sourcePdfPage,

  // Clip a section of the source page so that we only embed part of it
  { left: 100, right: 450, bottom: 330, top: 570 },

  // Translate all drawings of the embedded page by (10, 200) units
  [1, 0, 0, 1, 10, 200],
)

Parameters

ParameterTypeDescription
pagePDFPageThe page to be embedded.
boundingBox?PageBoundingBoxOptionally, an area of the source page that should be embedded (defaults to entire page).
transformationMatrix?TransformationMatrixOptionally, a transformation matrix that is always applied to the embedded page anywhere it is drawn.

Returns

Promise&lt;PDFEmbeddedPage&gt;

Resolves with the embedded pdf page.


embedPages()

ts
embedPages(
   pages, 
   boundingBoxes?, 
transformationMatrices?): Promise<PDFEmbeddedPage[]>;

Defined in: src/api/PDFDocument.ts:1827

Embed one or more PDF pages into this document.

For example:

js
const pdfDoc = await PDFDocument.create()

const sourcePdfUrl = 'https://pdf-lib.js.org/assets/with_large_page_count.pdf'
const sourceBuffer = await fetch(sourcePdfUrl).then((res) => res.arrayBuffer())
const sourcePdfDoc = await PDFDocument.load(sourceBuffer)

const page1 = sourcePdfDoc.getPages()[0]
const page2 = sourcePdfDoc.getPages()[52]
const page3 = sourcePdfDoc.getPages()[73]

const embeddedPages = await pdfDoc.embedPages([page1, page2, page3])

Parameters

ParameterTypeDefault valueDescription
pagesPDFPage[]undefined-
boundingBoxes(PageBoundingBox | undefined)[][]Optionally, an array of clipping boundaries - one for each page (defaults to entirety of each page).
transformationMatrices( | TransformationMatrix | undefined)[][]Optionally, an array of transformation matrices - one for each page (each page's transformation will apply anywhere it is drawn).

Returns

Promise&lt;PDFEmbeddedPage[]&gt;

Resolves with an array of the embedded pdf pages.


embedPdf()

ts
embedPdf(pdf, indices?): Promise<PDFEmbeddedPage[]>;

Defined in: src/api/PDFDocument.ts:1733

Embed one or more PDF pages into this document.

For example:

js
const pdfDoc = await PDFDocument.create()

const sourcePdfUrl = 'https://pdf-lib.js.org/assets/with_large_page_count.pdf'
const sourcePdf = await fetch(sourcePdfUrl).then((res) => res.arrayBuffer())

// Embed page 74 of `sourcePdf` into `pdfDoc`
const [embeddedPage] = await pdfDoc.embedPdf(sourcePdf, [73])

See [[PDFDocument.load]] for examples of the allowed input data formats.

Parameters

ParameterTypeDescription
pdfBinaryData | PDFDocumentThe input data containing a PDF document.
indicesnumber[]The indices of the pages that should be embedded.

Returns

Promise&lt;PDFEmbeddedPage[]&gt;

Resolves with an array of the embedded pages.


embedPng()

ts
embedPng(png): Promise<PDFImage>;

Defined in: src/api/PDFDocument.ts:1673

Embed a PNG image into this document. The input data can be provided in multiple formats:

TypeContents
stringA base64 encoded string (or data URI) containing a PNG image
Uint8ArrayThe raw bytes of a PNG image
ArrayBufferThe raw bytes of a PNG image

For example:

js
// png=string
const image1 = await pdfDoc.embedPng('iVBORw0KGgoAAAANSUhEUgAAAlgAAAF3...')
const image2 = await pdfDoc.embedPng('data:image/png;base64,iVBORw0KGg...')

// png=Uint8Array
import fs from 'fs'
const uint8Array = fs.readFileSync('small_mario.png')
const image3 = await pdfDoc.embedPng(uint8Array)

// png=ArrayBuffer
const url = 'https://pdf-lib.js.org/assets/small_mario.png'
const arrayBuffer = await fetch(url).then(res => res.arrayBuffer())
const image4 = await pdfDoc.embedPng(arrayBuffer)

Parameters

ParameterTypeDescription
pngBinaryDataThe input data for a PNG image.

Returns

Promise&lt;PDFImage&gt;

Resolves with the embedded image.


embedStandardFont()

ts
embedStandardFont(font, customName?): PDFFont;

Defined in: src/api/PDFDocument.ts:1588

Embed a standard font into this document. For example:

js
import { StandardFonts } from 'pdf-lib'
const helveticaFont = pdfDoc.embedFont(StandardFonts.Helvetica)

Parameters

ParameterTypeDescription
fontStandardFontsThe standard font to be embedded.
customName?stringThe name to be used when embedding the font.

Returns

PDFFont

The embedded font.


embedSvg()

ts
embedSvg(svg): Promise<PDFSvg>;

Defined in: src/api/PDFDocument.ts:1683

Parameters

ParameterType
svgstring

Returns

Promise&lt;PDFSvg&gt;


encrypt()

ts
encrypt(options): void;

Defined in: src/api/PDFDocument.ts:1866

Parameters

ParameterType
optionsSecurityOptions

Returns

void


findPageForAnnotationRef()

ts
findPageForAnnotationRef(ref): PDFPage | undefined;

Defined in: src/api/PDFDocument.ts:2062

Parameters

ParameterType
refPDFRef

Returns

PDFPage | undefined


flush()

ts
flush(): Promise<void>;

Defined in: src/api/PDFDocument.ts:1887

> NOTE: You shouldn't need to call this method directly. The [[save]] > and [[saveAsBase64]] methods will automatically ensure that all embedded > assets are flushed before serializing the document.

Flush all embedded fonts, PDF pages, and images to this document's [[context]].

Returns

Promise&lt;void&gt;

Resolves when the flush is complete.


getAttachments()

ts
getAttachments(): PDFAttachment[];

Defined in: src/api/PDFDocument.ts:1461

Get all attachments that are embedded in this document.

Returns

PDFAttachment[]

Array of attachments with name and data


getAuthor()

ts
getAuthor(): string | undefined;

Defined in: src/api/PDFDocument.ts:469

Get this document's author metadata. The author appears in the "Document Properties" section of most PDF readers. For example:

js
const author = pdfDoc.getAuthor()

Returns

string | undefined

A string containing the author of this document, if it has one.


getCreationDate()

ts
getCreationDate(): Date | undefined;

Defined in: src/api/PDFDocument.ts:561

Get this document's creation date metadata. The creation date appears in the "Document Properties" section of most PDF readers. For example:

js
const creationDate = pdfDoc.getCreationDate()

Returns

Date | undefined

A Date containing the creation date of this document, if it has one.


getCreator()

ts
getCreator(): string | undefined;

Defined in: src/api/PDFDocument.ts:514

Get this document's creator metadata. The creator appears in the "Document Properties" section of most PDF readers. For example:

js
const creator = pdfDoc.getCreator()

Returns

string | undefined

A string containing the creator of this document, if it has one.


getDocumentJavaScripts()

ts
getDocumentJavaScripts(): {
  name: string;
  script: string;
}[];

Defined in: src/api/PDFDocument.ts:1161

Get all document-level JavaScript scripts from the document's Names dictionary. These scripts are executed when the document is opened. For example:

js
const scripts = pdfDoc.getDocumentJavaScripts()
scripts.forEach(({ name, script }) => {
  console.log(`Script "${name}":`, script)
})

Returns

{ name: string; script: string; }[]

An array of objects containing script names and their JavaScript code.


getForm()

ts
getForm(): PDFForm;

Defined in: src/api/PDFDocument.ts:374

Get the [[PDFForm]] containing all interactive fields for this document. For example:

js
const form = pdfDoc.getForm()
const fields = form.getFields()
fields.forEach(field => {
  const type = field.constructor.name
  const name = field.getName()
  console.log(`${type}: ${name}`)
})

XFA caveat: if the document contains XFA form data and it was not loaded with preserveXFA: true, calling this method strips the XFA data (pdf-lib cannot render or edit XFA and removes it to keep the AcroForm consistent). Because the XFA read/write helpers ([[getXFAJavaScripts]], [[setXFAJavaScript]]) operate on that same data, call them beforegetForm() — or load with preserveXFA: true otherwise the XFA will already be gone.

Returns

PDFForm

The form for this document.


getKeywords()

ts
getKeywords(): string | undefined;

Defined in: src/api/PDFDocument.ts:499

Get this document's keywords metadata. The keywords appear in the "Document Properties" section of most PDF readers. For example:

js
const keywords = pdfDoc.getKeywords()

Returns

string | undefined

A string containing the keywords of this document, if it has any.


getLanguage()

ts
getLanguage(): string | undefined;

Defined in: src/api/PDFDocument.ts:545

Get this document's language metadata. The language appears in the "Document Properties" section of most PDF readers. For example:

js
const language = pdfDoc.getLanguage()

Returns

string | undefined

A string containing the RFC 3066 Language-Tag of this document, if it has one.


getModificationDate()

ts
getModificationDate(): Date | undefined;

Defined in: src/api/PDFDocument.ts:578

Get this document's modification date metadata. The modification date appears in the "Document Properties" section of most PDF readers. For example:

js
const modification = pdfDoc.getModificationDate()

Returns

Date | undefined

A Date containing the modification date of this document, if it has one.


getOptionalContentGroups()

ts
getOptionalContentGroups(): PDFOptionalContentGroup[];

Defined in: src/api/PDFDocument.ts:396

List this document's optional content groups (PDF "layers"), if any. Visibility reflects the default configuration (/OCProperties /D). Returns an empty array when the document has no /OCProperties.

For example:

js
const layers = pdfDoc.getOptionalContentGroups()
layers.forEach((layer) => console.log(layer.name, layer.visible))

Returns

PDFOptionalContentGroup[]


getPage()

ts
getPage(index): PDFPage;

Defined in: src/api/PDFDocument.ts:892

Get the page rendered at a particular index of the document. For example:

js
pdfDoc.getPage(0)   // The first page of the document
pdfDoc.getPage(2)   // The third page of the document
pdfDoc.getPage(197) // The 198th page of the document

Parameters

ParameterType
indexnumber

Returns

PDFPage

The [[PDFPage]] rendered at the given index of the document.


getPageCount()

ts
getPageCount(): number;

Defined in: src/api/PDFDocument.ts:862

Get the number of pages contained in this document. For example:

js
const totalPages = pdfDoc.getPageCount()

Returns

number

The number of pages in this document.


getPageIndices()

ts
getPageIndices(): number[];

Defined in: src/api/PDFDocument.ts:913

Get an array of indices for all the pages contained in this document. The array will contain a range of integers from 0..pdfDoc.getPageCount() - 1. For example:

js
const pdfDoc = await PDFDocument.create()
pdfDoc.addPage()
pdfDoc.addPage()
pdfDoc.addPage()

const indices = pdfDoc.getPageIndices()
indices // => [0, 1, 2]

Returns

number[]

An array of indices for all pages contained in this document.


getPages()

ts
getPages(): PDFPage[];

Defined in: src/api/PDFDocument.ts:879

Get an array of all the pages contained in this document. The pages are stored in the array in the same order that they are rendered in the document. For example:

js
const pages = pdfDoc.getPages()
pages[0]   // The first page of the document
pages[2]   // The third page of the document
pages[197] // The 198th page of the document

Returns

PDFPage[]

An array of all the pages contained in this document.


getProducer()

ts
getProducer(): string | undefined;

Defined in: src/api/PDFDocument.ts:529

Get this document's producer metadata. The producer appears in the "Document Properties" section of most PDF readers. For example:

js
const producer = pdfDoc.getProducer()

Returns

string | undefined

A string containing the producer of this document, if it has one.


getSubject()

ts
getSubject(): string | undefined;

Defined in: src/api/PDFDocument.ts:484

Get this document's subject metadata. The subject appears in the "Document Properties" section of most PDF readers. For example:

js
const subject = pdfDoc.getSubject()

Returns

string | undefined

A string containing the subject of this document, if it has one.


getTitle()

ts
getTitle(): string | undefined;

Defined in: src/api/PDFDocument.ts:454

Get this document's title metadata. The title appears in the "Document Properties" section of most PDF readers. For example:

js
const title = pdfDoc.getTitle()

Returns

string | undefined

A string containing the title of this document, if it has one.


getXFAJavaScripts()

ts
getXFAJavaScripts(): {
  event: string;
  field: string;
  script: string;
}[];

Defined in: src/api/PDFDocument.ts:1224

Get all JavaScript from XFA form template. XFA forms can contain JavaScript in <script> elements within the template XML. For example:

js
const xfaScripts = pdfDoc.getXFAJavaScripts()
xfaScripts.forEach(({ field, event, script }) => {
  console.log(`Field "${field}" on ${event}:`, script)
})

Note: load the document with preserveXFA: true and call this before [[getForm]], which strips XFA data when preserveXFA is not set.

Returns

{ event: string; field: string; script: string; }[]

An array of objects containing field names, events, and JavaScript code.


insertPage()

ts
insertPage(index, page?): PDFPage;

Defined in: src/api/PDFDocument.ts:1007

Insert a page at a given index within this document. This method accepts three different value types for the page parameter:

TypeBehavior
undefinedCreate a new page and insert it into this document
[number, number]Create a new page with the given dimensions and insert it into this document
PDFPageInsert the existing page into this document

For example:

js
// page=undefined
const newPage = pdfDoc.insertPage(2)

// page=[number, number]
import { PageSizes } from 'pdf-lib'
const newPage1 = pdfDoc.insertPage(2, PageSizes.A7)
const newPage2 = pdfDoc.insertPage(0, PageSizes.Letter)
const newPage3 = pdfDoc.insertPage(198, [500, 750])

// page=PDFPage
const pdfDoc1 = await PDFDocument.create()
const pdfDoc2 = await PDFDocument.load(...)
const [existingPage] = await pdfDoc1.copyPages(pdfDoc2, [0])
pdfDoc1.insertPage(0, existingPage)

Parameters

ParameterTypeDescription
indexnumberThe index at which the page should be inserted (zero-based).
page?[number, number] | PDFPageOptionally, the desired dimensions or existing page.

Returns

PDFPage

The newly created (or existing) page.


load()

ts
static load(pdf, options?): Promise<PDFDocument>;

Defined in: src/api/PDFDocument.ts:185

Load an existing [[PDFDocument]]. The input data can be provided in multiple formats:

TypeContents
stringA base64 encoded string (or data URI) containing a PDF
Uint8ArrayThe raw bytes of a PDF
ArrayBufferThe raw bytes of a PDF
ArrayBufferViewThe raw bytes of a PDF (includes Node.js Buffer)

For example:

js
import { PDFDocument } from 'pdf-lib'

// pdf=string
const base64 =
 'JVBERi0xLjcKJYGBgYEKCjUgMCBvYmoKPDwKL0ZpbHRlciAvRmxhdGVEZWNvZGUKL0xlbm' +
 'd0aCAxMDQKPj4Kc3RyZWFtCniccwrhMlAAwaJ0Ln2P1Jyy1JLM5ERdc0MjCwUjE4WQNC4Q' +
 '6cNlCFZkqGCqYGSqEJLLZWNuYGZiZmbkYuZsZmlmZGRgZmluDCQNzc3NTM2NzdzMXMxMjQ' +
 'ztFEKyuEK0uFxDuAAOERdVCmVuZHN0cmVhbQplbmRvYmoKCjYgMCBvYmoKPDwKL0ZpbHRl' +
 'ciAvRmxhdGVEZWNvZGUKL1R5cGUgL09ialN0bQovTiA0Ci9GaXJzdCAyMAovTGVuZ3RoID' +
 'IxNQo+PgpzdHJlYW0KeJxVj9GqwjAMhu/zFHkBzTo3nCCCiiKIHPEICuJF3cKoSCu2E8/b' +
 '20wPIr1p8v9/8kVhgilmGfawX2CGaVrgcAi0/bsy0lrX7IGWpvJ4iJYEN3gEmrrGBlQwGs' +
 'HHO9VBX1wNrxAqMX87RBD5xpJuddqwd82tjAHxzV1U5LPgy52DKXWnr1Lheg+j/c/pzGVr' +
 'iqV0VlwZPXGPCJjElw/ybkwUmeoWgxesDXGhHJC/D/iikp1Av80ptKU0FdBEe25pPihAM1' +
 'u6ytgaaWfs2Hrz35CJT1+EWmAKZW5kc3RyZWFtCmVuZG9iagoKNyAwIG9iago8PAovU2l6' +
 'ZSA4Ci9Sb290IDIgMCBSCi9GaWx0ZXIgL0ZsYXRlRGVjb2RlCi9UeXBlIC9YUmVmCi9MZW' +
 '5ndGggMzgKL1cgWyAxIDIgMiBdCi9JbmRleCBbIDAgOCBdCj4+CnN0cmVhbQp4nBXEwREA' +
 'EBAEsCwz3vrvRmOOyyOoGhZdutHN2MT55fIAVocD+AplbmRzdHJlYW0KZW5kb2JqCgpzdG' +
 'FydHhyZWYKNTEwCiUlRU9G'

const dataUri = 'data:application/pdf;base64,' + base64

const pdfDoc1 = await PDFDocument.load(base64)
const pdfDoc2 = await PDFDocument.load(dataUri)

// pdf=Uint8Array / Node Buffer
import fs from 'fs'
const bytes = fs.readFileSync('with_update_sections.pdf')
const pdfDoc3 = await PDFDocument.load(bytes)

// pdf=ArrayBuffer
const url = 'https://pdf-lib.js.org/assets/with_update_sections.pdf'
const arrayBuffer = await fetch(url).then(res => res.arrayBuffer())
const pdfDoc4 = await PDFDocument.load(arrayBuffer)

Parameters

ParameterTypeDescription
pdfBinaryDataThe input data containing a PDF document.
optionsLoadOptionsThe options to be used when loading the document.

Returns

Promise&lt;PDFDocument&gt;

Resolves with a document loaded from the input.


registerFontkit()

ts
registerFontkit(fontkit): void;

Defined in: src/api/PDFDocument.ts:347

Register a font engine instance for backwards compatibility. This is no longer required before embedding custom fonts, which are now shaped with the bundled HarfBuzz engine.

> You do not need to call this method to embed standard fonts.

For example:

js
import { PDFDocument } from '@cantoo/pdf-lib'
const pdfDoc = await PDFDocument.create()
pdfDoc.registerFontkit({})

Parameters

ParameterTypeDescription
fontkitanyRetained for backwards compatibility.

Returns

void


removePage()

ts
removePage(index): void;

Defined in: src/api/PDFDocument.ts:928

Remove the page at a given index from this document. For example:

js
pdfDoc.removePage(0)   // Remove the first page of the document
pdfDoc.removePage(2)   // Remove the third page of the document
pdfDoc.removePage(197) // Remove the 198th page of the document

Once a page has been removed, it will no longer be rendered at that index in the document.

Parameters

ParameterTypeDescription
indexnumberThe index of the page to be removed.

Returns

void


save()

ts
save(options?): Promise<Uint8Array<ArrayBuffer>>;

Defined in: src/api/PDFDocument.ts:1911

Serialize this document to an array of bytes making up a PDF file. For example:

js
const pdfBytes = await pdfDoc.save()

There are a number of things you can do with the serialized document, depending on the JavaScript environment you're running in:

  • Write it to a file in Node or React Native
  • Download it as a Blob in the browser
  • Render it in an iframe

Parameters

ParameterTypeDescription
optionsSaveOptionsThe options to be used when saving the document.

Returns

Promise&lt;Uint8Array&lt;ArrayBuffer&gt;&gt;

Resolves with the bytes of the serialized document.


saveAsBase64()

ts
saveAsBase64(options?): Promise<string>;

Defined in: src/api/PDFDocument.ts:2054

Serialize this document to a base64 encoded string or data URI making up a PDF file. For example:

js
const base64String = await pdfDoc.saveAsBase64()
base64String // => 'JVBERi0xLjcKJYGBgYEKC...'

const base64DataUri = await pdfDoc.saveAsBase64({ dataUri: true })
base64DataUri // => 'data:application/pdf;base64,JVBERi0xLjcKJYGBgYEKC...'

Parameters

ParameterTypeDescription
optionsBase64SaveOptionsThe options to be used when saving the document.

Returns

Promise&lt;string&gt;

Resolves with a base64 encoded string or data URI of the serialized document.


saveIncremental()

ts
saveIncremental(snapshot, options?): Promise<Uint8Array<ArrayBuffer>>;

Defined in: src/api/PDFDocument.ts:2003

Serialize only the changes to this document to an array of bytes making up a PDF file. For example:

js
const snapshot = pdfDoc.takeSnapshot();
...
const pdfBytes = await pdfDoc.saveIncremental(snapshot);

Similar to [[save]] function. The changes are saved in an incremental way, the result buffer will contain only the differences

Parameters

ParameterTypeDescription
snapshotDocumentSnapshotThe snapshot to be used when saving the document.
optionsIncrementalSaveOptionsThe options to be used when saving the document.

Returns

Promise&lt;Uint8Array&lt;ArrayBuffer&gt;&gt;

Resolves with the bytes of the serialized document.


setAuthor()

ts
setAuthor(author): void;

Defined in: src/api/PDFDocument.ts:622

Set this document's author metadata. The author will appear in the "Document Properties" section of most PDF readers. For example:

js
pdfDoc.setAuthor('Humpty Dumpty')

Parameters

ParameterTypeDescription
authorstringThe author of this document.

Returns

void


setCreationDate()

ts
setCreationDate(creationDate): void;

Defined in: src/api/PDFDocument.ts:708

Set this document's creation date metadata. The creation date will appear in the "Document Properties" section of most PDF readers. For example:

js
pdfDoc.setCreationDate(new Date())

Parameters

ParameterTypeDescription
creationDateDateThe date this document was created.

Returns

void


setCreator()

ts
setCreator(creator): void;

Defined in: src/api/PDFDocument.ts:664

Set this document's creator metadata. The creator will appear in the "Document Properties" section of most PDF readers. For example:

js
pdfDoc.setCreator('PDF App 9000 🤖')

Parameters

ParameterTypeDescription
creatorstringThe creator of this document.

Returns

void


setKeywords()

ts
setKeywords(keywords): void;

Defined in: src/api/PDFDocument.ts:650

Set this document's keyword metadata. These keywords will appear in the "Document Properties" section of most PDF readers. For example:

js
pdfDoc.setKeywords(['eggs', 'wall', 'fall', 'king', 'horses', 'men'])

Parameters

ParameterTypeDescription
keywordsstring[]An array of keywords associated with this document.

Returns

void


setLanguage()

ts
setLanguage(language): void;

Defined in: src/api/PDFDocument.ts:694

Set this document's language metadata. The language will appear in the "Document Properties" section of some PDF readers. For example:

js
pdfDoc.setLanguage('en-us')

Parameters

ParameterTypeDescription
languagestringAn RFC 3066 Language-Tag denoting the language of this document, or an empty string if the language is unknown.

Returns

void


setModificationDate()

ts
setModificationDate(modificationDate): void;

Defined in: src/api/PDFDocument.ts:723

Set this document's modification date metadata. The modification date will appear in the "Document Properties" section of most PDF readers. For example:

js
pdfDoc.setModificationDate(new Date())

Parameters

ParameterTypeDescription
modificationDateDateThe date this document was last modified.

Returns

void


setOptionalContentGroupVisibility()

Call Signature

ts
setOptionalContentGroupVisibility(nameOrRef, visible): void;

Defined in: src/api/PDFDocument.ts:417

Set the default visibility of an optional content group (layer) so PDF readers open the file with that layer on or off. Matches by layer name (all groups with that name) or by indirect PDFRef.

For example:

js
pdfDoc.setOptionalContentGroupVisibility('Watermark', false)
pdfDoc.setOptionalContentGroupVisibility([
  { name: 'Notes', visible: false },
  { ref: layers[0].ref, visible: true },
])

This updates /OCProperties /D (/ON, /OFF, /BaseState) only. It does not remove layer content from page streams.

Parameters
ParameterType
nameOrRefstring | PDFRef
visibleboolean
Returns

void

Call Signature

ts
setOptionalContentGroupVisibility(updates): void;

Defined in: src/api/PDFDocument.ts:421

Set the default visibility of an optional content group (layer) so PDF readers open the file with that layer on or off. Matches by layer name (all groups with that name) or by indirect PDFRef.

For example:

js
pdfDoc.setOptionalContentGroupVisibility('Watermark', false)
pdfDoc.setOptionalContentGroupVisibility([
  { name: 'Notes', visible: false },
  { ref: layers[0].ref, visible: true },
])

This updates /OCProperties /D (/ON, /OFF, /BaseState) only. It does not remove layer content from page streams.

Parameters
ParameterType
updatesOptionalContentVisibilityUpdate[]
Returns

void


setProducer()

ts
setProducer(producer): void;

Defined in: src/api/PDFDocument.ts:678

Set this document's producer metadata. The producer will appear in the "Document Properties" section of most PDF readers. For example:

js
pdfDoc.setProducer('PDF App 9000 🤖')

Parameters

ParameterTypeDescription
producerstringThe producer of this document.

Returns

void


setSubject()

ts
setSubject(subject): void;

Defined in: src/api/PDFDocument.ts:636

Set this document's subject metadata. The subject will appear in the "Document Properties" section of most PDF readers. For example:

js
pdfDoc.setSubject('📘 An Epic Tale of Woe 📖')

Parameters

ParameterTypeDescription
subjectstringThe subject of this document.

Returns

void


setTitle()

ts
setTitle(title, options?): void;

Defined in: src/api/PDFDocument.ts:602

Set this document's title metadata. The title will appear in the "Document Properties" section of most PDF readers. For example:

js
pdfDoc.setTitle('🥚 The Life of an Egg 🍳')

To display the title in the window's title bar, set the showInWindowTitleBar option to true (works for most PDF readers). For example:

js
pdfDoc.setTitle('🥚 The Life of an Egg 🍳', { showInWindowTitleBar: true })

Parameters

ParameterTypeDescription
titlestringThe title of this document.
options?SetTitleOptionsThe options to be used when setting the title.

Returns

void


setXFAJavaScript()

ts
setXFAJavaScript(
   fieldName, 
   eventName, 
   newScript): void;

Defined in: src/api/PDFDocument.ts:1243

Modify JavaScript in XFA form template for a specific field and event. For example:

js
pdfDoc.setXFAJavaScript('import', 'event__click', 'console.println("Modified!");')

Parameters

ParameterTypeDescription
fieldNamestringThe name of the field containing the script
eventNamestringThe name of the event (e.g., 'event__click', 'calculate')
newScriptstringThe new JavaScript code to set

Returns

void

Throws

Error if the XFA form is not found, the script location is not found, or decoding fails

Note: load the document with preserveXFA: true and call this before [[getForm]], which strips XFA data when preserveXFA is not set.


takeSnapshot()

ts
takeSnapshot(): DocumentSnapshot;

Defined in: src/api/PDFDocument.ts:2076

Returns

DocumentSnapshot

MIT Licensed. A fork of pdf-lib.