Как добавить новую пустую страницу в конец файла PDF с помощью Python - PullRequest
0 голосов
/ 26 октября 2018

Я использую PyPDF2 lib, но она просто перезаписывает пустую страницу и не добавляется в конец файла PDF. Вот мой код.

#this is the file i'm creating
file1 = canvas.Canvas("Statements.pdf", pagesize=letter)
file1.drawString(100,400,"HELLOOOO")
file1.save()

# using this code i want to append blank page at the end but it overwrites 
#with blank page
with open("Statements.pdf", 'rb') as input:
pdf=PdfFileReader(input)
numPages=pdf.getNumPages()

outPdf=PdfFileWriter()
outPdf.cloneDocumentFromReader(pdf)
outPdf.addBlankPage()
outStream=file('Statements.pdf','wb')
outPdf.write(outStream)
outStream.close()

1 Ответ

0 голосов
/ 26 октября 2018

Похоже, что есть проблема с cloneDocumentFromReader, см .: https://github.com/mstamy2/PyPDF2/issues/219
Если вы не пытаетесь добавить пустую страницу, а просто выполняете клонирование, вы получите пустой файл.

Следующее работает для меня (Linux), на что ссылается SPYBUG96

import PyPDF2
import shutil
a = open("some_pdf_file.pdf", 'rb')
pdf=PyPDF2.PdfFileReader(a)
numPages=pdf.getNumPages()
outPdf=PyPDF2.PdfFileWriter()
outPdf.appendPagesFromReader(pdf)
#outPdf.cloneDocumentFromReader(pdf)
outPdf.addBlankPage()
outStream=open('Amended.pdf','wb')
outPdf.write(outStream)
outStream.close()
a.close()
#Copy amended file back over the original
shutil.copyfile('Amended.pdf','some_pdf_file.pdf')

Примечание: вы можете использовать shutil.move('Amended.pdf','some_pdf_file.pdf')

...