我在发现设置中使用 pdf.js 来确定多个 PDF 文档的高度和宽度(以像素为单位)。
在下面的代码片段中,我将一个 8.5 x 11 Word 文档的缓冲区打印为 PDF。我收到的回报是大小除以 4.16666....
我发现,如果我通过 4.166666666666667 的比例,我会非常接近文档的实际大小,通常在百万分之几像素之内。
function process(images) {
//All Images in the array have the same path
let pdfdoc = images[0].ImageFilePath
fs.readFile(pdfdoc, (err, imageBuffer) => {
let u = PDFJSLib.getDocument(imageBuffer)
images.forEach(img => {
//if we failed to read the pdf, we need to mark each page for manual review.
if(err) {
console.error(err)
postMessage({height:-1, width:-1, ImageFilePath:img.ImageFilePath, DocId:img.DocId, PageId:img.PageId})
}
else {
u.promise.then(pdf => {
pdf.getPage(img.PageNumber).then(data => {
console.log(data.getViewport(1).width)
console.log(data.getViewport(1).height)
})
});
}
})
})
}
我期望的输出是要记录到控制台的自然宽度和高度。我需要了解应该传递什么比例,以及哪些因素决定该比例值。我可以安全地传入 4.166666666666667 并知道我每次都获得页面的自然高度和宽度吗?
我发现的与此相关的其他问题通常与将 PDF 传递给查看器有关 - 我没有这样做。同样,我的目标是简单地发现给定 PDF 页面的自然高度和宽度。
谢谢!
在进一步审查此问题时,我确定输出页面大小(以像素为单位)假设 DPI 为 72。我可以将值 (612, 792) 除以 72,然后将它们乘以 300 以获得我的预期数字:2550 和 3300 .
let dimensions = data.getViewport(1).viewBox.map(n => n / 72 * 300)
//[ 0, 0, 2550, 3300 ]
从 getViewport 获取 pdf 宽度和高度(以英寸为单位)
let viewport= data.getViewport({ scale: 1 });
let inchHeight=viewport.height/72;
let inchWidth=viewport.width/72;
转换为像素
let pixleHeight=inchHeight*96;
let pixleWidth=inchWidth*96;
从 Adobe 中查找文档页面尺寸(英寸) -> 在 Adobe 中打开文档,转到文件 -> 属性或 ctrl+d