Watermark two pdfs - Each page of the first with each page of the second

风格不统一 提交于 2020-08-25 04:10:24

问题


I have two pdf files of the same length, let's say pdf1.pdf and pdf2.pdf. I'm trying to watermark each page of pdf1.pdf with pdf2.pdf (i.e., page 1 of pdf1.pdf with page 1 of pdf2.pdf, page 2 of pdf1.pdf with page 2 of pdf2.pdf ...).

However, I'm really struggling with how to loop them around (I'm new to programming).

For example, I tried this:

import PyPDF2
from PyPDF2 import PdfFileMerger
from PyPDF2 import PdfFileReader, PdfFileWriter

output = PdfFileWriter()

ipdf = PdfFileReader(open('pdf1.pdf', 'rb'))
wpdf = PdfFileReader(open('pdf2.pdf', 'rb'))
for i in xrange(wpdf.getNumPages()):
    watermark = wpdf.getPage(i)
    for i in xrange(ipdf.getNumPages()):
        page = ipdf.getPage(i)

for i in watermark:
    page.mergePage(watermark)
    output.addPage(page)

with open('newfile.pdf', 'wb') as f:
   output.write(f)

Any help would be appreciated :) :)


回答1:


You use too many loops, page counts are identical so you loop once over the pagecount, get the watermark, get the page, combine both and add them to the output:

import PyPDF2
from PyPDF2 import PdfFileMerger
from PyPDF2 import PdfFileReader, PdfFileWriter

output = PdfFileWriter()

ipdf = PdfFileReader(open('pdf1.pdf', 'rb'))
wpdf = PdfFileReader(open('pdf2.pdf', 'rb'))

# same page counts - just loop once
for i in xrange(wpdf.getNumPages()):
    watermark = wpdf.getPage(i)    # get i-th watermark
    page = ipdf.getPage(i)         # get i-th page
    page.mergePage(watermark)      # marry them and add to output
    output.addPage(page)

with open('newfile.pdf', 'wb') as f:
   output.write(f)

Done.



来源:https://stackoverflow.com/questions/50075979/watermark-two-pdfs-each-page-of-the-first-with-each-page-of-the-second

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!