I need to combine (merge/overlay) 2 pdf files like second on first by each page. I've tried the code
import fitz
doc1 = fitz.open(background)
doc2 = fitz.open(only_text_path)
doc1.insertPDF(doc2)
but it only concatenates doc1 + doc2, doesn't overlay
Is where a way to do this using fitz
(pymupdf library)?
I found a code with PyPDF2
, but it works slow and not so stable:
from PyPDF2 import PdfFileWriter, PdfFileReader
output = PdfFileWriter()
with open(background, "rb") as f:
empty_pdf = PdfFileReader(f)
with open(only_text_path, 'rb') as f2:
text_pdf = PdfFileReader(f2)
for i in range(empty_pdf.getNumPages()):
empty_page = empty_pdf.getPage(i)
text_page = text_pdf.getPage(i)
empty_page.mergePage(text_page)
output.addPage(empty_page)
with open(merge_result_path, "wb") as out_pdf:
output.write(out_pdf)