PyPDF2 Pdfwriter is unable to write the pdf in memory. I checked this code earlier and it was working fine. I returned to the project after few months and it started giving me errors. i dont know what went wrong.
import io
from PyPDF2 import PdfFileWriter, PdfFileReader
def mergePDFs(InputFile1,InputFile2,OutputFile):
existing_pdf = PdfFileReader(open(InputFile1, "rb"))
output = PdfFileWriter()
new_pdf = PdfFileReader(open(InputFile2, "rb"))
output.cloneDocumentFromReader(new_pdf)
if existing_pdf.getNumPages() > output.getNumPages():
while existing_pdf.getNumPages() != output.getNumPages():
output.addBlankPage()
temp = io.BytesIO()
output.write(temp)
new_pdf = PdfFileReader(temp)
output = PdfFileWriter()
for PageNum in range(existing_pdf.getNumPages()):
page = existing_pdf.getPage(PageNum)
page.mergePage(new_pdf.getPage(PageNum))
output.addPage(page)
outputStream = open(OutputFile, "wb")
output.write(outputStream)
outputStream.close()
mergePDFs('HQ.pdf',"LSF.pdf","Mixed.pdf")
Getting following Error :
PdfReadWarning: Object 25 0 not defined. [pdf.py:1628]
Traceback (most recent call last):
File "c:/Users/Ram Vikas/Documents/PythonyRV/Tester.py", line 29, in <module>
mergePDFs('LSF.pdf',"HQ.pdf","Mixed.pdf")
File "c:/Users/Ram Vikas/Documents/PythonyRV/Tester.py", line 17, in mergePDFs
output.write(temp)
File "D:\Python3\lib\site-packages\PyPDF2\pdf.py", line 482, in write
self._sweepIndirectReferences(externalReferenceMap, self._root)
File "D:\Python3\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
self._sweepIndirectReferences(externMap, realdata)
File "D:\Python3\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
value = self._sweepIndirectReferences(externMap, value)
File "D:\Python3\lib\site-packages\PyPDF2\pdf.py", line 577, in _sweepIndirectReferences
newobj = data.pdf.getObject(data)
File "D:\Python3\lib\site-packages\PyPDF2\pdf.py", line 1631, in getObject
raise utils.PdfReadError("Could not find object.")
PyPDF2.utils.PdfReadError: Could not find object.
Help.