跳過到頁腳內容
使用 IRONPDF FOR PYTHON

Python PdfWriter(代碼示例教程)

IronPDF是一個純 Python PDF 文件物件庫,適用於希望在應用程式中編寫 PDF 文件或操作 PDF 文件的 Python 開發人員。 IronPDF 以其簡潔性和多功能性脫穎而出,使其成為需要自動建立 PDF 或將 PDF 生成整合到軟體系統中的任務的理想選擇。

本指南將探討如何使用純 Python PDF 庫 IronPDF 來建立 PDF 文件或 PDF 頁面屬性以及讀取 PDF 文件。 它將包含範例和實用程式碼片段,讓您親身了解如何在 Python 專案中使用 IronPDF for Python 的 PdfWriter 來寫入 PDF 檔案和建立新的 PDF 頁面。

設定 IronPDF

安裝

要開始使用 IronPDF,您需要通過 Python Package Index 安裝它。 在終端機中執行以下命令:

pip install ironpdf

編寫和操作 PDF 文件

建立新的PDF

IronPDF 簡化了建立新 PDF 檔案和處理現有 PDF 檔案的過程。 它提供了一個簡單的介面來產生文檔,無論是簡單的單頁 PDF 文檔,還是包含使用者密碼等各種元素的更複雜的文檔。 此功能對於產生報表、建立發票等任務至關重要。

from ironpdf import ChromePdfRenderer, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Basic HTML content for the PDF
html = """
<html>
   <head>
      <title>IronPDF for Python!</title>
      <link rel='stylesheet' href='assets/style.css'>
   </head>
   <body>
      <h1>It's IronPDF World!!</h1>
      <a href="https://ironpdf.com/python/"><img src='assets/logo.png' /></a>
   </body>
</html>
"""

# Create a PDF renderer
renderer = ChromePdfRenderer()
# Render the HTML content as a PDF
pdf = renderer.RenderHtmlAsPdf(html)
# Save the rendered PDF to a file
pdf.SaveAs("New PDF File.pdf")
from ironpdf import ChromePdfRenderer, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Basic HTML content for the PDF
html = """
<html>
   <head>
      <title>IronPDF for Python!</title>
      <link rel='stylesheet' href='assets/style.css'>
   </head>
   <body>
      <h1>It's IronPDF World!!</h1>
      <a href="https://ironpdf.com/python/"><img src='assets/logo.png' /></a>
   </body>
</html>
"""

# Create a PDF renderer
renderer = ChromePdfRenderer()
# Render the HTML content as a PDF
pdf = renderer.RenderHtmlAsPdf(html)
# Save the rendered PDF to a file
pdf.SaveAs("New PDF File.pdf")
PYTHON

Python PDFWriter(程式碼範例教學),圖 1:輸出文件 輸出檔案

合併 PDF 文件

IronPDF 簡化了將多個 PDF 文件合併為一個文件的任務。 此功能有利於匯總各種報告、組裝掃描文件或整理屬於同一類別的資訊。 例如,當您從多個來源建立綜合報告時,或者當您有一系列需要作為單一文件呈現的文件時,您可能需要合併 PDF 文件。

from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load existing PDF documents
pdfOne = PdfDocument("Report First.pdf")
pdfTwo = PdfDocument("Report Second.pdf")
# Merge the PDFs into a single document
merged = PdfDocument.Merge(pdfOne, pdfTwo)
# Save the merged PDF
merged.SaveAs("Merged.pdf")
from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load existing PDF documents
pdfOne = PdfDocument("Report First.pdf")
pdfTwo = PdfDocument("Report Second.pdf")
# Merge the PDFs into a single document
merged = PdfDocument.Merge(pdfOne, pdfTwo)
# Save the merged PDF
merged.SaveAs("Merged.pdf")
PYTHON

將現有 PDF 文件合併到新的 PDF 文件中的功能在資料科學等領域也很有用,因為合併後的 PDF 文件可以作為訓練 AI 模組的資料集。 IronPDF 可以輕鬆完成這項任務,保持原始文件每一頁的完整性和格式,從而產生無縫且連貫的輸出 PDF 文件。

Python PDFWriter(程式碼範例教學),圖 2:合併後的 PDF 輸出 合併 PDF 輸出

拆分單一 PDF

反之,IronPDF 也非常擅長將現有的 PDF 檔案分割成多個新檔案。 當您需要從大型 PDF 文件中提取特定部分,或將文件分成更小、更易於管理的部分時,此功能非常有用。

from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load the PDF document
pdf = PdfDocument("Report.pdf")
# Extract the first page
page1doc = pdf.CopyPage(0)
# Save the extracted page as a new PDF
page1doc.SaveAs("Split1.pdf")
from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load the PDF document
pdf = PdfDocument("Report.pdf")
# Extract the first page
page1doc = pdf.CopyPage(0)
# Save the extracted page as a new PDF
page1doc.SaveAs("Split1.pdf")
PYTHON

例如,您可能希望從大型報告中分離出某些 PDF 頁面,或從一本書的不同章節建立單獨的文件。 IronPDF 讓您選擇要轉換為新 PDF 檔案的所需多頁,確保您可以根據需要操作和管理 PDF 內容。

Python PDFWriter(程式碼範例教學),圖 3:拆分 PDF 輸出 拆分 PDF 輸出

實施安全功能

處理敏感或機密資訊時,保護PDF文件的安全至關重要。 IronPDF 透過提供強大的安全功能(包括使用者密碼保護和加密)來滿足這項需求。 這樣可以確保您的 PDF 檔案安全無虞,只有授權使用者才能存取。

from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load the PDF document
pdf = PdfDocument("Report.pdf")
# Adjust security settings to make the PDF read-only and set permissions
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key")
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights
# Set the document encryption passwords
pdf.SecuritySettings.OwnerPassword = "top-secret"  # password to edit the PDF
pdf.SecuritySettings.UserPassword = "sharable"  # password to open the PDF
# Save the secured PDF
pdf.SaveAs("secured.pdf")
from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load the PDF document
pdf = PdfDocument("Report.pdf")
# Adjust security settings to make the PDF read-only and set permissions
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key")
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights
# Set the document encryption passwords
pdf.SecuritySettings.OwnerPassword = "top-secret"  # password to edit the PDF
pdf.SecuritySettings.UserPassword = "sharable"  # password to open the PDF
# Save the secured PDF
pdf.SaveAs("secured.pdf")
PYTHON

透過設定使用者密碼,您可以控制誰可以檢視或編輯您的 PDF 文件。 加密選項增加了一層額外的安全保障,保護您的資料免受未經授權的訪問,使 IronPDF 成為管理 PDF 格式敏感資訊的可靠選擇。

從PDF中提取文本

IronPDF的另一個關鍵功能是能夠從PDF文件中提取文字。 此功能對於資料檢索、內容分析,甚至將現有 PDF 中的文字內容重新用於新文件特別有用。

from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load the PDF document
pdf = PdfDocument("Report.pdf")
# Extract all text from the PDF document
allText = pdf.ExtractAllText()
# Extract text from a specific page in the document
specificPage = pdf.ExtractTextFromPage(3)
from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load the PDF document
pdf = PdfDocument("Report.pdf")
# Extract all text from the PDF document
allText = pdf.ExtractAllText()
# Extract text from a specific page in the document
specificPage = pdf.ExtractTextFromPage(3)
PYTHON

無論您是提取數據進行分析、在大文檔中搜索特定信息,還是將內容從 PDF 轉換為文本文件進行進一步處理,IronPDF 都能讓這一切變得簡單高效。 該庫確保提取的文字保持其原始格式和結構,使其能夠立即用於您的特定需求。

管理文件資訊

高效率管理PDF文件不僅僅關乎其內容。 IronPDF 可以有效管理文件元資料和屬性,例如作者姓名、文件標題、建立日期等。 此功能對於組織和編目 PDF 文件至關重要,尤其是在文件來源和元資料很重要的環境中。

from ironpdf import PdfDocument, License, Logger
from datetime import datetime

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load an existing PDF or create a new one
pdf = PdfDocument("Report.pdf")
# Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = datetime.now()
# Save the PDF with updated metadata
pdf.SaveAs("MetaData Updated.pdf")
from ironpdf import PdfDocument, License, Logger
from datetime import datetime

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load an existing PDF or create a new one
pdf = PdfDocument("Report.pdf")
# Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = datetime.now()
# Save the PDF with updated metadata
pdf.SaveAs("MetaData Updated.pdf")
PYTHON

例如,在學術或企業環境中,能夠追蹤文件的建立日期和作者對於記錄保存和文件檢索至關重要。 IronPDF 讓管理這些資訊變得輕鬆,它提供了一種簡化的方式來處理和更新 Python 應用程式中的文件資訊。

結論

Python PDFWriter(程式碼範例教學),圖 4:許可證 License

本教學介紹了在 Python 中使用 IronPDF 進行 PDF 處理的基礎知識。 從建立新的 PDF 檔案到合併現有文件,再到新增安全功能,IronPDF 對於任何 Python 開發人員來說都是一款功能全面的工具。

IronPDF for Python 也提供以下功能:

IronPDF for Python 提供免費試用版,讓使用者可以探索其功能。 試用期結束後,如需繼續使用,許可證起價為$799 。 這種定價方式讓開發人員能夠在他們的專案中充分利用 IronPDF 的全部功能。

常見問題解答

如何在 Python 中建立 PDF 檔案?

您可以使用 IronPDF 的 CreatePdf 方法來產生新的 PDF 檔案。此方法可讓您使用 Python 從頭開始建立自訂 PDF 文件。

安裝 IronPDF for Python 的步驟是什麼?

要安裝 IronPDF for Python,您可以使用 Python 套件索引,執行下列指令:pip install ironpdf

如何使用 Python 將多個 PDF 合併為一個?

IronPDF 提供合併多個 PDF 檔案的功能。您可以使用 MergePdfFiles 方法將多個 PDF 合併為單一文件。

我可以用 IronPDF 將 PDF 分成不同的頁面嗎?

是的,IronPDF 提供 SplitPdf 功能,可讓您將 PDF 分成單獨的頁面或部分,並為每個部分建立獨立的檔案。

IronPDF 支持 PDF 的哪些安全功能?

IronPDF 支援多種安全功能,包括密碼保護和加密,以確保您的 PDF 檔案安全,且只有授權使用者才能存取。

如何用 Python 從 PDF 文件中提取文字?

使用 IronPdf,您可以使用 ExtractText 方法輕鬆地從 PDF 文件中提取文字,這對資料檢索和分析非常有用。

IronPDF 提供了哪些主要的 PDF 操作功能?

IronPdf 可讓您建立、合併和分割 PDF,套用安全措施、擷取文字,以及管理作者姓名和建立日期等文件元資料。

IronPDF 是否有免費試用版,如何使用?

是的,IronPdf 提供免費試用。您可以在試用期間探索其功能,試用結束後可購買授權繼續使用。

IronPDF 在 Python 項目中有哪些實際使用案例?

IronPDF 是在各種 Python 專案中產生報表、建立發票、保護文件以及管理 PDF 元資料的理想工具。

如何使用 IronPDF 管理 PDF 元資料?

IronPDF 可讓您管理 PDF 元資料,包括作者姓名、文件標題和建立日期,這對文件組織和編目至關重要。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。