useDocumentSaving

Builds the final PDF from the loaded document and the changes recorded during the session (see Building a PDF application for how changes are tracked).

const { prepareDocument, downloadDocument } = useDocumentSaving()

Both functions are asynchronous, accept the same options, and throw DocumentNotLoadedError when no document is loaded:

  • prepareDocument(options?) resolves with the document bytes (Uint8Array) for your own handling, such as uploading to a server.
  • downloadDocument(options?) builds the same bytes and saves them on the user's device as a file.

Options

OptionDefaultWhat it does
pageIdsall pagesThe pages to save, as an iterable of page ids, in the order they appear in the saved PDF: [thirdPageId, firstPageId] saves the third page first. The other pages are left out. Without it, the saved PDF has the current pages in their current order.
returnOriginalIfUnchangedtrueWhen the saved document has no changes, the original buffer passed to loadPdf is returned directly, with no copy. Set to false when you intend to transfer or mutate the returned buffer (e.g. pass it to a worker), otherwise the loaded document's ArrayBuffer gets detached and later document reads throw.

pageIds must list at least one page, and each page at most once, or the call throws InvalidInputError; so does an id of a page that doesn't exist or is deleted. To save a page twice, duplicate it first with usePageDuplicate. A Set keeps the ids unique and in insertion order.

Example

import { useDocumentSaving } from '@sdk-pdf/react'

function useUploadDocument() {
  const { prepareDocument } = useDocumentSaving()

  return async () => {
    // The buffer is transferred to fetch, so don't hand out the original.
    const buffer = await prepareDocument({ returnOriginalIfUnchanged: false })
    await fetch('/api/documents', { method: 'PUT', body: buffer as BodyInit })
  }
}

function useDownloadPages() {
  const { downloadDocument } = useDocumentSaving()

  // Saves only the given pages, such as the ones the user picked in a page list.
  return (pageIds: Set<string>) => downloadDocument({ pageIds })
}

To save only when the document has changed since the last save, compare revisions with useDocumentRevisionGetter.

On this page