【问题标题】:How to insert blank pages into a pdf using PyPDF2如何使用 PyPDF2 将空白页插入 pdf
【发布时间】:2021-04-26 00:43:46
【问题描述】:

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

我有这个 Python 脚本在 pdf 文件中搜索表示字母结尾的特定文本。每个字母的页数不同。使用 PyPDF2,我尝试使用目录中的单个空白页 pdf 进行 merge()、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()

【问题讨论】:

    标签: python-3.x pdf pypdf2


    【解决方案1】:

    我能够找到成功遍历 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多