如何使用PDF.js确定PDF的自然页面大小

时间:2019-06-03 14:56:01

标签: javascript pdf.js

我在发现设置中使用pdf.js来确定许多PDF文档的高度和宽度(以像素为单位)。

在下面的代码片段中,我将提取一个8.5 x 11 Word文档的缓冲区,该文档打印为PDF。我收到的退货是大小除以4.16666 ...。

我发现,如果我通过4.166666666666667667的比例,我将非常接近文档的实际大小,通常在几百万分之一像素之内。


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页面的自然高度和宽度。

谢谢!

1 个答案:

答案 0 :(得分:0)

在进一步审查此问题时,我确定以像素为单位的输出页面大小假设DPI为72。我可以将值(612、792)除以72,然后将其乘以300以得到我的期望值:2550和3300。

let dimensions = data.getViewport(1).viewBox.map(n => n / 72 * 300)
 //[ 0, 0, 2550, 3300 ]
相关问题