'Python : Add watermark/background in all pages PDF

I just want to add/merge background in all pages in PDf but getpage(i) in inputfile giving me error. Only getPage(0) is running without error but creating duplicate copy of page first throughout the document keeping the original number of pages.

here is my code

from typing import BinaryIO
import os
import PyPDF2
from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger
from tkinter.filedialog import askopenfilename
from fpdf import FPDF

input_file = askopenfilename()
pdf = PdfFileReader(input_file)
watermark = PyPDF2.PdfFileReader(open('F:\abc\abc\PDF 
Templates\Report First - Potrait.pdf', 'rb'))
output = PdfFileWriter()


num_numbers = pdf.numPages
for i in range(pdf.getNumPages()):
watermarks = watermark.getPage(0)
page = pdf.getPage(i)
page.mergePage(watermarks)
output.addPage(page)

with open(input_file.rsplit(".", 1)[0] + '_FP.pdf', "wb") as merged_file:
output.write(merged_file)

getting Error::

Traceback (most recent call last): File "C:\Users\Gaurav\Desktop\PFD python\abc\PFD python\test2.py", line 23, in page.mergePage(watermarks) File "C:\Users\Gaurav\AppData\Local\Programs\Python\Python310\lib\site-packages\PyPDF2\pdf.py", line 2417, in mergePage self._mergePage(page2) File "C:\Users\Gaurav\AppData\Local\Programs\Python\Python310\lib\site-packages\PyPDF2\pdf.py", line 2426, in _mergePage originalResources = self[PG.RESOURCES].getObject() File "C:\Users\Gaurav\AppData\Local\Programs\Python\Python310\lib\site-packages\PyPDF2\generic.py", line 539, in getitem return dict.getitem(self, key).getObject() KeyError: '/Resources'



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source