利用第三方库PyPDF2,下面例子中进行的是将 origin.pdf 的第17页替换为 s17.pdf 的第1页:
python
import PyPDF2
def replace_pages(original_pdf_path, replacement_pages):
with open(original_pdf_path, 'rb') as original_file:
original_pdf = PyPDF2.PdfReader(original_file)
output_pdf = PyPDF2.PdfWriter()
for page_num in range(len(original_pdf.pages)):
if page_num == 16: # Replace page 17 with first page of s17.pdf
with open(replacement_pages['s17'], 'rb') as replacement_file:
replacement_pdf = PyPDF2.PdfReader(replacement_file)
output_pdf.add_page(replacement_pdf.pages[0])
else:
output_pdf.add_page(original_pdf.pages[page_num])
with open('output.pdf', 'wb') as output_file:
output_pdf.write(output_file)
# 定义要替换的页面和其对应的替换文件
replacement_pages = {
's17': 's17.pdf',
}
replace_pages('origin.pdf', replacement_pages)
可以根据自己的实际需求进行修改。