### Install and Run Next.js App Source: https://github.com/joshxfi/pdf-raster/blob/main/consumer/README.md Commands to install dependencies, start the development server, and build the Next.js application. ```bash bun install --cwd consumer ``` ```bash bun run --cwd consumer dev ``` ```bash bun run --cwd consumer build ``` -------------------------------- ### Local Development Setup and Commands Source: https://github.com/joshxfi/pdf-raster/blob/main/README.md Instructions for setting up the local development environment for pdf-raster, including installing dependencies, downloading native binaries, building, testing, and benchmarking. ```bash # Setup: bun install bun install ``` ```bash # Native Binaries: bun run pdfium:download bun run pdfium:download ``` ```bash # Build: bun run build bun run build ``` ```bash # Test: bun run test bun run test ``` ```bash # Benchmark: bun run benchmark bun run benchmark ``` -------------------------------- ### Run Development Server Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/README.md Starts the documentation site in local development mode. The app runs on port 3001. ```bash bun run dev ``` -------------------------------- ### Install pdf-raster with Bun, pnpm, or npm Source: https://context7.com/joshxfi/pdf-raster/llms.txt Install the pdf-raster package using your preferred package manager. ```bash # Bun bun add pdf-raster # pnpm pnpm add pdf-raster # npm npm install pdf-raster ``` -------------------------------- ### Install pdf-raster with Bun, PNPM, or NPM Source: https://github.com/joshxfi/pdf-raster/blob/main/README.md Choose the appropriate command based on your package manager to install the pdf-raster library. ```bash # Using Bun bun add pdf-raster ``` ```bash # Using PNPM pnpm add pdf-raster ``` ```bash # Using NPM npm install pdf-raster ``` -------------------------------- ### Install pdf-raster with Bun Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/installation.mdx Use this command to add the pdf-raster package to your project when using Bun as your package manager. ```bash bun add pdf-raster ``` -------------------------------- ### Run Development Server with npm Source: https://github.com/joshxfi/pdf-raster/blob/main/example/README.md Use this command to start the Next.js development server using npm. Open http://localhost:3000 in your browser to view the application. ```bash npm run dev ``` -------------------------------- ### Run Development Server with bun Source: https://github.com/joshxfi/pdf-raster/blob/main/example/README.md Use this command to start the Next.js development server using bun. Open http://localhost:3000 in your browser to view the application. ```bash bun dev ``` -------------------------------- ### Install pdf-raster Source: https://github.com/joshxfi/pdf-raster/blob/main/core/README.md Install the pdf-raster package using your preferred package manager (Bun, PNPM, or NPM). ```bash # Bun bun add pdf-raster # PNPM pnpm add pdf-raster # NPM npm install pdf-raster ``` -------------------------------- ### Run Development Server with pnpm Source: https://github.com/joshxfi/pdf-raster/blob/main/example/README.md Use this command to start the Next.js development server using pnpm. Open http://localhost:3000 in your browser to view the application. ```bash pnpm dev ``` -------------------------------- ### Run Benchmark Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/benchmark.mdx Execute the benchmark script to compare different PDF rendering implementations. Ensure you have the necessary dependencies installed, especially for node-canvas. ```bash bun run benchmark ``` -------------------------------- ### Run Development Server with yarn Source: https://github.com/joshxfi/pdf-raster/blob/main/example/README.md Use this command to start the Next.js development server using yarn. Open http://localhost:3000 in your browser to view the application. ```bash yarn dev ``` -------------------------------- ### Install pdf-raster with npm Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/installation.mdx Use this command to add the pdf-raster package to your project when using npm as your package manager. ```bash npm install pdf-raster ``` -------------------------------- ### Install pdf-raster with pnpm Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/installation.mdx Use this command to add the pdf-raster package to your project when using pnpm as your package manager. ```bash pnpm add pdf-raster ``` -------------------------------- ### Request Different Output Format (WebP) Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/examples-node.mdx Use this pattern to request a different output format like WebP or JPEG when smaller payloads matter more than lossless output. PNG is the safest default. This example converts to WebP with 200 DPI. ```typescript import { convert } from "pdf-raster"; const pages = await convert("./report.pdf", { outputFormat: "webp", dpi: 200, }); console.log(pages[0].mimeType); // "image/webp" ``` -------------------------------- ### Convert PDF from In-Memory Buffer Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/examples-node.mdx Use this pattern when the PDF data is available as an in-memory buffer, such as from an upload, queue payload, or external storage SDK. This example reads a PDF from disk into a buffer and then converts it. ```typescript import { readFile } from "node:fs/promises"; import { convert } from "pdf-raster"; const bytes = await readFile("./invoice.pdf"); const pages = await convert(bytes, { dpi: 300, }); ``` -------------------------------- ### Convert Selected PDF Pages Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/examples-node.mdx Use this pattern to convert specific pages from a larger PDF document. This example converts pages 0, 3, and 4. ```typescript import { convert } from "pdf-raster"; const pages = await convert("./report.pdf", { pages: [0, 3, 4], dpi: 300, }); ``` -------------------------------- ### Get details of a single page Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/quickstart.mdx Extracts and logs detailed information about the first page of a PDF. Useful for inspecting individual page properties like dimensions and byte length. ```typescript const [page] = await convert("./report.pdf"); console.log({ pageIndex: page.pageIndex, mimeType: page.mimeType, width: page.width, height: page.height, dpi: page.dpi, bytes: page.data.byteLength, }); // { // pageIndex: 0, // mimeType: "image/png", // width: 833, // height: 417, // dpi: 300, // bytes: 14032 // } ``` -------------------------------- ### Build Documentation Site Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/README.md Builds the documentation site for production deployment. ```bash bun run build ``` -------------------------------- ### Convert PDF to image buffers using pdf-raster Source: https://context7.com/joshxfi/pdf-raster/llms.txt Demonstrates various ways to use the `convert()` function, including converting all pages, selected pages, custom DPI, different output formats, and from different input types like file paths, in-memory buffers, Uint8Array, and ArrayBuffer. Also shows how to save rendered pages and handle errors. ```typescript import { convert, PdfToImagesError } from "pdf-raster"; import { readFile, writeFile } from "node:fs/promises"; // --- From a file path (all pages, default PNG at 300 DPI) --- const allPages = await convert("./document.pdf"); // allPages[0] => { pageIndex: 0, mimeType: "image/png", width: 833, height: 417, dpi: 300, data: Buffer } // --- Selected pages, custom DPI, WebP output --- const pages = await convert("./report.pdf", { pages: [0, 2], // zero-based indices dpi: 150, outputFormat: "webp", }); console.log(pages[0].mimeType); // "image/webp" // --- From an in-memory Buffer (e.g. fetched from S3 or an upload) --- const bytes = await readFile("./invoice.pdf"); const bufferPages = await convert(bytes, { dpi: 300 }); // --- From Uint8Array --- const uint8 = new Uint8Array(await readFile("./invoice.pdf")); const uint8Pages = await convert(uint8, { pages: [0] }); // --- From ArrayBuffer --- const ab = (await readFile("./invoice.pdf")).buffer; const abPages = await convert(ab, { pages: [0] }); // --- Save a rendered page to disk --- const [firstPage] = await convert("./report.pdf", { pages: [0], dpi: 300 }); await writeFile("./report-page-1.png", firstPage.data); // --- Encrypted PDF --- const [secured] = await convert("./secure.pdf", { password: "mysecretpassword", pages: [0], }); // --- Crop a region (pixel coordinates at the rendered DPI) --- const [cropped] = await convert("./diagram.pdf", { pages: [0], dpi: 300, crop: { x: 10, y: 20, width: 400, height: 300 }, }); console.log(cropped.width, cropped.height); // 400, 300 // --- Disable annotation/form rendering --- const [clean] = await convert("./form.pdf", { pages: [0], renderAnnotations: false, }); // --- Error handling with stable error codes --- try { await convert("./bad.pdf", { pages: [99] }); } catch (error) { if (error instanceof PdfToImagesError) { // Stable codes: INVALID_INPUT | INVALID_OPTIONS | INVALID_PAGE_INDEX // INVALID_CROP | PASSWORD_ERROR | MALFORMED_PDF // PDFIUM_UNAVAILABLE | RENDER_ERROR console.error(error.code, error.message); // "INVALID_PAGE_INDEX" "Page indices must be non-negative integers." } } ``` -------------------------------- ### Run Package Tests Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/local-development.mdx Execute the package tests to validate the local native build. This confirms that the native path is set up correctly. ```bash bun run --filter pdf-raster test ``` -------------------------------- ### Sample Benchmark Output Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/benchmark.mdx Sample output from the benchmark run, showing performance metrics for multi-page and single-page PDFs across different libraries. This data helps in comparing conversion speeds and identifying regressions. ```text File: multi-page.pdf Settings: dpi=300, output=png, pages=all, warmups=1, runs=5 Input size: 842 B Library Pages Avg total P50 total Avg/page Avg bytes ---------------------------- ----- --------- --------- -------- --------- pdf-raster 2 1.72 ms 1.70 ms 0.86 ms 36.2 KB pdfjs-dist + @napi-rs/canvas 2 11.96 ms 11.91 ms 5.98 ms 22.6 KB pdfjs-dist + node-canvas 2 14.37 ms 14.37 ms 7.19 ms 22.8 KB Relative speed (pdf-raster vs pdfjs-dist + @napi-rs/canvas): total 6.94x Relative speed (pdf-raster vs pdfjs-dist + node-canvas): total 8.35x File: single-page.pdf Settings: dpi=300, output=png, pages=all, warmups=1, runs=5 Input size: 583 B Library Pages Avg total P50 total Avg/page Avg bytes ---------------------------- ----- --------- --------- -------- --------- pdf-raster 1 1.29 ms 1.00 ms 1.29 ms 13.4 KB pdfjs-dist + @napi-rs/canvas 1 5.81 ms 5.83 ms 5.81 ms 7.6 KB pdfjs-dist + node-canvas 1 7.25 ms 7.26 ms 7.25 ms 7.8 KB Relative speed (pdf-raster vs pdfjs-dist + @napi-rs/canvas): total 4.51x Relative speed (pdf-raster vs pdfjs-dist + node-canvas): total 5.63x ``` -------------------------------- ### Path vs Buffer Input for Conversion Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/examples-node.mdx Choose between path input (when the file is on disk) and buffer input (when the PDF is already in memory). ```typescript await convert("./document.pdf"); ``` ```typescript await convert(pdfBuffer); ``` -------------------------------- ### Convert all pages from a file path Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/quickstart.mdx Use this to render all pages of a PDF file. The output defaults to PNG format if not specified. ```typescript import { convert } from "pdf-raster"; const pages = await convert("./report.pdf"); for (const page of pages) { console.log({ pageIndex: page.pageIndex, outputFormat: page.mimeType, width: page.width, height: page.height, dpi: page.dpi, }); } ``` -------------------------------- ### Download PDFium Cache Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/local-development.mdx Use this command to download or refresh the local PDFium cache. This is a prerequisite for building the native package. ```bash bun run pdfium:download ``` -------------------------------- ### Check Types and Generate Docs Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/README.md Executes Fumadocs MDX generation, Next.js type generation, and TypeScript compilation. ```bash bun run check-types ``` -------------------------------- ### Build Native Package Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/local-development.mdx Build the native package for the pdf-raster project. This command is essential after updating dependencies or PDFium. ```bash bun run --filter pdf-raster build ``` -------------------------------- ### VLM Prompt with Vercel AI SDK Source: https://context7.com/joshxfi/pdf-raster/llms.txt Pass rendered page images as vision inputs to multimodal language models. The Buffer is passed directly to the image type. ```typescript import { convert } from "pdf-raster"; import { generateText } from "ai"; import { openai } from "@ai-sdk/openai"; const [page] = await convert("./invoice.pdf", { pages: [0], dpi: 300, outputFormat: "png", }); const { text } = await generateText({ model: openai("gpt-4.1"), messages: [ { role: "user", content: [ { type: "text", text: "Extract all line items from this invoice." }, { type: "image", image: page.data }, // Buffer passed directly ], }, ], }); console.log(text); ``` -------------------------------- ### Quick Usage: Convert PDF to WebP with pdf-raster Source: https://github.com/joshxfi/pdf-raster/blob/main/README.md Demonstrates converting a specific page of a PDF to a high-quality WebP image buffer using pdf-raster. Ensure you have Node.js or Bun and the 'node:fs/promises' module available. ```typescript import { convert } from "pdf-raster"; import { writeFile } from "node:fs/promises"; // Convert specific pages to high-quality WebP const [page] = await convert("./report.pdf", { pages: [0], // 0-indexed page numbers dpi: 300, // Higher DPI is useful for OCR and VLM inputs outputFormat: "webp", }); console.log(`Rendered page ${page.pageIndex} (${page.width}x${page.height})`); // page.data is a Buffer of the encoded image await writeFile("output.webp", page.data); ``` -------------------------------- ### Convert PDF from Disk to PNG Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/examples-node.mdx Use this pattern when the PDF is on disk and you want to save or inspect the rendered image output directly. It converts the first page of a PDF to a PNG image. ```typescript import { writeFile } from "node:fs/promises"; import { convert } from "pdf-raster"; const [firstPage] = await convert("./report.pdf", { pages: [0], dpi: 300, }); await writeFile("./report-page-1.png", firstPage.data); console.log(firstPage.mimeType); // "image/png" ``` -------------------------------- ### convert(input, options?) Source: https://context7.com/joshxfi/pdf-raster/llms.txt Converts PDF pages into image buffers. Accepts a file path or in-memory bytes and returns a Promise resolving to an array of ConvertedPage objects, one for each rendered page. ```APIDOC ## convert(input, options?) ### Description The sole public entrypoint. Accepts a file path or in-memory bytes and returns a `Promise` — one entry per rendered page. ### Method ```javascript convert(input: string | Buffer | Uint8Array | ArrayBuffer, options?: ConvertOptions): Promise ``` ### Parameters #### Input - **input** (string | Buffer | Uint8Array | ArrayBuffer) - Required - Path to the PDF file or an in-memory buffer containing PDF data. #### Options - **pages** (number[]) - Optional - Zero-based indices of the pages to render. Omit for all pages. - **dpi** (number) - Optional - Render resolution in dots per inch. Defaults to 300. Truncated to an integer. - **outputFormat** ("png" | "jpeg" | "webp") - Optional - The desired output image format. Defaults to "png". - **password** (string) - Optional - Password for encrypted PDFs. - **crop** (object) - Optional - A crop rectangle in rendered-image pixel coordinates. Should contain `x`, `y`, `width`, and `height` properties. - **renderAnnotations** (boolean) - Optional - Whether to include annotations and form data. Defaults to true. ### Request Example ```javascript // From a file path (all pages, default PNG at 300 DPI) const allPages = await convert("./document.pdf"); // Selected pages, custom DPI, WebP output const pages = await convert("./report.pdf", { pages: [0, 2], dpi: 150, outputFormat: "webp", }); // From an in-memory Buffer const bytes = await readFile("./invoice.pdf"); const bufferPages = await convert(bytes, { dpi: 300 }); // With crop and password const [cropped] = await convert("./diagram.pdf", { pages: [0], dpi: 300, crop: { x: 10, y: 20, width: 400, height: 300 }, password: "mysecretpassword", }); ``` ### Response #### Success Response (ConvertedPage[]) An array of objects, where each object represents a rendered page and contains: - **pageIndex** (number) - The zero-based index of the page. - **mimeType** (string) - The MIME type of the image buffer (e.g., "image/png"). - **width** (number) - The width of the image in pixels. - **height** (number) - The height of the image in pixels. - **dpi** (number) - The DPI at which the page was rendered. - **data** (Buffer) - The image data as a Node.js Buffer. #### Response Example ```json [ { "pageIndex": 0, "mimeType": "image/png", "width": 833, "height": 417, "dpi": 300, "data": Buffer.from([ ... image data ... ]) } ] ``` #### Error Handling Throws a `PdfToImagesError` with a stable `code` property for specific errors like `INVALID_INPUT`, `INVALID_OPTIONS`, `INVALID_PAGE_INDEX`, `PASSWORD_ERROR`, `MALFORMED_PDF`, `PDFIUM_UNAVAILABLE`, `RENDER_ERROR`. ``` -------------------------------- ### convert(input, options?) Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/api-reference.mdx Converts a PDF input into rasterized image pages. Supports various input types and configurable rendering options. ```APIDOC ## `convert(input, options?)` ### Description Converts a PDF input into rasterized image pages. Supports various input types and configurable rendering options. ### Parameters #### Input (`input`) - **file path** (string) - Absolute or relative path to a PDF on disk. - **Buffer** (Buffer) - PDF bytes already loaded into memory. - **Uint8Array** (Uint8Array) - Typed-array PDF bytes. - **ArrayBuffer** (ArrayBuffer) - Browser-style binary buffer passed from server code. #### Options (`options`) - **pages** (number[]) - Optional - Zero-based page indices to render. Defaults to all pages. - **dpi** (number) - Optional - Target raster DPI. Defaults to 300. - **outputFormat** (string) - Optional - Output format. Supported values: "png", "jpeg", "webp". Defaults to "png". - **password** (string) - Optional - Password for encrypted PDFs. - **crop** ({ x; y; width; height }) - Optional - Crop rectangle applied after rendering. Expected format: { x: number; y: number; width: number; height: number }. - **renderAnnotations** (boolean) - Optional - Whether annotations and form data should be rendered. Defaults to true. ### Returns - **Promise** - A promise that resolves to an array of `ConvertedPage` objects, each representing a rendered page. ``` -------------------------------- ### Quick Usage: Convert PDF to Image Source: https://github.com/joshxfi/pdf-raster/blob/main/core/README.md Import the convert function and use it to render a PDF page to an image buffer. Specify the page number and desired DPI for high-resolution output. ```typescript import { convert } from "pdf-raster"; const [page] = await convert("./report.pdf", { pages: [0], // 0-indexed page numbers dpi: 300, // High resolution for OCR and VLM inputs }); // page.data is the encoded image buffer (default: png) console.log({ pageIndex: page.pageIndex, mimeType: page.mimeType, width: page.width, height: page.height, }); ``` -------------------------------- ### Next.js Client Page for PDF Upload and Preview Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/examples-nextjs-full-flow.mdx This client component provides a form for uploading PDF files and displays converted image previews. It uses `useState` for managing file, page, error, and loading states, and `fetch` to communicate with the server route handler. The `next/image` component is used for rendering the image previews. ```tsx "use client"; import Image from "next/image"; import { useState } from "react"; type ConvertedPage = { pageIndex: number; width: number; height: number; dpi: number; mimeType: string; src: string; }; export default function Page() { const [file, setFile] = useState(null); const [pages, setPages] = useState([]); const [error, setError] = useState(null); const [isLoading, setIsLoading] = useState(false); async function handleSubmit(event: React.FormEvent) { event.preventDefault(); if (!file) { setError("Choose a PDF before converting."); return; } setError(null); setIsLoading(true); setPages([]); const formData = new FormData(); formData.set("file", file); const response = await fetch("/api/convert", { method: "POST", body: formData, }); const payload = await response.json(); if (!response.ok) { setError(payload.message ?? "Conversion failed."); setIsLoading(false); return; } setPages(payload.pages ?? []); setIsLoading(false); } return (
setFile(event.currentTarget.files?.[0] ?? null)} />
{error ?

{error}

: null}
{pages.map((page) => (

Page {page.pageIndex + 1}

{page.width} × {page.height} at {page.dpi} DPI

{`Rendered
))}
); } ``` -------------------------------- ### Next.js Route Handler for PDF Conversion Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/examples-nextjs-full-flow.mdx This server-side route handler accepts PDF uploads, converts each page to a PNG image using `pdf-raster`, and returns image data. It includes input validation and error handling for conversion failures. Ensure `pdf-raster` is imported only on the server. ```typescript import { NextResponse } from "next/server"; import { convert, PdfToImagesError } from "pdf-raster"; export const runtime = "nodejs"; function errorResponse(code: string, message: string, status: number) { return NextResponse.json({ code, message }, { status }); } export async function POST(request: Request) { try { const formData = await request.formData(); const upload = formData.get("file"); if (!(upload instanceof File)) { return errorResponse("INVALID_INPUT", "Missing PDF upload.", 400); } const lowerName = upload.name.toLowerCase(); const isPdf = upload.type === "application/pdf" || lowerName.endsWith(".pdf"); if (!isPdf) { return errorResponse("INVALID_INPUT", "Only PDF uploads are supported.", 400); } const buffer = Buffer.from(await upload.arrayBuffer()); const pages = await convert(buffer, { dpi: 300, outputFormat: "png", }); return NextResponse.json({ pages: pages.map((page) => ({ pageIndex: page.pageIndex, width: page.width, height: page.height, dpi: page.dpi, mimeType: page.mimeType, src: `data:${page.mimeType};base64,${page.data.toString("base64")}`, })), }); } catch (error) { if (error instanceof PdfToImagesError) { return errorResponse(error.code, error.message, 400); } return errorResponse( "RENDER_ERROR", "Unexpected conversion failure.", 500, ); } } ``` -------------------------------- ### OCR Pipeline with Tesseract.js Source: https://context7.com/joshxfi/pdf-raster/llms.txt Pass page data directly into OCR SDKs. Higher DPI improves OCR accuracy. ```typescript import { convert } from "pdf-raster"; import { createWorker } from "tesseract.js"; const worker = await createWorker("eng"); const [page] = await convert("./scan.pdf", { pages: [0], dpi: 300, // Higher DPI improves OCR accuracy }); const result = await worker.recognize(page.data); console.log(result.data.text); await worker.terminate(); ``` -------------------------------- ### Convert Function Signature Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/api-reference.mdx The main `convert` function accepts a PDF input (file path, Buffer, Uint8Array, or ArrayBuffer) and optional conversion options, returning a promise that resolves to an array of converted pages. ```typescript function convert( input: string | Buffer | Uint8Array | ArrayBuffer, options?: ConvertOptions, ): Promise; ``` -------------------------------- ### Convert PDF pages to WebP format Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/quickstart.mdx Specifies a non-default output format, such as WebP, for the converted page images. Useful when a specific image encoding is required. ```typescript import { convert } from "pdf-raster"; const pages = await convert("./report.pdf", { outputFormat: "webp", }); console.log(pages[0].mimeType); // "image/webp" ``` -------------------------------- ### Next.js POST Route Handler for PDF Conversion Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/examples-nextjs.mdx This route handler accepts a PDF file upload via POST request, converts it to images using pdf-raster, and returns the converted pages as base64 encoded data URLs. It is designed for Node.js runtime only and includes specific error handling for PDF conversion issues. ```typescript import { NextResponse } from "next/server"; import { convert, PdfToImagesError } from "pdf-raster"; export const runtime = "nodejs"; export async function POST(request: Request) { try { const formData = await request.formData(); const upload = formData.get("file"); const isPdf = upload instanceof File && (upload.type === "application/pdf" || upload.name.toLowerCase().endsWith(".pdf")); if (!isPdf || !(upload instanceof File)) { return NextResponse.json( { code: "INVALID_INPUT", message: "Missing PDF upload." }, { status: 400 }, ); } const bytes = Buffer.from(await upload.arrayBuffer()); const pages = await convert(bytes, { pages: [0], outputFormat: "webp", dpi: 300, }); return NextResponse.json({ pages: pages.map((page) => ({ pageIndex: page.pageIndex, width: page.width, height: page.height, dpi: page.dpi, mimeType: page.mimeType, src: `data:${page.mimeType};base64,${page.data.toString("base64")}`, })), }); } catch (error) { if (error instanceof PdfToImagesError) { return NextResponse.json( { code: error.code, message: error.message }, { status: 400 }, ); } return NextResponse.json( { code: "RENDER_ERROR", message: "Unexpected conversion failure." }, { status: 500 }, ); } } ``` -------------------------------- ### Convert PDF to Images and Inspect Page Data Source: https://context7.com/joshxfi/pdf-raster/llms.txt Demonstrates converting a PDF file to an array of image buffers. Each page object contains metadata like index, MIME type, dimensions, DPI, and the image data itself. The image data is a Node.js Buffer, ready for various uses. ```typescript import { convert } from "pdf-raster"; const [page] = await convert("./report.pdf"); // ConvertedPage shape: // { // pageIndex: number; // zero-based index in the source document // data: Buffer; // encoded image bytes // mimeType: "image/png" | "image/jpeg" | "image/webp"; // width: number; // rendered width in pixels // height: number; // rendered height in pixels // dpi: number; // effective DPI used for rendering // } console.log({ pageIndex: page.pageIndex, // 0 mimeType: page.mimeType, // "image/png" width: page.width, // 833 height: page.height, // 417 dpi: page.dpi, // 300 bytes: page.data.byteLength, // e.g. 14032 }); // page.data is a standard Node.js Buffer — pass it anywhere: // writeFile, res.send(), S3 upload, base64 encode, OCR SDK, VLM prompt... ``` -------------------------------- ### Convert PDF page for AI SDK generateText Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/examples-ocr-vlm.mdx Convert a PDF page using `pdf-raster` and then pass the image data to an AI SDK's `generateText` function for multimodal analysis. The `page.data` and `page.mimeType` are crucial for the AI model. ```typescript import { convert } from "pdf-raster"; import { generateText } from "ai"; import { openai } from "@ai-sdk/openai"; const [page] = await convert("./invoice.pdf", { pages: [0], dpi: 300, }); const { text } = await generateText({ model: openai("gpt-4.1"), messages: [ { role: "user", content: [ { type: "text", text: "Extract all visible text from this page." }, { type: "image", image: page.data }, ], }, ], }); ``` -------------------------------- ### Convert selected pages from a PDF Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/quickstart.mdx Renders specific pages from a PDF file by providing an array of zero-based page indices. Allows for targeted conversion and setting a custom DPI. ```typescript import { convert } from "pdf-raster"; const pages = await convert("./report.pdf", { pages: [0, 2], dpi: 300, }); ``` -------------------------------- ### Convert PDF page for Tesseract.js OCR Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/examples-ocr-vlm.mdx Use `pdf-raster` to convert a PDF page to an image buffer, then pass it to Tesseract.js for text recognition. Ensure Tesseract.js is initialized with the correct language. ```typescript import { convert } from "pdf-raster"; import { createWorker } from "tesseract.js"; const worker = await createWorker("eng"); const [page] = await convert("./scan.pdf", { pages: [0], dpi: 300, }); const result = await worker.recognize(page.data); console.log(result.data.text); ``` -------------------------------- ### Next.js App Router Route Handler for PDF Conversion Source: https://context7.com/joshxfi/pdf-raster/llms.txt Implements a Next.js API route to handle PDF uploads and convert them to images. This server-side handler ensures that `convert()` is not called in Client Components or Edge routes. It returns base64 encoded image data suitable for previews. ```typescript // app/api/convert/route.ts import { NextResponse } from "next/server"; import { convert, PdfToImagesError } from "pdf-raster"; export const runtime = "nodejs"; // Required — do NOT use "edge" export async function POST(request: Request) { try { const formData = await request.formData(); const upload = formData.get("file"); if (!(upload instanceof File)) { return NextResponse.json( { code: "INVALID_INPUT", message: "Missing PDF upload." }, { status: 400 }, ); } const isPdf = upload.type === "application/pdf" || upload.name.toLowerCase().endsWith(".pdf"); if (!isPdf) { return NextResponse.json( { code: "INVALID_INPUT", message: "Only PDF uploads are supported." }, { status: 400 }, ); } const buffer = Buffer.from(await upload.arrayBuffer()); const pages = await convert(buffer, { dpi: 300, outputFormat: "webp", }); return NextResponse.json({ pages: pages.map((page) => ({ pageIndex: page.pageIndex, width: page.width, height: page.height, dpi: page.dpi, mimeType: page.mimeType, // base64 data URL — suitable for small previews src: `data:${page.mimeType};base64,${page.data.toString("base64")}`, })), }); } catch (error) { if (error instanceof PdfToImagesError) { return NextResponse.json( { code: error.code, message: error.message }, { status: 400 }, ); } return NextResponse.json( { code: "RENDER_ERROR", message: "Unexpected conversion failure." }, { status: 500 }, ); } } ``` -------------------------------- ### pdf-raster ConvertOptions type definition Source: https://context7.com/joshxfi/pdf-raster/llms.txt Defines the structure and types of all optional parameters accepted by the `convert()` function, including page selection, DPI, output format, password, cropping, and annotation rendering. ```typescript import { convert } from "pdf-raster"; // All fields are optional const pages = await convert("./document.pdf", { pages: [0, 1, 2], // number[] — zero-based page indices; omit for all pages dpi: 300, // number — render resolution (default: 300); truncated to integer outputFormat: "png", // "png" | "jpeg" | "webp" (default: "png") password: "secret", // string — for password-protected PDFs crop: { // Crop rectangle in rendered-image pixel coordinates x: 0, y: 0, width: 500, height: 400, }, renderAnnotations: true, // boolean — include annotations/form data (default: true) }); ``` -------------------------------- ### Handle pdf-raster Errors with PdfToImagesError Source: https://context7.com/joshxfi/pdf-raster/llms.txt Provides a robust way to handle errors during PDF conversion using the `PdfToImagesError` class. This allows for specific error code handling to manage issues like invalid input, incorrect options, or PDF parsing failures. ```typescript import { convert, PdfToImagesError } from "pdf-raster"; async function safePdfConvert(path: string) { try { return await convert(path, { pages: [0], dpi: 300 }); } catch (error) { if (error instanceof PdfToImagesError) { switch (error.code) { case "INVALID_INPUT": // Input was not a file path, Buffer, Uint8Array, or ArrayBuffer return { status: 400, error: error.message }; case "INVALID_OPTIONS": // Bad dpi, pages, or outputFormat value return { status: 400, error: error.message }; case "INVALID_PAGE_INDEX": // Requested page index out of range or not a non-negative integer return { status: 400, error: error.message }; case "INVALID_CROP": // Crop rectangle malformed or out of bounds return { status: 400, error: error.message }; case "PASSWORD_ERROR": // Encrypted PDF — password missing or wrong return { status: 403, error: error.message }; case "MALFORMED_PDF": // PDFium could not parse the document return { status: 422, error: error.message }; case "PDFIUM_UNAVAILABLE": // Native PDFium library failed to load return { status: 503, error: error.message }; case "RENDER_ERROR": // Unexpected native rendering failure after validation return { status: 500, error: error.message }; } } throw error; // re-throw non-pdf-raster errors } } ``` -------------------------------- ### ConvertedPage Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/api-reference.mdx Represents a single page converted from a PDF. ```APIDOC ## `ConvertedPage` ### Description Represents a single page converted from a PDF. ### Fields - **pageIndex** (number) - Required - Zero-based page index in the source document. - **data** (Buffer) - Required - Encoded image bytes for the rendered page. - **mimeType** (string) - Required - MIME type of the returned image buffer. Possible values: "image/png", "image/jpeg", "image/webp". - **width** (number) - Required - Rendered image width in pixels. - **height** (number) - Required - Rendered image height in pixels. - **dpi** (number) - Required - Effective DPI used to render the page. ``` -------------------------------- ### Converted Page Type Definition Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/index.mdx Defines the structure of the output for each converted PDF page, including its index, image data, MIME type, dimensions, and DPI. ```typescript type ConvertedPage = { pageIndex: number; data: Buffer; mimeType: "image/png" | "image/jpeg" | "image/webp"; width: number; height: number; dpi: number; }; ``` -------------------------------- ### Error Codes Source: https://github.com/joshxfi/pdf-raster/blob/main/docs/content/docs/api-reference.mdx List of possible error codes that can be returned by the convert function. ```APIDOC ## Error Codes ### Description List of possible error codes that can be returned by the convert function. ### Error Types - **INVALID_INPUT** (PdfToImagesError) - The input was not a supported file path or binary type. - **INVALID_OPTIONS** (PdfToImagesError) - One or more options were invalid, such as a non-positive DPI or unsupported output format. - **INVALID_PAGE_INDEX** (PdfToImagesError) - A requested page index was negative or out of range. - **INVALID_CROP** (PdfToImagesError) - The crop rectangle was malformed or exceeded the rendered page bounds. - **PASSWORD_ERROR** (PdfToImagesError) - The PDF password was missing or incorrect. - **MALFORMED_PDF** (PdfToImagesError) - The PDF could not be parsed by PDFium. - **PDFIUM_UNAVAILABLE** (PdfToImagesError) - The native PDFium library or binding could not be initialized. - **RENDER_ERROR** (PdfToImagesError) - An unexpected native rendering failure occurred after input validation. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.