fix(pdf): stream print pages with per-page budget and cleanup (#354)

* fix(pdf): stream print pages with per-page budget and cleanup

* fix(sheets): satisfy exactOptionalPropertyTypes for LazyCellMatch rawValue

* fix(pdf): render over-budget pages at reduced scale instead of skipping

- Keep the skip only for degenerate NaN/zero-area pages; pages exceeding MAX_PAGE_PIXELS now render at scale * sqrt(MAX_PAGE_PIXELS / (w*h)). Per-page cleanup retained.

Test updated: huge page renders reduced (2 imgs), NaN skipped; getPage mock selects viewports by page number so measure+render passes align.

* fix(pdf): update print tests for measure-then-render getPage counts

---------

Co-authored-by: Aniruddha Adak <aniruddhaadak80@users.noreply.github.com>
This commit is contained in:
ANIRUDDHA ADAK
2026-09-15 11:20:18 +08:00
committed by GitHub
co-authored by Aniruddha Adak
parent e064f3ad68
commit 692c929c8d
2 changed files with 105 additions and 18 deletions
+55 -14
View File
@@ -1,4 +1,4 @@
import type { PDFDocumentProxy, PDFPageProxy } from 'pdfjs-dist'
import type { PDFDocumentProxy } from 'pdfjs-dist'
/** Baseline raster density (previous behavior — quality never drops below this). */
const BASE_DPI = 150
@@ -21,8 +21,9 @@ const MAX_PRINT_PIXELS = 150_000_000
export function printScaleForAreas(areas: number[]): number {
const target = TARGET_DPI / 72
const total = areas.reduce((sum, area) => sum + area, 0)
if (!(total > 0)) return target
if (!(total > 0) || !Number.isFinite(total)) return target
const atTarget = total * target * target
if (!Number.isFinite(atTarget) || atTarget <= 0) return target
if (atTarget <= MAX_PRINT_PIXELS) return target
return Math.max(BASE_DPI / 72, target * Math.sqrt(MAX_PRINT_PIXELS / atTarget))
}
@@ -45,23 +46,63 @@ export async function printPdf(doc: PDFDocumentProxy, pages?: number[]): Promise
pages && pages.length > 0
? [...new Set(pages)].filter((n) => n >= 1 && n <= doc.numPages).sort((a, b) => a - b)
: Array.from({ length: doc.numPages }, (_x, i) => i + 1)
const fetched: PDFPageProxy[] = []
// First pass: measure each page at unit scale to budget the shared scale.
// Stream one page at a time so no PDFPageProxy outlives its render — the
// previous two-pass held all pages alive plus 2× viewports.
const areas: number[] = []
for (const n of targets) {
const page = await doc.getPage(n)
fetched.push(page)
const unit = page.getViewport({ scale: 1 })
areas.push(unit.width * unit.height)
try {
const unit = page.getViewport({ scale: 1 })
const area = unit.width * unit.height
areas.push(Number.isFinite(area) && area > 0 ? area : 0)
} finally {
try {
page.cleanup()
} catch {
/* older pdf.js without cleanup */
}
}
}
const scale = printScaleForAreas(areas)
for (const page of fetched) {
const viewport = page.getViewport({ scale })
canvas.width = Math.floor(viewport.width)
canvas.height = Math.floor(viewport.height)
await page.render({ canvas, viewport }).promise
const img = document.createElement('img')
img.src = canvas.toDataURL('image/jpeg', 0.92)
root.appendChild(img)
// Second pass: render at the budgeted scale, bounding each canvas to the
// pixel budget so a single huge drawing (e.g. 200in² at 150 DPI → >1Bpx)
// cannot OOM the renderer even at the floor scale.
const MAX_PAGE_PIXELS = MAX_PRINT_PIXELS
for (const n of targets) {
const page = await doc.getPage(n)
try {
let viewport = page.getViewport({ scale })
let w = Math.floor(viewport.width)
let h = Math.floor(viewport.height)
if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0) {
// Skip a single corrupt page rather than aborting the whole print.
continue
}
if (w * h > MAX_PAGE_PIXELS) {
// A missing page is worse than a softer one: render this page at its
// own reduced scale instead of dropping it.
const pageScale = scale * Math.sqrt(MAX_PAGE_PIXELS / (w * h))
viewport = page.getViewport({ scale: pageScale })
w = Math.floor(viewport.width)
h = Math.floor(viewport.height)
if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0) {
continue
}
}
canvas.width = w
canvas.height = h
await page.render({ canvas, viewport }).promise
const img = document.createElement('img')
img.src = canvas.toDataURL('image/jpeg', 0.92)
root.appendChild(img)
} finally {
try {
page.cleanup()
} catch {
/* older pdf.js without cleanup */
}
}
}
canvas.width = 0
canvas.height = 0
+50 -4
View File
@@ -39,8 +39,13 @@ describe('printPdf', () => {
await printPdf(doc)
expect(getPage).toHaveBeenCalledTimes(3)
expect(getPage).toHaveBeenCalledTimes(6)
expect(getPage).toHaveBeenNthCalledWith(1, 1)
expect(getPage).toHaveBeenNthCalledWith(2, 2)
expect(getPage).toHaveBeenNthCalledWith(3, 3)
expect(getPage).toHaveBeenNthCalledWith(4, 1)
expect(getPage).toHaveBeenNthCalledWith(5, 2)
expect(getPage).toHaveBeenNthCalledWith(6, 3)
expect(render).toHaveBeenCalledTimes(3)
expect(imgsAtPrintTime).toBe(3)
expect(window.print).toHaveBeenCalledTimes(1)
@@ -63,9 +68,12 @@ describe('printPdf', () => {
await printPdf(doc, [4, 2, 99, 0])
// Out-of-range entries are dropped; the rest render in document order.
expect(getPage).toHaveBeenCalledTimes(2)
// Measure pass fetches each target first, then the render pass refetches.
expect(getPage).toHaveBeenCalledTimes(4)
expect(getPage).toHaveBeenNthCalledWith(1, 2)
expect(getPage).toHaveBeenNthCalledWith(2, 4)
expect(getPage).toHaveBeenNthCalledWith(3, 2)
expect(getPage).toHaveBeenNthCalledWith(4, 4)
expect(render).toHaveBeenCalledTimes(2)
expect(imgsAtPrintTime).toBe(2)
expect(window.print).toHaveBeenCalledTimes(1)
@@ -117,6 +125,8 @@ describe('printScaleForAreas', () => {
it('falls back to the target for empty or degenerate input', () => {
expect(printScaleForAreas([])).toBeCloseTo(200 / 72, 10)
expect(printScaleForAreas([0])).toBeCloseTo(200 / 72, 10)
expect(printScaleForAreas([Number.NaN])).toBeCloseTo(200 / 72, 10)
expect(printScaleForAreas([Number.POSITIVE_INFINITY])).toBeCloseTo(200 / 72, 10)
})
it('scales down proportionally over budget, never below the 150 DPI baseline', () => {
@@ -143,7 +153,7 @@ describe('printPdf render scale', () => {
it('renders small documents at 200 DPI (all pages measured before the render pass)', async () => {
const { doc, scales, getPage } = scalesDoc(2)
await printPdf(doc)
expect(getPage).toHaveBeenCalledTimes(2)
expect(getPage).toHaveBeenCalledTimes(4)
expect(scales).toEqual([1, 1, 200 / 72, 200 / 72])
})
@@ -159,9 +169,45 @@ describe('printPdf render scale', () => {
it('budgets a page subset on its own: two pages out of a huge document print at 200 DPI', async () => {
const { doc, scales, getPage } = scalesDoc(200)
await printPdf(doc, [7, 3])
expect(getPage).toHaveBeenCalledTimes(2)
expect(getPage).toHaveBeenCalledTimes(4)
expect(getPage).toHaveBeenNthCalledWith(1, 3)
expect(getPage).toHaveBeenNthCalledWith(2, 7)
expect(getPage).toHaveBeenNthCalledWith(3, 3)
expect(getPage).toHaveBeenNthCalledWith(4, 7)
expect(scales).toEqual([1, 1, 200 / 72, 200 / 72])
})
it('streams pages and cleans up each one, bounding a corrupt huge page', async () => {
const cleanups: number[] = []
const viewports: Array<{ width: number; height: number }> = [
{ width: 612, height: 792 },
{ width: Number.NaN, height: Number.NaN },
{ width: 1e6, height: 1e6 },
]
const getPage = vi.fn(async (n: number) => {
const vp = viewports[n - 1]!
return {
getViewport: vi.fn(({ scale }: { scale: number }) => ({
width: vp.width * scale,
height: vp.height * scale,
})),
render: vi.fn(() => ({ promise: Promise.resolve() })),
cleanup: vi.fn(() => cleanups.push(1)),
}
})
const doc = { numPages: 3, getPage } as unknown as PDFDocumentProxy
// The print root is removed on afterprint, so snapshot the image count
// at print time like the other tests do.
let imgsAtPrintTime = 0
;(window.print as ReturnType<typeof vi.fn>).mockImplementation(() => {
imgsAtPrintTime = document.querySelectorAll('.pdf-print-root img').length
window.dispatchEvent(new Event('afterprint'))
})
await printPdf(doc)
// each page cleaned up twice: once after measure, once after render/skip
expect(cleanups).toHaveLength(6)
// NaN pages are skipped and huge pages render at their own reduced scale
// rather than aborting the whole print
expect(imgsAtPrintTime).toBe(2)
})
})