如何在 Python 中建立 PDF 檔案
使用 IronPDF 在 Python 中建立 PDF 檔案,只需幾行程式碼,即可將 HTML 字串、HTML 檔案或 URL 轉換為 PDF 文件。 IronPDF 會自動處理渲染、格式設定及安全性功能。
快速入門:使用 Python 建立 PDF 檔案
:path=/static-assets/pdf/content-code-examples/how-to/python-create-pdf/quickstart.py
# 1. Install IronPDF: pip install ironpdf
# 2. Import the library
from ironpdf import *
# 3. Create renderer
renderer = ChromePdfRenderer()
# 4. Convert HTML to PDF
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")
# 5. Save the PDF
pdf.SaveAs("output.pdf")// 此程式碼片段無法顯示!
# 1. Install IronPDF: pip install ironpdf
# 2. Import the library
from ironpdf import *
# 3. Create renderer
renderer = ChromePdfRenderer()
# 4. Convert HTML to PDF
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")
# 5. Save the PDF
pdf.SaveAs("output.pdf")如何在 Python 中建立 PDF 檔案
- 安裝 IronPDF Python 函式庫
- 使用
RenderHtmlAsPdf方法將 HTML 字串轉換為 PDF 文件 - 使用
RenderHtmlFileAsPdf方法,將本機 HTML 檔案轉為 PDF 檔案 - 使用
RenderUrlAsPdf方法將網頁網址轉為 PDF - 啟用密碼保護,並將 PDF 儲存至指定目錄
透過 Python 自動化 PDF 生成,開發人員可在不離開應用程式的情況下,以程式化方式產生各類文件:發票、報告、合約及證書。 傳統上這需要同時處理版面配置引擎和格式規範,但 IronPDF 的"HTML 優先"方法意味著,任何 HTML/CSS 文件都能透過單一方法呼叫,轉化為像素級精準的 PDF。
本操作指南涵蓋 IronPDF for Python 中的四種主要 PDF 建立工作流程:轉換 HTML 字串、轉換本機 HTML 檔案、轉換 URL,以及在匯出前套用密碼保護。
我該使用哪個 Python 函式庫來建立 PDF 檔案?
IronPDF 是一個專為從 HTML 建立 PDF 文件而設計的 Python 函式庫。 其 API 操作簡明:傳入 HTML 標記(或檔案路徑、或 URL),即可取得一個 PdfDocument 物件,該物件可供儲存、加蓋水印、合併或加密。
此函式庫封裝了 IronPDF 經過實戰驗證的 .NET 渲染引擎,該引擎亦廣泛應用於 .NET、Java 及 Node.js 專案中,因此 HTML 轉 PDF 的輸出效果在各平台上均能保持一致。 它支援現代網頁標準,包括 CSS3、HTML5、JavaScript 執行、網頁字型及響應式佈局。
除了 PDF 生成功能外,IronPDF 還涵蓋完整的 PDF 生命週期:
- 從現有 PDF 檔案中擷取文字與資料
- 檔案格式轉換(HTML、DOCX、圖片轉 PDF)
- 合併多個 PDF 檔案
- 壓縮 PDF 檔案
- 密碼加密與數位版權管理
- 透過程式化方式填寫 PDF 表單
建立 PDF 檔案前需要哪些先決條件?
若要使用 IronPDF for Python,必須安裝以下軟體:
.NET 6.0 SDK:IronPDF for Python 基於 IronPDF .NET 函式庫運行。 請從 Microsoft .NET 6.0 官方下載頁面取得。Python 3.x:請從 Python 官方網站下載並安裝 Python。 安裝時請選擇將 Python 加入 PATH 的選項。pip:隨 Python 3.4 以上版本捆綁提供。 請在終端機中執行pip --version以確認安裝是否成功。IronPDF:使用 pip 安裝該函式庫:
pip install ironpdf
pip3 取代 pip 來安裝 Python 3 套件。 若遇到安裝錯誤,請參閱我們的疑難排解指南以解決 OSError 相關問題。)}]建立 PDF 檔案前需要哪些程式碼設定?
請在 Python 腳本開頭加入以下匯入語句:
:path=/static-assets/pdf/content-code-examples/how-to/python-create-pdf/import.py
# Import statement for IronPDF for Python
from ironpdf import *// 此程式碼片段無法顯示!
# Import statement for IronPDF for Python
from ironpdf import *在呼叫任何其他 IronPDF 函式之前,請先將有效的授權金鑰指派給 LicenseKey 的 License 屬性,以完成設定。 此功能可移除生成的 PDF 檔案中的試用版浮水印。 有關實施授權金鑰的詳細說明,請參閱授權金鑰設定指南。
:path=/static-assets/pdf/content-code-examples/how-to/python-create-pdf/license.py
# Apply your license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"// 此程式碼片段無法顯示!
# Apply your license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"如何將 HTML 字串轉換為 PDF 文件?
RenderHtmlAsPdf 方法可將 HTML 字串直接轉換為 PdfDocument 物件。 將任何有效的 HTML 標記作為方法參數傳入,IronPDF 便會透過其內建的 Chromium 引擎進行渲染,在產生 PDF 之前執行 JavaScript 並套用 CSS。
對於動態生成的內容,此方法最具彈性:先在 Python 中建構 HTML 字串(使用 Jinja2 等模板引擎或簡單的字串格式化),然後直接將其傳遞給渲染器。 舉例來說,生成發票意味著將訂單資料填入 HTML 範本,並在單一步驟中呼叫 RenderHtmlAsPdf。
:path=/static-assets/pdf/content-code-examples/how-to/python-create-pdf/html-string-to-pdf.py
from ironpdf import *
# Apply license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
# Instantiate the Chromium renderer
renderer = ChromePdfRenderer()
# Convert an HTML string to a PDF document
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1><p>This is an example HTML string.</p>")// 此程式碼片段無法顯示!
from ironpdf import *
# Apply license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
# Instantiate the Chromium renderer
renderer = ChromePdfRenderer()
# Convert an HTML string to a PDF document
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1><p>This is an example HTML string.</p>")如何儲存生成的 PDF 檔案?
將 HTML 字串轉換為 PdfDocument 實例後,請傳入目標檔案路徑並呼叫 SaveAs:
:path=/static-assets/pdf/content-code-examples/how-to/python-create-pdf/save-html-string.py
# Save the PDF to a file
pdf.SaveAs("htmlstring_to_pdf.pdf")// 此程式碼片段無法顯示!
# Save the PDF to a file
pdf.SaveAs("htmlstring_to_pdf.pdf")檔案 htmlstring_to_pdf.pdf 已寫入當前工作目錄,並完整保留 HTML 內容及其 CSS 樣式。 關於進階的 HTML 渲染技術(包括 CSS 框架、JavaScript 框架及複雜版面配置),請參閱 Python 的 HTML 轉 PDF 教學指南。
如何從本機 HTML 檔案產生 PDF 檔案?
當 HTML 內容位於本機檔案系統中的檔案時,RenderHtmlFileAsPdf 是正確的方法。 請將檔案路徑作為參數提供:
:path=/static-assets/pdf/content-code-examples/how-to/python-create-pdf/html-file-to-pdf.py
from ironpdf import *
# Apply license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
# Instantiate the renderer
renderer = ChromePdfRenderer()
# Create a PDF from a local HTML file
pdf = renderer.RenderHtmlFileAsPdf("example.html")
# Save the output PDF
pdf.SaveAs("htmlfile_to_pdf.pdf")// 此程式碼片段無法顯示!
from ironpdf import *
# Apply license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
# Instantiate the renderer
renderer = ChromePdfRenderer()
# Create a PDF from a local HTML file
pdf = renderer.RenderHtmlFileAsPdf("example.html")
# Save the output PDF
pdf.SaveAs("htmlfile_to_pdf.pdf")IronPDF 會根據 HTML 檔案的位置,解析連結的 CSS 檔案、圖片及腳本的相對路徑。 渲染器會在生成 PDF 之前載入所有相關資源,因此產出結果與瀏覽器顯示的效果完全一致。 這使其成為處理模板化文件的可靠選擇,其中 HTML 和資源皆以檔案形式儲存於磁碟中。
如何在 Python 中從網址建立 PDF 檔案?
使用 RenderUrlAsPdf 將動態網頁轉換為 PDF。 請將完整網址作為參數提供:
:path=/static-assets/pdf/content-code-examples/how-to/python-create-pdf/url-to-pdf.py
from ironpdf import *
# Apply license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
# Instantiate the renderer
renderer = ChromePdfRenderer()
# Convert a web page to PDF
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com")
# Save the output PDF
pdf.SaveAs("url.pdf")// 此程式碼片段無法顯示!
from ironpdf import *
# Apply license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
# Instantiate the renderer
renderer = ChromePdfRenderer()
# Convert a web page to PDF
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com")
# Save the output PDF
pdf.SaveAs("url.pdf")URL 渲染功能支援現代網頁技術,包括動態 JavaScript 內容、AJAX 呼叫及響應式佈局。 IronPDF 會在頁面完全載入(包括 JavaScript 執行)後才擷取 PDF,因此所有動態內容皆能精準擷取。
哪裡可以找到更多 URL 轉換範例?
有關將網頁轉換為 PDF 的其他範例,請參閱"URL 轉 PDF"程式碼範例頁面。 若涉及需要驗證的網頁,請參閱網站與系統登入指南。
如何自訂 PDF 格式設定選項?
RenderingOptions 的 ChromePdfRenderer 屬性用於控制輸出 PDF 的格式與版面配置。 常見設定包含頁面大小、頁面方向、邊距大小及Zoom比例。
:path=/static-assets/pdf/content-code-examples/how-to/python-create-pdf/rendering-options.py
from ironpdf import *
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
renderer = ChromePdfRenderer()
# Configure rendering options
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait
renderer.RenderingOptions.MarginTop = 20
renderer.RenderingOptions.MarginBottom = 20
renderer.RenderingOptions.MarginLeft = 25
renderer.RenderingOptions.MarginRight = 25
# Render with custom formatting
pdf = renderer.RenderHtmlAsPdf("<h1>Custom Formatted PDF</h1><p>Content here.</p>")
pdf.SaveAs("formatted.pdf")// 此程式碼片段無法顯示!
from ironpdf import *
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
renderer = ChromePdfRenderer()
# Configure rendering options
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait
renderer.RenderingOptions.MarginTop = 20
renderer.RenderingOptions.MarginBottom = 20
renderer.RenderingOptions.MarginLeft = 25
renderer.RenderingOptions.MarginRight = 25
# Render with custom formatting
pdf = renderer.RenderHtmlAsPdf("<h1>Custom Formatted PDF</h1><p>Content here.</p>")
pdf.SaveAs("formatted.pdf")有哪些可用的格式設定?
RenderingOptions 屬性提供紙張尺寸、頁面方向、邊距及 Zoom 比例的設定選項。 下表列出最常用的屬性:
| 屬性 | 類型 | 描述 |
|---|---|---|
PaperSize | PdfPaperSize | 標準頁面尺寸(A4、Letter、Legal)或自訂尺寸 |
PaperOrientation | PdfPaperOrientation | 直向或橫向頁面方向 |
MarginTop / MarginBottom | int (mm) | 頁面的上、下邊距(單位:毫米) |
左邊距 / 右邊距 | int (mm) | 左右頁邊距(單位:公釐) |
HtmlHeader / HtmlFooter | HtmlHeaderFooter | 支援頁碼的 HTML 頁首與頁尾 |
如需包含更多設定的完整參考資料,請參閱 PDF 生成設定程式碼範例。
RenderingOptions 上使用 HtmlHeader 和 HtmlFooter 屬性。 (頁首與頁尾範例展示了完整的語法。如何使用密碼保護 PDF 檔案?
若要為 PDF/A 設定密碼保護,請在 PdfDocument 物件的 SecuritySettings 屬性上設定 UserPassword 屬性。 亦可設定擁有者密碼,以將編輯權限與讀取權限分開限制。
請考慮保護 URL 範例中建立的 PDF 檔案:
:path=/static-assets/pdf/content-code-examples/how-to/python-create-pdf/password-protect.py
from ironpdf import *
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
renderer = ChromePdfRenderer()
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com")
# Set user password (required to open the PDF)
pdf.SecuritySettings.UserPassword = "sharable"
# Set owner password (controls permissions)
pdf.SecuritySettings.OwnerPassword = "admin123"
# Configure document permissions
pdf.SecuritySettings.AllowUserPrinting = True
pdf.SecuritySettings.AllowUserCopyPasteContent = False
# Save the password-protected PDF
pdf.SaveAs("protected.pdf")// 此程式碼片段無法顯示!
from ironpdf import *
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
renderer = ChromePdfRenderer()
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com")
# Set user password (required to open the PDF)
pdf.SecuritySettings.UserPassword = "sharable"
# Set owner password (controls permissions)
pdf.SecuritySettings.OwnerPassword = "admin123"
# Configure document permissions
pdf.SecuritySettings.AllowUserPrinting = True
pdf.SecuritySettings.AllowUserCopyPasteContent = False
# Save the password-protected PDF
pdf.SaveAs("protected.pdf")密碼保護在實際應用中是如何運作的?
在任何 PDF 檢視器中開啟 protected.pdf 時,系統會在顯示文件內容前要求輸入使用者密碼。 擁有者密碼可提供管理權限,用以修改安全性設定。 設定 AllowUserCopyPasteContent = False 可防止讀者從 PDF 中複製文字,同時仍允許列印。
若需進一步控制文件權限,請參閱安全性與元資料設定範例,以及 PDF 加密與解密指南。
完整的原始碼是什麼?
以下綜合範例展示如何在單一 Python 腳本中實現這四種 PDF 建立工作流程:
:path=/static-assets/pdf/content-code-examples/how-to/python-create-pdf/complete-example.py
from ironpdf import *
# Apply your license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
# --- HTML string to PDF ---
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1><p>This is an example HTML string.</p>")
pdf.SaveAs("htmlstring_to_pdf.pdf")
# --- Local HTML file to PDF ---
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlFileAsPdf("example.html")
pdf.SaveAs("htmlfile_to_pdf.pdf")
# --- URL to PDF ---
renderer = ChromePdfRenderer()
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com")
pdf.SaveAs("url.pdf")
# --- Password-protected PDF ---
pdf.SecuritySettings.UserPassword = "sharable"
pdf.SecuritySettings.OwnerPassword = "admin123"
pdf.SecuritySettings.AllowUserPrinting = True
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SaveAs("protected.pdf")// 此程式碼片段無法顯示!
from ironpdf import *
# Apply your license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
# --- HTML string to PDF ---
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1><p>This is an example HTML string.</p>")
pdf.SaveAs("htmlstring_to_pdf.pdf")
# --- Local HTML file to PDF ---
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlFileAsPdf("example.html")
pdf.SaveAs("htmlfile_to_pdf.pdf")
# --- URL to PDF ---
renderer = ChromePdfRenderer()
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com")
pdf.SaveAs("url.pdf")
# --- Password-protected PDF ---
pdf.SecuritySettings.UserPassword = "sharable"
pdf.SecuritySettings.OwnerPassword = "admin123"
pdf.SecuritySettings.AllowUserPrinting = True
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SaveAs("protected.pdf")IronPDF 能精準呈現所有圖像與文字,同時完整保留格式。 互動元件(例如按鈕)在生成的 PDF 中仍可正常運作,文字方塊亦保留其可編輯性。
在 Python 中建立 PDF 的下一步該怎麼做?
本指南介紹了 IronPDF for Python 中三種主要的 PDF 建立方法——HTML 字串、本地 HTML 檔案及 URL——以及用於保護輸出檔案安全的密碼保護功能。 每個方法都會產生一個 PdfDocument 物件,該物件可在儲存前進行進一步處理:加蓋、合併、分割或加密。
準備好擴展這些工作流程了嗎? 以下資源展示了實用的後續步驟:
- HTML 轉 PDF Python 教學 — 運用 CSS 框架與 JavaScript 進行進階渲染
- 在 Python 中合併 PDF — 將多個文件合併為一個檔案
- 使用 Python 壓縮 PDF — 縮小檔案大小以利儲存與電子郵件傳送
- 使用 Python 填寫 PDF 表單 — 填入現有 PDF 表單欄位
IronPDF 需具備有效授權方可於生產環境中使用。 授權條款自 $999 開始。 Start a free 30-day trial to evaluate the library without restrictions, or view licensing options for the full product suite.
常見問題
如何安裝 IronPDF for Python?
在 pip install ironpdf 於您的終端機中執行。您還需安裝 Python 3.x 及 .NET 6.0 SDK,因為 IronPDF for Python 是基於 IronPDF .NET 引擎運作的。
在 Python 中將 HTML 轉換為 PDF 的最簡單方法是什麼?
建立一個 ChromePdfRenderer 實例,然後呼叫 renderer.RenderHtmlAsPdf('<h1>Hello</h1>')。此方法接受任何有效的 HTML 字串,並返回一個 PdfDocument 物件,您可以將其儲存為 pdf.SaveAs('output.pdf').
我可以從本地的 HTML 檔案生成 PDF 檔嗎?
是的。請使用 renderer.RenderHtmlFileAsPdf('path/to/file.html')。IronPDF 會在渲染前,根據 HTML 檔案的位置解析相關的 CSS、圖片及腳本。
如何將即時網頁網址轉換為 PDF?
呼叫 renderer.RenderUrlAsPdf('https://example.com')。IronPDF 會在擷取 PDF 之前,等待整頁載入完畢,包括 JavaScript 的執行。
如何為生成的 PDF 設定密碼保護?
設定 pdf.SecuritySettings.UserPassword 設定為需輸入密碼才能開啟檔案,並 pdf.SecuritySettings.OwnerPassword 以限制編輯權限。隨後呼叫 pdf.SaveAs 來寫入受保護的檔案。
我可以控制生成的 PDF 檔案的頁面大小和邊距嗎?
是的。請設定 renderer.RenderingOptions.PaperSize (例如 PdfPaperSize.A4) 並設定 MarginTop, MarginBottom, MarginLeft,並 MarginRight 以公釐為單位,然後才呼叫渲染方法。
IronPDF 是否支援在 HTML 轉 PDF 過程中執行 JavaScript?
是的。IronPDF 採用基於 Chromium 的渲染引擎,該引擎會在生成 PDF 之前執行 JavaScript、處理 AJAX 呼叫並套用 CSS,因此能精確擷取動態內容。
建立 PDF 檔案後,我可以合併或壓縮它們嗎?
是的。IronPDF 提供了獨立的方法,可用於將多個 PdfDocument 物件合併為單一檔案,以及壓縮現有 PDF 以減小檔案大小。這兩項操作皆可對 PdfDocument 任何渲染方法所返回的物件上。







