使用 PDFJS 和 NodeJS 提取 PDF 页面大小

虽然大多数 PDF 只有一种页面大小(例如 DIN A4 或纵向的 Letter),PDF 有时也有页面具有与同一文档中其他页面不同的大小或方向(被视为另一种大小)。

本文提供了一个易于重用的示例,说明如何在 NodeJS 中使用 PDFJS(虽然在浏览器中同样容易)提取 PDF

它基于此之前的文章关于如何使用 PDFJS 从 PDF 文档读取所有页面,所以一定要先查看它。

首先安装所需的依赖:

install_pdfjs2.sh
npm install bereich pdfjs-dist

然后你可以使用此源代码读取 mypdf.pdf 的页面大小:

extract_pdf_page_sizes.js
const pdfjs = require('pdfjs-dist');
const bereich = require('bereich');

class PageSize {
  constructor(width, height) {
    this.width = width;
    this.height = height
  }
}

function getPageSize (page) {
    const [x, y, w, h] = page.pageInfo.view;
    const width = w - x;
    const height = h - y;
    const rotate = page.pageInfo.rotate;
    // 考虑旋转
    return (rotate === 90 || rotate === 270)
        ? new PageSize(height, width) : new PageSize(width, height);
}

async function readPDFPageSizes() {
  const pdf = await pdfjs.getDocument('mypdf.pdf');
  const numPages = pdf.numPages;

  const pageNumbers = Array.from(bereich(1, numPages));
  // 开始读取所有页面 1...numPages
  const promises = pageNumbers.map(pageNo => pdf.getPage(pageNo));
  // 等待所有页面被读取
  const pages = await Promise.all(promises);
  // 你可以在此对页面做些处理。
  return pages.map(getPageSize);
}

readPDFPageSizes()
    .then(pageSizes => {console.log(pageSizes)})
    .catch(err => {console.error(`Error while reading PDF: ${err}`)})

使用具有单个 A4 页面的文档运行此命令将产生

page_sizes_output.txt
[ PageSize { width: 595, height: 842 } ]

注意宽度和高度单位是 pt(点)。一个 pt 定义为 1/72 英寸。DIN A4 页面(纵向)是 595x842pt,因此你在这里看到这些值。 请参见此 TechOverflow 文章了解将 pt 转换为 mm 和英寸的代码。


Check out similar posts by category: Javascript, PDF