问题
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