Skip to content

The Open Source DocuSign Alternative.

fix: handle malformed pdf cropbox/mediabox entries (#2668)

Lucas Smith0b9a23c5507c
diff --git a/packages/lib/server-only/pdf/get-page-size.ts b/packages/lib/server-only/pdf/get-page-size.ts
index 8c88912b0..982810f1d 100644
--- a/packages/lib/server-only/pdf/get-page-size.ts
+++ b/packages/lib/server-only/pdf/get-page-size.ts
@@ -13,14 +13,31 @@ const MIN_CERT_PAGE_HEIGHT = 300;
* Falls back to MediaBox when it's smaller than CropBox, following typical PDF reader behavior.
*/
export const getPageSize = (page: PDFPage) => {
- const cropBox = page.getCropBox();
- const mediaBox = page.getMediaBox();
+ let mediaBox;
+ let cropBox;
- if (mediaBox.width < cropBox.width || mediaBox.height < cropBox.height) {
- return mediaBox;
+ try {
+ mediaBox = page.getMediaBox();
+ } catch {
+ // MediaBox lookup can fail for malformed PDFs where the entry is not a valid PDFArray.
}
- return cropBox;
+ try {
+ cropBox = page.getCropBox();
+ } catch {
+ // CropBox lookup can fail for malformed PDFs where the entry is not a valid PDFArray.
+ }
+
+ if (mediaBox && cropBox) {
+ if (mediaBox.width < cropBox.width || mediaBox.height < cropBox.height) {
+ return mediaBox;
+ }
+
+ return cropBox;
+ }
+
+ // If either box is missing or invalid, fall back to MediaBox if available, otherwise CropBox, or default to A4 size.
+ return mediaBox || cropBox || PDF_SIZE_A4_72PPI;
};
export const getLastPageDimensions = (pdfDoc: PDF): { width: number; height: number } => {