Files
documenso/packages/lib/client-only/download-pdf.ts
T
ephraimduncan e6ad94a58f feat: add pending signed pdf downloads for recipients
Recipients can download a PDF that contains the inserted fields while
the envelope is in the PENDING state.

The token file route accepts the `pending` version. The PDF contains
only the fields from recipients who signed and the fields of the
recipient who makes the request. This is the same set of fields that
the signing page shows to the recipient.

The signing page and the completion page show the download dialog for
pending envelopes. The dialog does not show the "Partial" button for
legacy envelopes.
2026-08-11 15:52:39 +00:00

70 lines
1.8 KiB
TypeScript

import type { EnvelopeItem } from '@prisma/client';
import { getEnvelopeItemPdfUrl } from '../utils/envelope-download';
import { downloadFile } from './download-file';
type DocumentVersion = 'original' | 'signed' | 'pending';
type DownloadPDFProps = {
envelopeItem: Pick<EnvelopeItem, 'id' | 'envelopeId'>;
token: string | undefined;
fileName?: string;
/**
* Specifies which version of the document to download.
* 'signed': Downloads the signed version (default).
* 'original': Downloads the original version.
* 'pending': Downloads the original document with currently-inserted fields burned in.
* Only valid while the envelope is in PENDING status.
*/
version?: DocumentVersion;
};
const versionToFilenameSuffix = (version: DocumentVersion): string => {
switch (version) {
case 'signed':
return '_signed.pdf';
case 'pending':
return '_pending.pdf';
case 'original':
return '.pdf';
}
};
/**
* Fetches a PDF for an envelope item and returns it as a blob alongside the
* filename it should be saved as. Throws on non-OK responses.
*/
export const fetchPDF = async ({ envelopeItem, token, fileName, version = 'signed' }: DownloadPDFProps) => {
const downloadUrl = getEnvelopeItemPdfUrl({
type: 'download',
envelopeItem: envelopeItem,
token,
version,
});
const response = await fetch(downloadUrl);
if (!response.ok) {
throw new Error(`Failed to download PDF: ${response.status}`);
}
const blob = await response.blob();
const baseTitle = (fileName ?? 'document').replace(/\.pdf$/, '');
return {
filename: `${baseTitle}${versionToFilenameSuffix(version)}`,
blob,
};
};
export const downloadPDF = async (options: DownloadPDFProps) => {
const { filename, blob } = await fetchPDF(options);
downloadFile({
filename,
data: blob,
});
};