如何在Node.js中获取PDF的像素维度?pdf2json返回未知单位值
解决PDF尺寸转像素适配pdf-poppler的问题
嘿,这个问题我之前也碰到过——pdf2json返回的其实是PDF原生的**点(pt)**单位(1pt = 1/72英寸),而pdf-poppler需要的是像素尺寸,核心就是要结合DPI(每英寸像素数)来做单位转换。
核心换算逻辑
PDF的默认单位是点,1英寸=72pt。而图片的像素数是由「英寸数 × DPI」决定的,所以换算公式很简单:
- 像素宽度 = (PDF宽度(pt) ÷ 72) × DPI
- 像素高度 = (PDF高度(pt) ÷ 72) × DPI
pdf-poppler的默认DPI是96(大部分屏幕的标准密度),如果你转换时自定义了DPI,记得同步修改这里的数值。
基于你现有代码的修正版
直接在你原来的pdf2json代码里加上转换逻辑就行:
const PDFParser = require("pdf2json"); let pdfParser = new PDFParser(); // 这里的DPI要和pdf-poppler转换时用的保持一致,默认是96 const TARGET_DPI = 96; pdfParser.loadPDF("./30x40.pdf"); pdfParser.on("pdfParser_dataReady", pdfData => { // pdf2json返回的是pt单位的尺寸 const pdfWidthPt = pdfData.formImage.Width; const pdfHeightPt = pdfData.formImage.Pages[0].Height; // 转换为像素,用Math.round取整(图片尺寸必须是整数) const widthPx = Math.round((pdfWidthPt / 72) * TARGET_DPI); const heightPx = Math.round((pdfHeightPt / 72) * TARGET_DPI); console.log(`Height (像素) : ${heightPx}`); console.log(`Width (像素) : ${widthPx}`); // 现在widthPx和heightPx就可以直接传给pdf-poppler用啦 });
备选方案:用pdf-lib更精准获取尺寸
如果你想更稳妥地读取PDF页面尺寸,也可以用pdf-lib这个库,它直接读取PDF的MediaBox(页面实际有效尺寸),返回的同样是pt单位,转换逻辑一样:
const { PDFDocument } = require("pdf-lib"); const fs = require("fs").promises; async function getPdfPixelSize(pdfPath, dpi = 96) { const pdfBuffer = await fs.readFile(pdfPath); const pdfDoc = await PDFDocument.load(pdfBuffer); const firstPage = pdfDoc.getPage(0); // 获取页面宽高(pt单位) const { width: ptWidth, height: ptHeight } = firstPage.getSize(); // 转成像素 return { width: Math.round((ptWidth / 72) * dpi), height: Math.round((ptHeight / 72) * dpi) }; } // 调用示例 getPdfPixelSize("./30x40.pdf").then(size => { console.log("PDF像素尺寸:", size); });
重要提醒
- 务必保证这里的DPI和你在pdf-poppler中设置的
dpi参数完全一致!比如你转换时用了dpi: 300,那上面的TARGET_DPI也要改成300,不然像素尺寸会不匹配。 - 一定要用
Math.round()把结果转成整数,因为图片的宽高不能是小数。
内容的提问来源于stack exchange,提问作者DINO
相关产品推荐
相关产品推荐

