gpt4 book ai didi

使用 pyPDF 删除空白页的 Python 脚本

转载 作者:太空狗 更新时间:2023-10-29 21:50:56 48 4
gpt4 key购买 nike

我正在尝试使用 pyPDF 编写几个 python 脚本,将 PDF 页面拆分为六个单独的页面,正确排序它们(通常正面和背面打印,因此每个其他页面都需要以不同方式排序),并删除结果输出文档末尾的空白页。

我编写了以下脚本来剪切 PDF 页面并重新排序。将每页分成两列,每列分为三页。我对 python 不是很有经验,所以请原谅我做的不正确。

#!/usr/bin/env python
import copy, sys
from pyPdf import PdfFileWriter, PdfFileReader
input = PdfFileReader(sys.stdin)
output = PdfFileWriter()

for i in range(0,input.getNumPages(),2):
p = input.getPage(i)
q = copy.copy(p)
r = copy.copy(p)
s = copy.copy(p)
t = copy.copy(p)
u = copy.copy(p)
(x, y) = p.mediaBox.lowerLeft
(w, h) = p.mediaBox.upperRight

p.mediaBox.lowerLeft = (x, 2 * h / 3)
p.mediaBox.upperRight = (w / 2, h)

q.mediaBox.lowerLeft = (w / 2, 2 * h / 3)
q.mediaBox.upperRight = (w, h)

r.mediaBox.lowerLeft = (x, h / 3)
r.mediaBox.upperRight = (w / 2, 2 * h / 3)

s.mediaBox.lowerLeft = (w / 2, h / 3)
s.mediaBox.upperRight = (w, 2 * h / 3)

t.mediaBox.lowerLeft = (x, y)
t.mediaBox.upperRight = (w / 2, h / 3)

u.mediaBox.lowerLeft = (w / 2, y)
u.mediaBox.upperRight = (w, h / 3)

a = input.getPage(i+1)
b = copy.copy(a)
c = copy.copy(a)
d = copy.copy(a)
e = copy.copy(a)
f = copy.copy(a)
(x, y) = a.mediaBox.lowerLeft
(w, h) = a.mediaBox.upperRight

a.mediaBox.lowerLeft = (x, 2 * h / 3)
a.mediaBox.upperRight = (w / 2, h)

b.mediaBox.lowerLeft = (w / 2, 2 * h / 3)
b.mediaBox.upperRight = (w, h)

c.mediaBox.lowerLeft = (x, h / 3)
c.mediaBox.upperRight = (w / 2, 2 * h / 3)

d.mediaBox.lowerLeft = (w / 2, h / 3)
d.mediaBox.upperRight = (w, 2 * h / 3)

e.mediaBox.lowerLeft = (x, y)
e.mediaBox.upperRight = (w / 2, h / 3)

f.mediaBox.lowerLeft = (w / 2, y)
f.mediaBox.upperRight = (w, h / 3)

output.addPage(p)
output.addPage(b)
output.addPage(q)
output.addPage(a)
output.addPage(r)
output.addPage(d)
output.addPage(s)
output.addPage(c)
output.addPage(t)
output.addPage(f)
output.addPage(u)
output.addPage(e)

output.write(sys.stdout)

然后我使用以下脚本删除空白页。

#!/usr/bin/env python
import copy, sys
from pyPdf import PdfFileWriter, PdfFileReader
input = PdfFileReader(sys.stdin)
output = PdfFileWriter()

for i in range(0,input.getNumPages()):
p = input.getPage(i)

text = p.extractText()

if (len(text) > 10):
output.addPage(p)

output.write(sys.stdout)

问题似乎是,虽然页面明显被裁剪了,但文本绘制命令仍然存在。这些页面都没有被扫描,所以如果它们是空白的,那么它们真的是空白的。有没有人对我可以采取不同的方式或可能采取完全不同的方法来删除空白页有任何想法?如果有任何帮助,我将不胜感激。

最佳答案

PdfFileReader 有一个方法 getPage(self, page number) 返回一个对象 PageObject,而这个对象又有一个方法 getContents,如果页面是空白的,它将返回None。因此,使用您的 pdf 对象 getNumPages(),使用 if getPage(i).getContents(): 进行迭代,将命中收集到要输出的页码列表中。

关于使用 pyPDF 删除空白页的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6310251/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com