### Install unpdf Source: https://github.com/unjs/unpdf/blob/main/README.md Install unpdf using pnpm or npm. ```bash # pnpm pnpm add unpdf # npm npm install unpdf ``` -------------------------------- ### Override PDF.js Build with definePDFJSModule Source: https://context7.com/unjs/unpdf/llms.txt Register a custom PDF.js resolver before any other unpdf function. This example shows how to use the official pdfjs-dist package instead of the bundled serverless build. Ensure you have installed `pdfjs-dist`. ```typescript import { definePDFJSModule, extractText, getDocumentProxy } from 'unpdf' // Use the official pdfjs-dist instead of the bundled serverless build. // Requires: npm install pdfjs-dist // WARNING: pdfjs-dist v5.x requires Promise.withResolvers (Node >= 22). await definePDFJSModule(() => import('pdfjs-dist')) const buffer = await fetch('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf') .then(res => res.arrayBuffer()) const pdf = await getDocumentProxy(new Uint8Array(buffer)) const { totalPages, text } = await extractText(pdf, { mergePages: true }) console.log(`Pages: ${totalPages}`) // => Pages: 1 console.log(text) // => "Dummy PDF file" ``` -------------------------------- ### Load PDF and Reuse Proxy with getDocumentProxy Source: https://context7.com/unjs/unpdf/llms.txt Parses binary PDF data into a `PDFDocumentProxy` for efficient multi-operation workflows. This example demonstrates reusing the same proxy for metadata extraction and text extraction. Custom options can override default behaviors like font rendering. ```typescript import { readFile } from 'node:fs/promises' import { extractLinks, extractText, getDocumentProxy, getMeta } from 'unpdf' const buffer = await readFile('./document.pdf') const pdf = await getDocumentProxy(new Uint8Array(buffer)) // Reuse the same proxy for multiple operations const { info } = await getMeta(pdf) const { text } = await extractText(pdf, { mergePages: true }) const { links } = await extractLinks(pdf) console.log(`Author: ${info.Author}`) // => Author: Evangelos Vlachogiannis console.log(`Text preview: ${text.slice(0, 50)}`) // => Text preview: Dummy PDF file console.log(`Links found: ${links.length}`) // Custom options – override font rendering for accurate output const pdfCustom = await getDocumentProxy(new Uint8Array(buffer), { disableFontFace: false, standardFontDataUrl: 'https://unpkg.com/pdfjs-dist@latest/standard_fonts/' }) ``` -------------------------------- ### Render PDF Page to Image (Node.js/Browser) Source: https://github.com/unjs/unpdf/blob/main/README.md Renders a specific page of a PDF document into an ArrayBuffer representing a PNG image. Ensure the official PDF.js build is used and `@napi-rs/canvas` is installed for Node.js environments. The `definePDFJSModule` function must be called to set up PDF.js. ```typescript import { definePDFJSModule, renderPageAsImage } from 'unpdf' // Use the official PDF.js build await definePDFJSModule(() => import('pdfjs-dist')) const pdf = await readFile('./dummy.pdf') const buffer = new Uint8Array(pdf) const pageNumber = 1 const result = await renderPageAsImage(buffer, pageNumber, { canvasImport: () => import('@napi-rs/canvas'), scale: 2, }) await writeFile('dummy-page-1.png', new Uint8Array(result)) ``` -------------------------------- ### Get Resolved PDF.js Module Source: https://github.com/unjs/unpdf/blob/main/README.md Provides access to the resolved PDF.js module, enabling direct interaction with the PDF.js API. It defaults to the serverless build if no custom module has been defined. ```APIDOC ## Get Resolved PDF.js Module ### Description Returns the resolved PDF.js module, allowing direct use of the PDF.js API. It defaults to the serverless build if no custom PDF.js module has been defined using `definePDFJSModule`. ### Method `getResolvedPDFJS(): Promise` ### Parameters None ### Request Example ```ts import { getResolvedPDFJS } from 'unpdf' const { version } = await getResolvedPDFJS() console.log(`Using PDF.js version: ${version}`) ``` ### Response #### Success Response (200) - **PDFJS** (object) - The resolved PDF.js module, providing access to its API. #### Response Example ```json { "version": "5.6.205" } ``` ``` -------------------------------- ### Get PDF Metadata Using PDF.js API Source: https://github.com/unjs/unpdf/blob/main/README.md Loads a PDF file using the PDF.js API and retrieves its metadata. Ensure the file path is correct. ```typescript import { readFile } from 'node:fs/promises' import { getResolvedPDFJS } from 'unpdf' const { getDocument } = await getResolvedPDFJS() const data = await readFile('./dummy.pdf') const document = await getDocument(new Uint8Array(data)).promise console.log(await document.getMetadata()) ``` -------------------------------- ### Access PDF.js API Directly Source: https://github.com/unjs/unpdf/blob/main/README.md Get the resolved PDF.js module to use its API directly. If no custom build is defined, the serverless build is used by default. ```typescript import { getResolvedPDFJS } from 'unpdf' const { version } = await getResolvedPDFJS() ``` -------------------------------- ### Extract Plain Text from PDF with extractText Source: https://context7.com/unjs/unpdf/llms.txt Use extractText to get all text content from a PDF. By default, it returns an array of per-page strings. Set mergePages to true to get a single concatenated string with collapsed whitespace. ```typescript import { readFile } from 'node:fs/promises' import { extractText, getDocumentProxy } from 'unpdf' const buffer = await readFile('./document.pdf') const pdf = await getDocumentProxy(new Uint8Array(buffer)) // Per-page text array (default) const { totalPages, text: pages } = await extractText(pdf) console.log(`Total pages: ${totalPages}`) // => Total pages: 3 pages.forEach((pageText, i) => { console.log(`Page ${i + 1}:`, pageText.slice(0, 80)) }) // Merged into a single string (ideal for AI summarization) const { text } = await extractText(pdf, { mergePages: true }) console.log(typeof text) // => "string" console.log(text.slice(0, 120)) // => "Dummy PDF file" // Works equally on remote PDFs const remoteBuffer = await fetch('https://example.com/report.pdf').then(r => r.arrayBuffer()) const { text: remoteText } = await extractText(new Uint8Array(remoteBuffer), { mergePages: true }) ``` -------------------------------- ### Get PDF Metadata Source: https://github.com/unjs/unpdf/blob/main/README.md Extracts metadata information from a PDF document. Optionally, date properties within the metadata can be parsed into JavaScript Date objects. ```APIDOC ## Get PDF Metadata ### Description Extracts metadata and information from a PDF document. Supports parsing date fields into `Date` objects if the `parseDates` option is enabled. ### Method `getMeta(data: DocumentInitParameters['data'] | PDFDocumentProxy, options?: { parseDates?: boolean }): Promise<{ info: Record; metadata: Record }>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts import { getMeta } from 'unpdf' import { readFile } from 'node:fs/promises' const data = await readFile('./document.pdf') const { info, metadata } = await getMeta(new Uint8Array(data), { parseDates: true }) console.log('Info:', info) console.log('Metadata:', metadata) ``` ### Response #### Success Response (200) - **info** (Record) - General information about the PDF. - **metadata** (Record) - Extracted metadata from the PDF. #### Response Example ```json { "info": { "PDFFormatVersion": "1.5", "IsLinearized": true }, "metadata": { "CreationDate": "D:20230101T100000Z", "ModDate": "D:20230101T110000Z" } } ``` ``` -------------------------------- ### Extract Structured Text Items with extractTextItems Source: https://context7.com/unjs/unpdf/llms.txt Use extractTextItems to get rich text item objects per page, including position, dimensions, font details, and reading direction. This is useful for layout analysis or building bounding-box overlays. ```typescript import { readFile } from 'node:fs/promises' import { extractTextItems, getDocumentProxy } from 'unpdf' import type { StructuredTextItem } from 'unpdf' const buffer = await readFile('./document.pdf') const pdf = await getDocumentProxy(new Uint8Array(buffer)) const { totalPages, items } = await extractTextItems(pdf) console.log(`Pages: ${totalPages}`) // => Pages: 1 // items is a StructuredTextItem[][] — one array per page const firstPageItems: StructuredTextItem[] = items[0]! const firstItem = firstPageItems[0]! console.log(firstItem) // => { // str: "Dummy PDF file", // x: 56.8, // y: 758.1, // width: 123.41, // height: 16.1, // fontSize: 16.1, // fontFamily: "sans-serif", // dir: "ltr", // hasEOL: false // } // Example: collect all text larger than 14pt (likely headings) const headings = firstPageItems.filter(item => item.fontSize > 14) console.log(headings.map(h => h.str)) // => ["Dummy PDF file"] ``` -------------------------------- ### Customizing getDocumentProxy Options Source: https://github.com/unjs/unpdf/blob/main/README.md Demonstrates how to provide custom options to `getDocumentProxy` for fine-grained control over PDF.js behavior, such as disabling font face loading or specifying a custom URL for standard font data. ```typescript const pdf = await getDocumentProxy(buffer, { disableFontFace: false, standardFontDataUrl: 'https://unpkg.com/pdfjs-dist@latest/standard_fonts/', }) ``` -------------------------------- ### renderPageAsImage Source: https://context7.com/unjs/unpdf/llms.txt Renders a complete PDF page using a canvas backend and returns the result as an ArrayBuffer (default) or base64 data URL. Requires the official `pdfjs-dist` build and the `@napi-rs/canvas` package in Node.js. Scale can be set explicitly or derived from a target `width` or `height`. ```APIDOC ## renderPageAsImage ### Description Renders a complete PDF page using a canvas backend and returns the result as an `ArrayBuffer` (default) or base64 data URL (`toDataURL: true`). Requires the official `pdfjs-dist` build (not the serverless bundle) and the `@napi-rs/canvas` package in Node.js. Scale can be set explicitly or derived from a target `width` or `height`. ### Usage ```ts import { readFile, writeFile } from 'node:fs/promises' import { definePDFJSModule, getDocumentProxy, renderPageAsImage } from 'unpdf' // Step 1: Switch to the official PDF.js build await definePDFJSModule(() => import('pdfjs-dist')) const buffer = new Uint8Array(await readFile('./document.pdf')) // Render page 1 as PNG ArrayBuffer (2× scale) const pngBuffer = await renderPageAsImage(buffer, 1, { canvasImport: () => import('@napi-rs/canvas'), // Required in Node.js scale: 2, }) await writeFile('page1.png', new Uint8Array(pngBuffer)) // => page1.png written (valid PNG, header: [137,80,78,71,13,10,26,10]) // Render with fixed width (scale is calculated automatically) const fixedWidthBuffer = await renderPageAsImage(buffer, 1, { canvasImport: () => import('@napi-rs/canvas'), width: 1200, }) await writeFile('page1-1200w.png', new Uint8Array(fixedWidthBuffer)) // Return a data URL instead (e.g., for embedding in HTML) const dataURL = await renderPageAsImage(buffer, 1, { canvasImport: () => import('@napi-rs/canvas'), scale: 1.5, toDataURL: true, }) console.log(dataURL.startsWith('data:image/png;base64,')) // => true const html = `` await writeFile('page1.html', html) ``` ``` -------------------------------- ### Define Custom PDF.js Build Source: https://github.com/unjs/unpdf/blob/main/README.md Allows defining a custom PDF.js build before using other unpdf methods. This is useful for specifying official or legacy builds. Note that older Node.js versions might not support Promise.withResolvers. ```typescript import { definePDFJSModule, extractText, getDocumentProxy } from 'unpdf' // Define the PDF.js build before using any other unpdf method await definePDFJSModule(() => import('pdfjs-dist')) // Now, you can use all unpdf methods with the official PDF.js build const pdf = await getDocumentProxy(/* … */) const { text } = await extractText(pdf) ``` -------------------------------- ### Extract PDF Metadata with getMeta Source: https://context7.com/unjs/unpdf/llms.txt Use getMeta to retrieve the /Info dictionary and XMP metadata. Set parseDates to true to convert date fields into Date objects. ```typescript import { readFile } from 'node:fs/promises' import { getDocumentProxy, getMeta } from 'unpdf' const buffer = await readFile('./document.pdf') const pdf = await getDocumentProxy(new Uint8Array(buffer)) // Basic metadata (dates remain as raw strings) const { info, metadata } = await getMeta(pdf) console.log(info) // => { // Author: "Evangelos Vlachogiannis", // CreationDate: "D:20070223175637+02'00'", // Creator: "Writer", // PDFFormatVersion: "1.4", // Producer: "OpenOffice.org 2.1", // IsLinearized: false, // ... // } // Parse date fields into Date objects const { info: parsedInfo, metadata: parsedMeta } = await getMeta(pdf, { parseDates: true }) console.log(parsedInfo.CreationDate instanceof Date) // => true console.log(parsedInfo.CreationDate.getFullYear()) // => 2007 // Access XMP dates (also parsed when parseDates: true) const createDate = parsedMeta.get('xmp:createdate') console.log(createDate instanceof Date) // => true ``` -------------------------------- ### Create Isomorphic Canvas Factory Source: https://context7.com/unjs/unpdf/llms.txt Provides an environment-aware canvas factory for browser (DOM) or Node.js (@napi-rs/canvas). Used internally by renderPageAsImage for custom rendering. ```typescript import { createIsomorphicCanvasFactory, definePDFJSModule, getResolvedPDFJS } from 'unpdf' await definePDFJSModule(() => import('pdfjs-dist')) // Obtain the correct CanvasFactory for this runtime const CanvasFactory = await createIsomorphicCanvasFactory( () => import('@napi-rs/canvas'), // required in Node.js; omit in browser ) // Use it directly with getDocument for custom rendering pipelines const { getDocument } = await getResolvedPDFJS() const doc = await getDocument({ data: pdfData, CanvasFactory, isEvalSupported: false, }).promise const page = await doc.getPage(1) const viewport = page.getViewport({ scale: 2 }) const { canvas, context } = (new CanvasFactory()).create(viewport.width, viewport.height) await page.render({ canvas, canvasContext: context, viewport }).promise ``` -------------------------------- ### Extract Text From PDF Source: https://github.com/unjs/unpdf/blob/main/README.md Demonstrates how to extract text content from a PDF file. It involves fetching the PDF, obtaining a PDF document proxy, and then extracting text, with an option to merge text from all pages. ```APIDOC ## Extract Text From PDF ### Description Extracts text content from a PDF document. Supports merging text from all pages into a single string. ### Method `extractText(pdf: PDFDocumentProxy, options?: { mergePages?: boolean }): Promise<{ totalPages: number; text: string }>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts import { extractText, getDocumentProxy } from 'unpdf' const buffer = await fetch('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf') .then(res => res.arrayBuffer()) const pdf = await getDocumentProxy(new Uint8Array(buffer)) const { totalPages, text } = await extractText(pdf, { mergePages: true }) console.log(`Total pages: ${totalPages}`) console.log(text) ``` ### Response #### Success Response (200) - **totalPages** (number) - The total number of pages in the PDF. - **text** (string) - The extracted text content from the PDF. #### Response Example ```json { "totalPages": 1, "text": "This is a sample PDF document." } ``` ``` -------------------------------- ### Define Custom PDF.js Module Source: https://github.com/unjs/unpdf/blob/main/README.md Allows users to specify a custom PDF.js build to be used by unpdf. This is useful for compatibility or if a specific PDF.js version is required. This method must be called before any other unpdf method. ```APIDOC ## Define Custom PDF.js Module ### Description Allows defining a custom PDF.js module to be used by `unpdf`. This method should be invoked before any other `unpdf` functions. If not called, `unpdf` defaults to its bundled serverless build. ### Method `definePDFJSModule(pdfjs: () => Promise): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts import { definePDFJSModule, extractText, getDocumentProxy } from 'unpdf' // Define the PDF.js build before using any other unpdf method await definePDFJSModule(() => import('pdfjs-dist')) // Now, you can use all unpdf methods with the official PDF.js build const pdf = await getDocumentProxy(/* ... */) const { text } = await extractText(pdf) ``` ### Response #### Success Response (200) This method returns a Promise that resolves when the PDF.js module has been successfully defined. #### Response Example None (void return type) ``` -------------------------------- ### getDocumentProxy — Load a PDF into a reusable proxy Source: https://context7.com/unjs/unpdf/llms.txt Parses binary PDF data into a `PDFDocumentProxy` that can be passed to any extraction function, avoiding repeated parsing when multiple operations are needed on the same file. Automatically applies sensible defaults. ```APIDOC ## getDocumentProxy ### Description Parses binary PDF data into a `PDFDocumentProxy` that can be passed to any extraction function, avoiding repeated parsing when multiple operations are needed on the same file. Automatically applies sensible defaults (`isEvalSupported: false`, `useSystemFonts: true`), and in Node.js also sets `disableFontFace: true` and resolves `standardFontDataUrl` from the local `pdfjs-dist` installation. ### Method `getDocumentProxy(data: Uint8Array | ArrayBuffer, options?: PDFProxyOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts import { readFile } from 'node:fs/promises' import { extractLinks, extractText, getDocumentProxy, getMeta } from 'unpdf' const buffer = await readFile('./document.pdf') const pdf = await getDocumentProxy(new Uint8Array(buffer)) // Reuse the same proxy for multiple operations const { info } = await getMeta(pdf) const { text } = await extractText(pdf, { mergePages: true }) const { links } = await extractLinks(pdf) console.log(`Author: ${info.Author}`) // => Author: Evangelos Vlachogiannis console.log(`Text preview: ${text.slice(0, 50)}`) // => Text preview: Dummy PDF file console.log(`Links found: ${links.length}`) // Custom options – override font rendering for accurate output const pdfCustom = await getDocumentProxy(new Uint8Array(buffer), { disableFontFace: false, standardFontDataUrl: 'https://unpkg.com/pdfjs-dist@latest/standard_fonts/', }) ``` ### Response #### Success Response (200) - **pdf**: `PDFDocumentProxy` - A proxy object representing the loaded PDF document. - **info**: `object` - Metadata about the PDF document. #### Response Example ```json { "pdf": { /* PDFDocumentProxy object */ }, "info": { "Author": "Evangelos Vlachogiannis", ... } } ``` ``` -------------------------------- ### createIsomorphicCanvasFactory Source: https://context7.com/unjs/unpdf/llms.txt A lower-level helper exported for advanced usage that returns the appropriate canvas factory class for the current runtime: `DOMCanvasFactory` in browsers and `NodeCanvasFactory` in Node.js (using `@napi-rs/canvas`). Throws in unsupported environments. Used internally by `renderPageAsImage`. ```APIDOC ## createIsomorphicCanvasFactory ### Description A lower-level helper exported for advanced usage that returns the appropriate canvas factory class for the current runtime: `DOMCanvasFactory` in browsers and `NodeCanvasFactory` in Node.js (using `@napi-rs/canvas`). Throws in unsupported environments. Used internally by `renderPageAsImage`. ### Usage ```ts import { createIsomorphicCanvasFactory, definePDFJSModule, getResolvedPDFJS } from 'unpdf' await definePDFJSModule(() => import('pdfjs-dist')) // Obtain the correct CanvasFactory for this runtime const CanvasFactory = await createIsomorphicCanvasFactory( () => import('@napi-rs/canvas'), // required in Node.js; omit in browser ) // Use it directly with getDocument for custom rendering pipelines const { getDocument } = await getResolvedPDFJS() const doc = await getDocument({ data: pdfData, CanvasFactory, isEvalSupported: false, }).promise const page = await doc.getPage(1) const viewport = page.getViewport({ scale: 2 }) const { canvas, context } = (new CanvasFactory()).create(viewport.width, viewport.height) await page.render({ canvas, canvasContext: context, viewport }).promise ``` ``` -------------------------------- ### Extract Text From PDF Source: https://github.com/unjs/unpdf/blob/main/README.md Fetches a PDF, extracts text, and logs the total pages and extracted text. Ensure the PDF buffer is correctly formatted. ```typescript import { extractText, getDocumentProxy } from 'unpdf' // Fetch a PDF from the web or load it from the file system const buffer = await fetch('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf') .then(res => res.arrayBuffer()) const pdf = await getDocumentProxy(new Uint8Array(buffer)) const { totalPages, text } = await extractText(pdf, { mergePages: true }) console.log(`Total pages: ${totalPages}`) console.log(text) ``` -------------------------------- ### getMeta Source: https://context7.com/unjs/unpdf/llms.txt Extracts metadata from a PDF, including the /Info dictionary and XMP metadata. Dates can be optionally parsed into Date objects. ```APIDOC ## getMeta ### Description Extracts the `/Info` dictionary and XMP metadata for a PDF. When `parseDates` is `true`, `CreationDate` and `ModDate` fields in `/Info` are converted to `Date` objects, and XMP date properties are also parsed. ### Method ```javascript getMeta(pdf: PDFProxy, options?: { parseDates?: boolean }): Promise<{ info: Record, metadata: Map }> ``` ### Parameters #### `pdf` - **pdf** (PDFProxy) - Required - The PDF document proxy object. #### `options` - **parseDates** (boolean) - Optional - If true, date fields will be parsed into `Date` objects. ### Request Example ```javascript import { readFile } from 'node:fs/promises' import { getDocumentProxy, getMeta } from 'unpdf' const buffer = await readFile('./document.pdf') const pdf = await getDocumentProxy(new Uint8Array(buffer)) // Basic metadata const { info, metadata } = await getMeta(pdf) console.log(info) // Parse date fields into Date objects const { info: parsedInfo, metadata: parsedMeta } = await getMeta(pdf, { parseDates: true }) console.log(parsedInfo.CreationDate instanceof Date) // => true ``` ### Response #### Success Response - **info** (Record) - An object containing PDF information. - **metadata** (Map) - A Map containing XMP metadata. #### Response Example ```json { "info": { "Author": "Evangelos Vlachogiannis", "CreationDate": "D:20070223175637+02'00'", "Creator": "Writer", "PDFFormatVersion": "1.4", "Producer": "OpenOffice.org 2.1", "IsLinearized": false }, "metadata": { "xmp:createdate": "2007-02-23T17:56:37+02:00", "xmp:modifydate": "2007-02-23T17:56:37+02:00", "xmp:metadatadate": "2007-02-23T17:56:37+02:00" } } ``` ``` -------------------------------- ### Render PDF Page as Image Source: https://context7.com/unjs/unpdf/llms.txt Renders a PDF page to a raster image (ArrayBuffer or data URL). Requires 'pdfjs-dist' and '@napi-rs/canvas' in Node.js. Scale can be explicit or derived from width/height. ```typescript import { readFile, writeFile } from 'node:fs/promises' import { definePDFJSModule, getDocumentProxy, renderPageAsImage } from 'unpdf' // Step 1: Switch to the official PDF.js build await definePDFJSModule(() => import('pdfjs-dist')) const buffer = new Uint8Array(await readFile('./document.pdf')) // Render page 1 as PNG ArrayBuffer (2× scale) const pngBuffer = await renderPageAsImage(buffer, 1, { canvasImport: () => import('@napi-rs/canvas'), // Required in Node.js scale: 2, }) await writeFile('page1.png', new Uint8Array(pngBuffer)) // => page1.png written (valid PNG, header: [137,80,78,71,13,10,26,10]) // Render with fixed width (scale is calculated automatically) const fixedWidthBuffer = await renderPageAsImage(buffer, 1, { canvasImport: () => import('@napi-rs/canvas'), width: 1200, }) await writeFile('page1-1200w.png', new Uint8Array(fixedWidthBuffer)) // Return a data URL instead (e.g., for embedding in HTML) const dataURL = await renderPageAsImage(buffer, 1, { canvasImport: () => import('@napi-rs/canvas'), scale: 1.5, toDataURL: true, }) console.log(dataURL.startsWith('data:image/png;base64,')) // => true const html = `` await writeFile('page1.html', html) ``` -------------------------------- ### Access Raw PDF.js Module with getResolvedPDFJS Source: https://context7.com/unjs/unpdf/llms.txt Returns the fully resolved PDF.js module, providing direct access to low-level PDF.js APIs like `getDocument`. This is useful for advanced use cases not covered by unpdf's higher-level helpers. It also allows checking the currently used PDF.js version. ```typescript import { readFile } from 'node:fs/promises' import { getResolvedPDFJS } from 'unpdf' // Check which PDF.js version is in use const { version } = await getResolvedPDFJS() console.log(version) // => "5.6.205" // Use the low-level getDocument API directly const { getDocument } = await getResolvedPDFJS() const data = await readFile('./document.pdf') const document = await getDocument(new Uint8Array(data)).promise const meta = await document.getMetadata() console.log(meta.info) // => { Author: "...", CreationDate: "D:20070223...", PDFFormatVersion: "1.4", ... } ``` -------------------------------- ### renderPageAsImage Source: https://github.com/unjs/unpdf/blob/main/README.md Renders a specific page of a PDF document as an image. It can return an ArrayBuffer or a data URL string. This method is compatible with Node.js and browser environments. ```APIDOC ## `renderPageAsImage` ### Description To render a PDF page as an image, you can use the `renderPageAsImage` method. This method will return an `ArrayBuffer` of the rendered image. It can also return a data URL (`string`) if `toDataURL` option is set to `true`. > [!NOTE] > This method will only work in Node.js and browser environments. ### Method Signature ```ts function renderPageAsImage( data: DocumentInitParameters['data'] | PDFDocumentProxy, pageNumber: number, options?: { canvasImport?: () => Promise /** @default 1.0 */ scale?: number width?: number height?: number toDataURL?: false }, ): Promise function renderPageAsImage( data: DocumentInitParameters['data'] | PDFDocumentProxy, pageNumber: number, options: { canvasImport?: () => Promise /** @default 1.0 */ scale?: number width?: number height?: number toDataURL: true }, ): Promise ``` ### Parameters - **data** (DocumentInitParameters['data'] | PDFDocumentProxy) - The PDF data or a PDFDocumentProxy object. - **pageNumber** (number) - The number of the page to render. - **options** (object) - Optional configuration for rendering. - **canvasImport** (function) - A function that imports the canvas module, required for Node.js environments. - **scale** (number) - The scale factor for rendering the page. Defaults to 1.0. - **width** (number) - The desired width of the rendered image. - **height** (number) - The desired height of the rendered image. - **toDataURL** (boolean) - If true, the method returns a data URL string; otherwise, it returns an ArrayBuffer. Defaults to false. ### Examples **Rendering to ArrayBuffer:** ```ts import { definePDFJSModule, renderPageAsImage } from 'unpdf' // Use the official PDF.js build await definePDFJSModule(() => import('pdfjs-dist')) const pdf = await readFile('./dummy.pdf') const buffer = new Uint8Array(pdf) const pageNumber = 1 const result = await renderPageAsImage(buffer, pageNumber, { canvasImport: () => import('@napi-rs/canvas'), scale: 2, }) await writeFile('dummy-page-1.png', new Uint8Array(result)) ``` **Rendering to Data URL:** ```ts import { definePDFJSModule, renderPageAsImage } from 'unpdf' await definePDFJSModule(() => import('pdfjs-dist')) const pdf = await readFile('./dummy.pdf') const buffer = new Uint8Array(pdf) const pageNumber = 1 const result = await renderPageAsImage(buffer, pageNumber, { canvasImport: () => import('@napi-rs/canvas'), scale: 2, toDataURL: true, }) const html = ` Dummy Page Example Page ` await writeFile('dummy-page-1.html', html) ``` ``` -------------------------------- ### definePDFJSModule — Override the PDF.js build Source: https://context7.com/unjs/unpdf/llms.txt Registers a custom PDF.js resolver before any other unpdf function is called. By default unpdf uses its bundled serverless build; call this to swap in the official pdfjs-dist package or a legacy version. Must be awaited before any extraction calls. ```APIDOC ## definePDFJSModule ### Description Registers a custom PDF.js resolver before any other `unpdf` function is called. By default `unpdf` uses its bundled serverless build; call this to swap in the official `pdfjs-dist` package or a legacy version. Must be awaited before any extraction calls. ### Method `definePDFJSModule(resolver: () => Promise)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts import { definePDFJSModule, extractText, getDocumentProxy } from 'unpdf' // Use the official pdfjs-dist instead of the bundled serverless build. // Requires: npm install pdfjs-dist // WARNING: pdfjs-dist v5.x requires Promise.withResolvers (Node >= 22). await definePDFJSModule(() => import('pdfjs-dist')) const buffer = await fetch('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf') .then(res => res.arrayBuffer()) const pdf = await getDocumentProxy(new Uint8Array(buffer)) const { totalPages, text } = await extractText(pdf, { mergePages: true }) console.log(`Pages: ${totalPages}`) // => Pages: 1 console.log(text) // => "Dummy PDF file" ``` ### Response #### Success Response None (This function is for configuration and does not return a value directly usable in the same way as extraction functions). #### Response Example None ``` -------------------------------- ### getResolvedPDFJS — Access the raw PDF.js module Source: https://context7.com/unjs/unpdf/llms.txt Returns the fully resolved PDF.js module, giving direct access to the low-level `getDocument`, `PDFDateString`, `OPS`, and all other PDF.js exports. Useful when `unpdf`'s higher-level helpers do not cover a specific use case. ```APIDOC ## getResolvedPDFJS ### Description Returns the fully resolved PDF.js module, giving direct access to the low-level `getDocument`, `PDFDateString`, `OPS`, and all other PDF.js exports. Useful when `unpdf`'s higher-level helpers do not cover a specific use case. ### Method `getResolvedPDFJS(): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts import { readFile } from 'node:fs/promises' import { getResolvedPDFJS } from 'unpdf' // Check which PDF.js version is in use const { version } = await getResolvedPDFJS() console.log(version) // => "5.6.205" // Use the low-level getDocument API directly const { getDocument } = await getResolvedPDFJS() const data = await readFile('./document.pdf') const document = await getDocument(new Uint8Array(data)).promise const meta = await document.getMetadata() console.log(meta.info) // => { Author: "...", CreationDate: "D:20070223...", PDFFormatVersion: "1.4", ... } ``` ### Response #### Success Response (200) - **pdfjsModule**: `object` - The resolved PDF.js module, containing exports like `getDocument`, `OPS`, `PDFDateString`, etc. #### Response Example ```json { "pdfjsModule": { "version": "5.6.205", "getDocument": "function", "OPS": { ... }, "PDFDateString": "function", ... } } ``` ``` -------------------------------- ### Render PDF Page to Data URL (Node.js/Browser) Source: https://github.com/unjs/unpdf/blob/main/README.md Renders a PDF page and returns a data URL string, suitable for embedding directly into HTML. This requires setting the `toDataURL` option to `true`. Similar to image rendering, ensure PDF.js is defined and the canvas package is available for Node.js. ```typescript import { definePDFJSModule, renderPageAsImage } from 'unpdf' await definePDFJSModule(() => import('pdfjs-dist')) const pdf = await readFile('./dummy.pdf') const buffer = new Uint8Array(pdf) const pageNumber = 1 const result = await renderPageAsImage(buffer, pageNumber, { canvasImport: () => import('@napi-rs/canvas'), scale: 2, toDataURL: true, }) const html = ` Dummy Page Example Page ` await writeFile('dummy-page-1.html', html) ``` -------------------------------- ### Extract Images from PDF Page Source: https://context7.com/unjs/unpdf/llms.txt Extracts raster images from a specific PDF page as pixel buffers. Requires Node.js environment with 'sharp' for image processing. ```typescript import { readFile, writeFile } from 'node:fs/promises' import sharp from 'sharp' import { extractImages, getDocumentProxy } from 'unpdf' const buffer = await readFile('./document.pdf') const pdf = await getDocumentProxy(new Uint8Array(buffer)) // Extract images from page 1 (1-indexed; throws if out of range) const images = await extractImages(pdf, 1) console.log(`Found ${images.length} images on page 1`) for (let i = 0; i < images.length; i++) { const img = images[i]! console.log(`Image ${i + 1}: key=${img.key}, ${img.width}x${img.height}, ${img.channels}ch`) // => Image 1: key=img_p0_1, 800x600, 3ch // Convert raw pixel buffer to PNG with sharp await sharp(img.data, { raw: { width: img.width, height: img.height, channels: img.channels, }, }) .png() .toFile(`page1-image-${i + 1}.png`) } ``` -------------------------------- ### extractImages Source: https://context7.com/unjs/unpdf/llms.txt Extracts all raster images embedded on a specific page as Uint8ClampedArray pixel buffers, with their dimensions and channel count. Designed for use with image processing libraries such as sharp. ```APIDOC ## extractImages ### Description Extracts all raster images embedded on a specific page as `Uint8ClampedArray` pixel buffers, with their dimensions and channel count (1 = grayscale, 3 = RGB, 4 = RGBA). Designed for use with image processing libraries such as `sharp`. ### Usage ```ts import { readFile, writeFile } from 'node:fs/promises' import sharp from 'sharp' import { extractImages, getDocumentProxy } from 'unpdf' const buffer = await readFile('./document.pdf') const pdf = await getDocumentProxy(new Uint8Array(buffer)) // Extract images from page 1 (1-indexed; throws if out of range) const images = await extractImages(pdf, 1) console.log(`Found ${images.length} images on page 1`) for (let i = 0; i < images.length; i++) { const img = images[i]! console.log(`Image ${i + 1}: key=${img.key}, ${img.width}x${img.height}, ${img.channels}ch`) // => Image 1: key=img_p0_1, 800x600, 3ch // Convert raw pixel buffer to PNG with sharp await sharp(img.data, { raw: { width: img.width, height: img.height, channels: img.channels, }, }) .png() .toFile(`page1-image-${i + 1}.png`) } ``` ``` -------------------------------- ### Extract Hyperlinks from PDF Annotations with extractLinks Source: https://context7.com/unjs/unpdf/llms.txt Use extractLinks to iterate through PDF pages and collect all URL strings from Link annotations. The result is a flat array of all URLs found in the document. ```typescript import { readFile } from 'node:fs/promises' import { extractLinks, getDocumentProxy } from 'unpdf' const buffer = await readFile('./document-with-links.pdf') const pdf = await getDocumentProxy(new Uint8Array(buffer)) const { totalPages, links } = await extractLinks(pdf) console.log(`Total pages: ${totalPages}`) // => Total pages: 2 console.log(`Links found: ${links.length}`) // => Links found: 4 links.forEach(url => console.log(url)) // => https://www.antennahouse.com/ // => https://example.com/page2 // ... // Filter to only external HTTPS links const externalLinks = links.filter(url => url.startsWith('https://')) console.log(`External HTTPS links: ${externalLinks.length}) ``` -------------------------------- ### Extract Images from PDF Page Source: https://github.com/unjs/unpdf/blob/main/README.md Extracts images from a specified page of a PDF. Requires the 'sharp' library for image processing and saving. The function returns an array of image objects, each containing image data, dimensions, and channel information. ```typescript import { readFile, writeFile } from 'node:fs/promises' import sharp from 'sharp' import { extractImages, getDocumentProxy } from 'unpdf' async function extractPdfImages() { const buffer = await readFile('./document.pdf') const pdf = await getDocumentProxy(new Uint8Array(buffer)) // Extract images from page 1 const imagesData = await extractImages(pdf, 1) console.log(`Found ${imagesData.length} images on page 1`) ``` ```typescript // Process each image with sharp (optional) let totalImagesProcessed = 0 for (const imgData of imagesData) { const imageIndex = ++totalImagesProcessed await sharp(imgData.data, { raw: { width: imgData.width, height: imgData.height, channels: imgData.channels } }) .png() .toFile(`image-${imageIndex}.png`) console.log(`Saved image ${imageIndex} (${imgData.width}x${imgData.height}, ${imgData.channels} channels)`) ``` ```typescript } } extractPdfImages().catch(console.error) ``` -------------------------------- ### extractLinks Source: https://context7.com/unjs/unpdf/llms.txt Extracts all hyperlink URLs from PDF annotations across all pages. ```APIDOC ## extractLinks ### Description Iterates all pages and collects URL strings from `Link` annotations. Returns a flat array of all URLs across the entire document. ### Method ```javascript extractLinks(pdf: PDFProxy | Uint8Array): Promise<{ totalPages: number, links: string[] }> ``` ### Parameters #### `pdf` - **pdf** (PDFProxy | Uint8Array) - Required - The PDF document proxy object or a Uint8Array buffer of the PDF. ### Request Example ```javascript import { readFile } from 'node:fs/promises' import { extractLinks, getDocumentProxy } from 'unpdf' const buffer = await readFile('./document-with-links.pdf') const pdf = await getDocumentProxy(new Uint8Array(buffer)) const { totalPages, links } = await extractLinks(pdf) console.log(`Total pages: ${totalPages}`) console.log(`Links found: ${links.length}`) links.forEach(url => console.log(url)) ``` ### Response #### Success Response - **totalPages** (number) - The total number of pages in the PDF. - **links** (string[]) - An array of all URL strings found in the PDF's link annotations. #### Response Example ```json { "totalPages": 2, "links": [ "https://www.antennahouse.com/", "https://example.com/page2", "http://another-link.org" ] } ``` ``` -------------------------------- ### Extract Links from PDF Source: https://github.com/unjs/unpdf/blob/main/README.md Use this function to extract all hyperlinks and external URLs from a PDF document. It returns the total number of pages and an array of found links. ```typescript import { readFile } from 'node:fs/promises' import { extractLinks, getDocumentProxy } from 'unpdf' // Load a PDF file const buffer = await readFile('./document.pdf') const pdf = await getDocumentProxy(new Uint8Array(buffer)) // Extract all links from the PDF const { totalPages, links } = await extractLinks(pdf) console.log(`Total pages: ${totalPages}`) console.log(`Found ${links.length} links:`) ``` ```typescript for (const link of links) console.log(link) ``` -------------------------------- ### extractLinks Source: https://github.com/unjs/unpdf/blob/main/README.md Extracts all links from a PDF document, including hyperlinks and external URLs. ```APIDOC ## extractLinks ### Description Extracts all links from a PDF document, including hyperlinks and external URLs. ### Method Signature ```ts function extractLinks( data: DocumentInitParameters['data'] | PDFDocumentProxy, ): Promise<{ totalPages: number, links: string[] }> ``` ### Example ```ts import { readFile } from 'node:fs/promises' import { extractLinks, getDocumentProxy } from 'unpdf' // Load a PDF file const buffer = await readFile('./document.pdf') const pdf = await getDocumentProxy(new Uint8Array(buffer)) // Extract all links from the PDF const { totalPages, links } = await extractLinks(pdf) console.log(`Total pages: ${totalPages}`) console.log(`Found ${links.length} links:`) for (const link of links) console.log(link) ``` ```