简体   繁体   中英

Replace a Specific page in a PDF with a page from another PDF in python 3

I am using pypdf2 to highlight text in a particular page in Pdf files.Hence,I get only a single page with higlighted text as an output.Now,I want to replace this page in the original pdf file.

I have also tried "search=" parameter from abode to highlight in the same file itself.But,It is not working.

I am new to working with PDFs.Sorry,If the question sounded a bit naive.

Get a word processor or page layout software. Convert PDF to format your software can read. Edit document. Write new PDF.

Anything else sounds nefarious. Nobody should help you do it any other way.

To replace a page in a given file you can try do the following approach:

  • Get the page (the object) that you wanna modify/replace
  • Change it (the PyPDF2 return the object itself instead a getter, so, you can change it).

In the code below, I'm adding a "water mark" in my document:

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)

My answer is based on this and this

The pdf that I've used 编辑后的pdf

Above you can see the second page (edited page) in my document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM