Fix sideways scanned images by detecting and rotating landscape pages

Scanners store landscape content with a PDF /Rotate flag that pdf2pic
doesn't always apply. Now uses a square bounding box with
preserveAspectRatio, then detects landscape output and rotates to
portrait with sharp.

Made-with: Cursor
This commit is contained in:
Randall Stillwell 2026-04-07 13:10:03 -05:00
parent f87ab36493
commit d56b1a27ec

View file

@ -12,9 +12,10 @@ export async function pdfToImages(pdfBuffer: Buffer): Promise<PageImage[]> {
const converter = fromBuffer(pdfBuffer, { const converter = fromBuffer(pdfBuffer, {
density: 200, density: 200,
format: "jpeg", format: "jpeg",
width: 1600, width: 2200,
height: 2200, height: 2200,
quality: 90, quality: 90,
preserveAspectRatio: true,
}); });
const pageCount = await getPdfPageCount(pdfBuffer); const pageCount = await getPdfPageCount(pdfBuffer);
@ -23,12 +24,21 @@ export async function pdfToImages(pdfBuffer: Buffer): Promise<PageImage[]> {
for (let i = 1; i <= pageCount; i++) { for (let i = 1; i <= pageCount; i++) {
const result = await converter(i, { responseType: "buffer" }); const result = await converter(i, { responseType: "buffer" });
if (result.buffer) { if (result.buffer) {
const metadata = await sharp(result.buffer).metadata(); let buf = result.buffer as Buffer;
let meta = await sharp(buf).metadata();
// Scanners often store landscape content with a PDF /Rotate flag that
// pdf2pic may not apply. Detect and rotate to portrait orientation.
if ((meta.width || 0) > (meta.height || 0)) {
buf = await sharp(buf).rotate(90).jpeg({ quality: 90 }).toBuffer();
meta = await sharp(buf).metadata();
}
images.push({ images.push({
page: i, page: i,
buffer: result.buffer as Buffer, buffer: buf,
width: metadata.width || 1600, width: meta.width || 1600,
height: metadata.height || 2200, height: meta.height || 2200,
}); });
} }
} }