編輯 PDF 檔案

from ironpdf import *

# Instantiate Renderer
renderer = ChromePdfRenderer()

# Join Multiple Existing PDFs into a single document
pdfs = List[PdfDocument]()
pdfs.Add(PdfDocument.FromFile("A.pdf"))
pdfs.Add(PdfDocument.FromFile("B.pdf"))
pdfs.Add(PdfDocument.FromFile("C.pdf"))
pdf = PdfDocument.Merge(pdfs)
pdf.SaveAs("merged.pdf")
 
# Add a cover page
pdf.PrependPdf(renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>"))
 
# Remove the last page from the PDF and save again
pdf.RemovePage(pdf.PageCount - 1)
pdf.SaveAs("merged.pdf")
 
# Copy pages 5-7 and save them as a new document.
pdf.CopyPages(ToPageList([4, 6])).SaveAs("excerpt.pdf")
 
for eachPdf in pdfs:
    eachPdf.Dispose()
pip install ironpdf
編輯 PDF 檔案

編輯 PDF 檔案

IronPDF for Python 提供了一組簡潔的方法,用於合併、重構和提取PDF文件的頁面——僅需幾行程式碼即可合併多個文件、添加封面頁、移除某些頁面、及複製頁面子集。

開始使用

將現有的PDF載入一個類型化的List[PdfDocument]集合,並傳遞給PdfDocument.Merge來合併它們。 從那裡開始,使用PrependPdf、RemovePage以及CopyPages進一步塑造文件,然後再保存。

理解程式碼

  • List[PdfDocument]():一個類型化的.NET風格清單,用於在合併之前收集多個PdfDocument對象。 呼叫.Add()來追加每個文件。
  • PdfDocument.FromFile(path):打開一個現有的PDF文件,並將其作為PdfDocument對象返回。
  • PdfDocument.Merge(pdfs):將清單中的所有文件合併為一個PdfDocument,並保留頁面順序。
  • SaveAs(path):將文件的當前狀態寫入磁碟。
  • PrependPdf(pdf):在當前文件的最開頭插入另一個PdfDocument,在此用於添加渲染的HTML封面頁作為第一頁。
  • RemovePage(index):在指定的零起始索引處移除單個頁面。 pdf.PageCount - 1目標是最後一頁。
  • CopyPages(ToPageList([4, 6])):按零基索引提取特定頁面,並將它們作為新的PdfDocument返回。 ToPageList將Python的索引清單轉換為所需的頁面清單格式。
  • eachPdf.Dispose():在合併完成後釋放每個加載的PdfDocument所持有的底層資源。

零基的頁面編號

IronPDF中的所有頁面操作都使用零基索引。 文檔的第5頁在索引4,第7頁在索引6,依此類推。

學習如何使用IronPDF for Python 來合併和編輯PDF文件!

準備好開始了嗎?

版本:2026.11剛剛發布