3

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 :) :)

Fabian
  • 51
  • 1
  • 10

1 Answers1

4

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.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Thank you so much!!! You're right, as they have the same number of pages I only need to get the number of pages once! :D – Fabian Apr 28 '18 at 11:34
  • 1
    @Fabian please add the python2.7 tag to your question (edit it) in addition to python general tag. If your problems is solved, consider [upvoting/accepting](https://meta.stackexchange.com/a/5235/377931) adding the tag and prettifying your questions helps the next Florian some weeks down into future to find your question to his identical problem easier ;) - happy coding – Patrick Artner Apr 28 '18 at 11:38
  • Thank you for the suggestions! I would love to add the tag, however, I'm not able to ("Creating the new tag 'python2.7' requires at least 1500 reputation. Try something from the existing tags list instead.") Similarly, upvoting is not possible ("Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score."), but accepting it did, at least, work :) :) – Fabian Apr 28 '18 at 13:10