我使用的是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()
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')