python - pyPdf如何理解文档边界?

标签 python pdf pypdf

Here我找到了分割 pdf 页面的代码。

#!/usr/bin/env python
import copy, sys
from pyPdf import PdfFileWriter, PdfFileReader
input = PdfFileReader(sys.stdin)
output = PdfFileWriter()
for p in [input.getPage(i) for i in range(0,input.getNumPages())]:
    q = copy.copy(p)
    (w, h) = p.mediaBox.upperRight
    p.mediaBox.upperRight = (w/2, h)
    q.mediaBox.upperLeft = (w/2, h)
    output.addPage(p)
    output.addPage(q)
output.write(sys.stdout)

如果一个页面包含另外四个页面,如下所示:

+-------+-------+
|   1   |   2   |
|-------+-------|
|   3   |   4   |
+-------+-------+

然后代码会将其拆分为两个页面(按此顺序),其中包含另外两个页面:

+-------+-------+
|   3   |   4   |
+-------+-------+

+-------+-------+
|   1   |   2   |
+-------+-------+

您可以测试它,例如上following文档。如果我正确理解代码中提到的 upperRightupperLeft (和其他)变量,那么这就是 pyPdf 看到的文档表示:

UL(0,10)        UR(10,10)
+-------+-------+
|   1   |   2   |
|-------+-------|
|   3   |   4   |
+-------+-------+
LL(0,0)         LR(10,0)

UL(x,y) = UpperLeft
UR(x,y) = UpperRight
LL(x,y) = LowerLeft
LR(x,y) = LowerRight

根据提到的代码:

(w, h) = p.mediaBox.upperRight
p.mediaBox.upperRight = (w/2, h)
q.mediaBox.upperLeft = (w/2, h)

我期待这个输出:

p:
+-------+
|   1   |
|-------+
|   3   |
+-------+

q:
+-------+
|   2   |
|-------+
|   4   |
+-------+

我在这里缺少什么?

最佳答案

在 PDF 中,有两种获取横向页面的方法:

  1. 定义宽度 > 高度的页面。
  2. 定义纵向页面(宽度 < 高度)和旋转(90 度、270 度等)。

您的示例 PDF 使用第二种方式:所有页面均为 595x842,旋转 270 度。不考虑旋转会导致垂直方向被解释为水平方向,反之亦然。

关于python - pyPdf如何理解文档边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33714894/

相关文章:

python - Django REST Framework - CurrentUserDefault 使用

python - 从 beautifulsoup 替换\n\t

python - 如何用 python 编写处理文本流的程序?

python - 将 bash 数组传递给 python 列表

java - iText PDF 创建错误

ruby-on-rails - 在新浏览器选项卡中打开的 PDF 文档中创建链接

regex - 从pdf文件中提取邮政地址

python - pypdf python工具

python - 使用 PyPDF2 去除 PDF 上的水印

python - PyPDF4 - 导出的 PDF 文件大小太大