Skip to content

Allow renderPageAsImage to return a data URL #40

@vladiantio

Description

@vladiantio

Describe the feature

I propose enhancing the renderPageAsImage function adding a toDataURL option:

  • Introduce a new boolean option, toDataURL, to the options object.
  • When options.toDataURL is set to true, the function's return type should be Promise<string>, resolving with the data URL of the rendered page.
  • When the option is false or not provided, the function should maintain its existing behavior, returning a Promise<ArrayBuffer>.

This can be achieved with TypeScript overloads to ensure type safety:

// Returns a buffer by default
function renderPageAsImage(
  data: DocumentInitParameters['data'] | PDFDocumentProxy,
  pageNumber: number,
  options?: {
    // ... other options
    toDataURL?: false
  },
): Promise<ArrayBuffer>

// Returns a data URL string when toDataURL is true
function renderPageAsImage(
  data: DocumentInitParameters['data'] | PDFDocumentProxy,
  pageNumber: number,
  options: {
    // ... other options
    toDataURL: true
  },
): Promise<string>

Example Usage:

import { getDocumentProxy, renderPageAsImage } from 'unpdf'

const buffer = await readFile('./document.pdf')
const pdf = await getDocumentProxy(new Uint8Array(buffer))
const pageNumber = 1

// Get the image as a data URL for web embedding
const dataUrl = await renderPageAsImage(pdf, pageNumber, {
  toDataURL: true,
})

// Example: <img src="data:image/png;base64,iVBORw0KGgo...">
const html = `<img src="${dataUrl}">`

// ...

Additional information

  • Would you be willing to help implement this feature?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions