如何使用PyPDF2将空白页插入pdf



问题:我有一个页码数组,其中空白页需要插入或合并到原始pdf中。示例)[1,3,5,8,10]。我需要这些页是空白的,然后原始文档将增加页码。

我有这个Python脚本在pdf文件中搜索特定的文本,该文本表示字母的结尾。每封信的页数都不一样。使用PyPDF2,我尝试合并()与目录内的单个空白页pdf, insertBlankPage(), addPage(), addBlankPage。我遇到的问题是空白页覆盖了原始页。第一页应该是空白的,但后面的页是错误的。看起来空白页被写在现有页面的顶部,而不是在页码处插入。

如何在数组中列出的页码处插入空白页?下面是代码。页的输出数组不需要是字符串;它被转换成一个字符串,带入另一个程序。如果我可以使用Python添加空白页,那么页码数组就不需要是字符串了。

import PyPDF2, re
pdfIn = open('sample_letter.pdf', 'rb')
pdfFile = PyPDF2.PdfFileReader(pdfIn)
NumPages = pdfFile.getNumPages()
string = "Text I am searching for."
separator = ', '
mystring = ""
def end_of_letter():
pages = []
for page in range(NumPages):
pgObj = pdfFile.getPage(page)
text = pgObj.extractText()
match = re.search(string, text)
if match:
pages.append(str(page + 1))
mystring = separator.join(pages)
print(mystring)
return mystring

end_of_letter()

我能够找到一个解决方案,成功地遍历pdf,找到字母末尾的文本,然后插入空白页。下面的代码。

"""This program will take an input pdf file and search for a string that signifies the end of a letter.
After the end of the letter is found based on a string, a blank page is added. The output file is then
created in the directory with blank pages added """
import PyPDF2, re
pdfIn = open('sample_letter.pdf', 'rb')
pdfFile = PyPDF2.PdfFileReader(pdfIn)
NumPages = pdfFile.getNumPages()
string = "Text I am searching for"
output = PyPDF2.PdfFileWriter()
outputStream = open('added_blank_pages.pdf', 'wb')

def end_of_letter():
pages = []
for page in range(NumPages):
pgObj = pdfFile.getPage(page)
text = pgObj.extractText()
match = re.search(string, text)
output.addPage(pgObj)
if match:
pages.append(page + 1)
output.addBlankPage()
output.write(outputStream)
print(pages)

end_of_letter()

我知道这个问题是专门为pyPDF2,但我使用不同的PDF库,pikepdf,这对我来说更快,我想分享我的代码:

import pikepdf
import sys
if len(sys.argv) == 1:
exit("No File provided")
with pikepdf.open(sys.argv[1], allow_overwriting_input=True) as pdf:
print(f"Editing {sys.argv[1]}")
length = len(pdf.pages)
pdf.add_blank_page(page_size=(pdf.pages[0]["/MediaBox"][2], 
pdf.pages[0]["/MediaBox"][3]))
for i in range(1, 2*length-2, 2):
print(f"inserting  blank page at {i}")
pdf.pages.insert(i, pdf.pages[-1])
pdf.save()

你可以对文件夹中的每个文件执行如下命令(Powershell):

dir ~/Downloads | ? -Property Extension -eq .pdf | % {py .addEmpty.py "$_"}

只是想分享我与另一个python库一起使用的方法,它解决了我今天的问题。我在Windows 11上安装了Python 3.10.10。

# Import library
# More, visit https://pypi.org/project/PyMuPDF/
import fitz
# Load input file
doc = fitz.open("file_to_be_edited.pdf")
# You can see the width and height of a pdf file like so
# print('Width: ',doc[0].rect.width,'Height: ',doc[0].rect.height)
# Insert a blank page before page 2, after page 1
# First page starts as 0, not 1
# Width and height are points/pt
# More see https://pymupdf.readthedocs.io/en/latest/document.html#Document.new_page
doc.new_page(pno=1, width=612, height=792)
doc.save("output_file_with_blank_page_inserted.pdf")