[英]append page to existing pdf file using python (and matplotlib?)
[英]insert new page between existing pages in pdf using matplotlib in python
是否可以將新頁面插入多頁pdf文件的任意位置?
在此虛擬示例中,我將創建一些pdf頁面:
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
with PdfPages('dummy.pdf') as pdf:
for i in range(5):
plt.plot(1,1)
pdf.savefig()
plt.close()
現在,我想繪制其他圖形並將新圖形另存為pdf第1頁。
您可以使用模塊PyPDF2 。 它使您可以合並或處理pdf文件。 我嘗試了一個簡單的示例,僅用一頁創建另一個pdf文件,並將此頁添加到第一個文件的中間。 然后,將所有內容寫入新的輸出文件:
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
from PyPDF2 import PdfFileWriter, PdfFileReader
with PdfPages('dummy.pdf') as pdf:
for i in range(5):
plt.plot(1,1)
pdf.savefig()
plt.close()
#Create another pdf file
with PdfPages('dummy2.pdf') as pdf:
plt.plot(range(10))
pdf.savefig()
plt.close()
infile = PdfFileReader('dummy.pdf', 'rb')
infile2 = PdfFileReader('dummy2.pdf', 'rb')
output = PdfFileWriter()
p2 = infile2.getPage(0)
for i in xrange(infile.getNumPages()):
p = infile.getPage(i)
output.addPage(p)
if i == 3:
output.addPage(p2)
with open('newfile.pdf', 'wb') as f:
output.write(f)
也許有一種更聰明的方法可以做到這一點,但是我希望這可以幫助我們開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.