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文档。如果我正确理解代码中提到的 upperRight
、upperLeft
(和其他)变量,那么这就是 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 中,有两种获取横向页面的方法:
- 定义宽度 > 高度的页面。
- 定义纵向页面(宽度 < 高度)和旋转(90 度、270 度等)。
您的示例 PDF 使用第二种方式:所有页面均为 595x842,旋转 270 度。不考虑旋转会导致垂直方向被解释为水平方向,反之亦然。
关于python - pyPdf如何理解文档边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33714894/