使用python 3中另一个PDF的页面替换PDF中的特定页面

时间:2017-11-30 05:44:16

标签: python python-3.x pypdf2

我正在使用pypdf2突出显示Pdf文件中特定页面中的文本。因此,我只得到一个带有高亮文本作为输出的页面。现在,我想在原始pdf文件中替换此页面。

我也试过" search ="从abode到相同文件本身的高亮显示的参数。但是,它无效。

我不熟悉PDF.Sorry,如果这个问题听起来有点天真。

2 个答案:

答案 0 :(得分:0)

获取文字处理程序或页面布局软件。将PDF转换为您的软件可以读取的格式。编辑文档。写下新的PDF。

其他任何听起来都是邪恶的。没有人应该以任何其他方式帮助你。

答案 1 :(得分:0)

要替换给定文件中的页面,您可以尝试执行以下方法:

  • 获取要修改/替换的页面(对象)
  • 更改它(PyPDF2 返回对象本身而不是 getter,因此,您可以更改它)。

在下面的代码中,我在我的文档中添加了一个“水印”:

tmp_name = "__tmp.pdf"

output_file = PdfFileWriter()

with open(inFile, 'rb') as f:
    # Read the pdf (create a pdf stream)
    pdf_original = PdfFileReader(f, strict=False)
    # put all buffer in a single file
    output_file.appendPagesFromReader(pdf_original)
    # create new PDF with water mark
    WaterMark._page(fixPage, tmp_name)
    # Open the created pdf
    with open(tmp_name, 'rb') as ftmp:
        # Read the temp pdf (create a pdf stream obj)
        temp_pdf = PdfFileReader(ftmp)
        for p in range(startPage, startPage+pages):
            original_page = output_file.getPage(p)
            temp_page = temp_pdf.getPage(0)
            original_page.mergePage(temp_page)

        # write result
        if output_file.getNumPages():
            # newpath = inFile[:-4] + "_numbered.pdf"
            with open(outFile, 'wb') as f:
                output_file.write(f)
    os.remove(tmp_name)

我的回答基于thisthis

The pdf that I've used The edited pdf

您可以在上方看到我文档中的第二页(已编辑页面)。