HTML 轉 PDF:Python
本指南為 Python 開發人員提供逐步說明,指導他們如何使用IronPDF庫將 HTML 內容轉換為高品質的 PDF 格式(便攜式文件格式)文件。
IronPDF是一個功能全面的 PDF 轉換器和處理庫,支援多種程式語言,包括.NET 、 Java和Python程式語言。 本教學專門介紹如何在 Python 腳本中使用IronPDF來轉換 HTML 內容,無論是檔案形式還是標記形式。
此外,我們還提供了關於如何在.NET應用程式中將 HTML 轉換為 PDF 的單獨教學課程。
概述
如何在 Python 中將 HTML 轉換為 PDF

- 安裝 HTML 轉 PDF 所需的 Python 函式庫
- 使用`RenderHtmlAsPdf`方法將 HTML 字串轉換為 PDF 文檔
- 使用 Python 直接從網站 URL 產生 PDF 文件
- 使用`RenderHtmlFileAsPdf`方法將 HTML 檔案轉換為 PDF 文件
- 將生成的 PDF 文件另存為新文件
入門
1. 安裝適用於 Python 的IronPDF PDF 庫
要安裝 Python 版IronPDF庫,可以使用流行的套件管理器 pip。只需執行以下命令:
pip install ironpdf
==2023.x.x。 例如,您可以執行以下命令:pip install ironpdf==2023.x.xpip install ironpdf==2023.x.x操作指南和程式碼範例
2. 將 HTML 轉換為 PDF
在接下來的部分中,我們將深入探討IronPDF在將 HTML 轉換為 PDF 方面的強大渲染功能。
PDF 文件渲染的主要元件是 ChromePdfRenderer 類別。 此外,PdfDocument 類別提供了一系列操作功能。 IronPDF提供可靠的方法將 HTML 內容轉換為 PDF 文檔,滿足 three key scenarios:
- 將 HTML 字串/標記轉換為 PDF
- 將 HTML 檔案/壓縮檔案轉換為 PDF
- 將 URL 轉換為 PDF
本節將簡要概述每個用例,並提供補充資源以了解更多詳細資訊。
2.1 導入IronPDF包
若要匯入IronPDF,請在將要使用IronPDF 的來源檔案的開頭新增下列匯入語句:
# Import statement for IronPDF for Python
from ironpdf import *# Import statement for IronPDF for Python
from ironpdf import *2.2 設定許可證密鑰(可選)
IronPDF for Python 可以免費使用,但免費用戶會在 PDF 檔案中加入平鋪背景浮水印。
請造訪許可證頁面以取得您的許可證密鑰,即可享受無浮水印 PDF。
要使用IronPDF產生無浮水印 PDF,需要向該庫提供有效的許可證密鑰。 以下程式碼片段示範如何使用許可證金鑰配置庫:
# Apply your license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"# Apply your license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"請確保在產生 PDF 檔案或修改其內容之前已設定許可證金鑰。 建議在任何其他程式碼行之前呼叫 LicenseKey 方法。 您可以從我們的授權頁面購買許可證金鑰,或聯絡我們以取得免費試用許可證金鑰。
2.3 設定日誌檔案位置(可選)
IronPDF可以將日誌訊息產生到與 Python 腳本位於相同目錄下的名為 Default.log 的文字檔案中。
如果要自訂日誌檔案名稱和位置,可以使用下列程式碼片段設定 LogFilePath 屬性:
# Set a log path
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All# Set a log path
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All在執行任何 PDF 轉換和處理方法之前,應呼叫 Logger.LogFilePath。
2.4 從 HTML 字串建立 PDF
RenderHtmlAsPdf 方法將 HTML 字串轉換為 PDF 格式文件。
以下程式碼片段示範如何從包含單一標題元素的 HTML 字串產生 PDF 檔案:
from ironpdf import *
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from a HTML string using Python
pdf = renderer.RenderHtmlAsPdf("<h1>Hello from IronPDF!</h1>")
# Export to a file or Stream
pdf.SaveAs("output.pdf")from ironpdf import *
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from a HTML string using Python
pdf = renderer.RenderHtmlAsPdf("<h1>Hello from IronPDF!</h1>")
# Export to a file or Stream
pdf.SaveAs("output.pdf")RenderHtmlAsPdf方法以與現代瀏覽器相同的方式處理 HTML、CSS 和JavaScript ,從而確保內容的準確渲染。此功能使軟體工程師能夠建立與網頁版 PDF 高度相似的 PDF 檔案。
此外,RenderHtmlAsPdf 方法可以處理位於本機或網頁資料夾中的外部資源,例如映像、樣式表和腳本。 以下範例示範如何從 HTML 建立 PDF 文檔,該文檔引用了儲存在 assets 資料夾中的 CSS 文件和圖像:
from ironpdf import *
html = """
<html>
<head>
<title>Hello world!</title>
<link rel='stylesheet' href='assets/style.css'>
</head>
<body>
<h1>Hello from IronPDF!</h1>
<a href="https://ironpdf.com/python/"><img src='assets/logo.png' /></a>
</body>
</html>
"""
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("output.pdf")from ironpdf import *
html = """
<html>
<head>
<title>Hello world!</title>
<link rel='stylesheet' href='assets/style.css'>
</head>
<body>
<h1>Hello from IronPDF!</h1>
<a href="https://ironpdf.com/python/"><img src='assets/logo.png' /></a>
</body>
</html>
"""
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("output.pdf")此外,開發者也可以選擇向RenderHtmlAsPdf方法提供第二個參數,從而指定引用 Web 資源的基本路徑。該路徑可以指向檔案系統上的本機目錄,甚至可以指向 URL 路徑。
為了更了解如何使用 RenderHtmlAsPdf 方法,您可以參考此程式碼範例或查閱 API 參考頁面以取得更多詳細資訊。
2.5 從 URL 建立 PDF
要將網站 URL 轉換為 PDF 文檔,開發人員可以使用IronPDF提供的 RenderUrlAsPdf 方法。
以下範例示範如何將維基百科文章渲染成 PDF 內容。
from ironpdf import *
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from a URL or local file path
pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF")
# Export to a file or Stream
pdf.SaveAs("url.pdf")from ironpdf import *
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from a URL or local file path
pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF")
# Export to a file or Stream
pdf.SaveAs("url.pdf")如需了解更多信息,您可以參考程式碼範例,了解如何將網頁轉換為 PDF。
2.6 從 HTML 檔案建立 PDF
IronPDF能夠將 HTML 檔案轉換為 PDF 並將其儲存在本機檔案系統中。 它直接將 HTML 內容渲染成等效的 PDF 格式。
For a real-world demonstration of this functionality, the following code example showcases the conversion of an invoice HTML file. You can access the HTML markup of the invoice.
為了方便起見,我們提供了以下HTML標記:
<html>
<head>
<meta charset="utf-8">
<title>Invoice</title>
<link rel="stylesheet" href="style.css">
<link rel="license" href="https://www.opensource.org/licenses/mit-license/">
<script src="script.js"></script>
</head>
<body>
<header>
<h1>Invoice</h1>
<address contenteditable>
<p>Jonathan Neal</p>
<p>101 E. Chapman Ave<br>Orange, CA 92866</p>
<p>(800) 555-1234</p>
</address>
<span><img alt="" src="http://www.jonathantneal.com/examples/invoice/logo.png"><input type="file" accept="image/*"></span>
</header>
<article>
<h1>Recipient</h1>
<address contenteditable>
<p>Some Company<br>c/o Some Guy</p>
</address>
<table class="meta">
<tr>
<th><span contenteditable>Invoice #</span></th>
<td><span contenteditable>101138</span></td>
</tr>
<tr>
<th><span contenteditable>Date</span></th>
<td><span contenteditable>January 1, 2012</span></td>
</tr>
<tr>
<th><span contenteditable>Amount Due</span></th>
<td><span id="prefix" contenteditable>$</span><span>600.00</span></td>
</tr>
</table>
<table class="inventory">
<thead>
<tr>
<th><span contenteditable>Item</span></th>
<th><span contenteditable>Description</span></th>
<th><span contenteditable>Rate</span></th>
<th><span contenteditable>Quantity</span></th>
<th><span contenteditable>Price</span></th>
</tr>
</thead>
<tbody>
<tr>
<td><a class="cut">-</a><span contenteditable>Front End Consultation</span></td>
<td><span contenteditable>Experience Review</span></td>
<td><span data-prefix>$</span><span contenteditable>150.00</span></td>
<td><span contenteditable>4</span></td>
<td><span data-prefix>$</span><span>600.00</span></td>
</tr>
</tbody>
</table>
<a class="add">+</a>
<table class="balance">
<tr>
<th><span contenteditable>Total</span></th>
<td><span data-prefix>$</span><span>600.00</span></td>
</tr>
<tr>
<th><span contenteditable>Amount Paid</span></th>
<td><span data-prefix>$</span><span contenteditable>0.00</span></td>
</tr>
<tr>
<th><span contenteditable>Balance Due</span></th>
<td><span data-prefix>$</span><span>600.00</span></td>
</tr>
</table>
</article>
<aside>
<h1><span contenteditable>Additional Notes</span></h1>
<div contenteditable>
<p>A finance charge of 1.5% will be made on unpaid balances after 30 days.</p>
</div>
</aside>
</body>
</html><html>
<head>
<meta charset="utf-8">
<title>Invoice</title>
<link rel="stylesheet" href="style.css">
<link rel="license" href="https://www.opensource.org/licenses/mit-license/">
<script src="script.js"></script>
</head>
<body>
<header>
<h1>Invoice</h1>
<address contenteditable>
<p>Jonathan Neal</p>
<p>101 E. Chapman Ave<br>Orange, CA 92866</p>
<p>(800) 555-1234</p>
</address>
<span><img alt="" src="http://www.jonathantneal.com/examples/invoice/logo.png"><input type="file" accept="image/*"></span>
</header>
<article>
<h1>Recipient</h1>
<address contenteditable>
<p>Some Company<br>c/o Some Guy</p>
</address>
<table class="meta">
<tr>
<th><span contenteditable>Invoice #</span></th>
<td><span contenteditable>101138</span></td>
</tr>
<tr>
<th><span contenteditable>Date</span></th>
<td><span contenteditable>January 1, 2012</span></td>
</tr>
<tr>
<th><span contenteditable>Amount Due</span></th>
<td><span id="prefix" contenteditable>$</span><span>600.00</span></td>
</tr>
</table>
<table class="inventory">
<thead>
<tr>
<th><span contenteditable>Item</span></th>
<th><span contenteditable>Description</span></th>
<th><span contenteditable>Rate</span></th>
<th><span contenteditable>Quantity</span></th>
<th><span contenteditable>Price</span></th>
</tr>
</thead>
<tbody>
<tr>
<td><a class="cut">-</a><span contenteditable>Front End Consultation</span></td>
<td><span contenteditable>Experience Review</span></td>
<td><span data-prefix>$</span><span contenteditable>150.00</span></td>
<td><span contenteditable>4</span></td>
<td><span data-prefix>$</span><span>600.00</span></td>
</tr>
</tbody>
</table>
<a class="add">+</a>
<table class="balance">
<tr>
<th><span contenteditable>Total</span></th>
<td><span data-prefix>$</span><span>600.00</span></td>
</tr>
<tr>
<th><span contenteditable>Amount Paid</span></th>
<td><span data-prefix>$</span><span contenteditable>0.00</span></td>
</tr>
<tr>
<th><span contenteditable>Balance Due</span></th>
<td><span data-prefix>$</span><span>600.00</span></td>
</tr>
</table>
</article>
<aside>
<h1><span contenteditable>Additional Notes</span></h1>
<div contenteditable>
<p>A finance charge of 1.5% will be made on unpaid balances after 30 days.</p>
</div>
</aside>
</body>
</html>假設我們有一個本地 HTML 檔案及其關聯的 CSS 和JavaScript檔案保存在名為"invoices"的資料夾中,我們可以使用IronPDF透過以下 Python 程式碼將範例 HTML 檔案轉換為 PDF:
from ironpdf import *
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from an existing HTML file using Python
pdf = renderer.RenderHtmlFileAsPdf("invoices/TestInvoice1.html")
# Export to a file or Stream
pdf.SaveAs("htmlfile_to_pdf.pdf")from ironpdf import *
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from an existing HTML file using Python
pdf = renderer.RenderHtmlFileAsPdf("invoices/TestInvoice1.html")
# Export to a file or Stream
pdf.SaveAs("htmlfile_to_pdf.pdf")與將 HTML 字串轉換為 PDF 類似, IronPDF會自動解析範例 HTML 文件中的相對 URL,確保任何引用的樣式表和腳本都正確套用於產生的 PDF 文件。 這樣可以確保網頁的視覺效果準確地反映在 PDF 檔案中。
3. 延伸閱讀
透過深入研究我們的程式碼範例部分,探索 IronPDF 的 HTML 轉 PDF 渲染的強大功能。
- 閱讀此程式碼範例,以了解如何在轉換過程中自訂 PDF 文件的外觀。
- 學習如何產生具有個人化頁首和頁尾的PDF 文件,調整頁邊距大小和頁面尺寸,添加浮水印等等。
- 此外,探索提取文字、優化文件大小以及以程式設計方式列印 PDF 的技術。
下載軟體產品。
常見問題解答
我如何使用Python將HTML轉換為PDF?
您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字串轉換為 PDF 文件於 Python 中。此方法保證 HTML 包括 CSS 和 JavaScript 能精確地轉換為高品質的 PDF。
什麼庫支持 HTML 到 PDF 的轉換在 Python 中?
IronPDF 是一個強大的庫,支持在 Python 中將 HTML 轉換為 PDF。它提供多種方法將 HTML 字串、URL 和文件轉換為 PDF 文件,同時保持格式。
如何安裝 IronPDF 以便在 Python 中進行 HTML 到 PDF 的轉換?
要安裝 IronPDF 到 Python,請在終端中使用命令 pip install ironpdf。注意您需要安裝 .NET 6.0 SDK,因為 IronPDF 依賴於它。
我可以將網頁 URL 轉換為 PDF 在 Python 中嗎?
是的,您可以使用 IronPDF 的 RenderUrlAsPdf 方法將網頁 URL 轉換為 PDF 文件。此功能允許您直接捕捉並轉換現場網頁的內容。
IronPDF 在轉換過程中如何處理外部資源?
IronPDF 可處理包含外部資源(如圖片、樣式表和腳本)的 HTML 文件。它會解決相對 URL,以確保這些資源正確地整合到 PDF 中。
是否可以使用 Python 自訂 PDF 的頁眉和頁腳?
是的,IronPDF 允許您將自定義頁眉和頁腳添加到您的 PDF 文件中。這可以透過調整 PdfDocument 屬性來滿足您的特定格式需求來完成。
如何去除使用 IronPDF 創建的 PDF 中的水印?
要去除由 IronPDF 生成的 PDF 上的水印,您需要在處理 PDF 前設置有效的許可證密鑰。這確保PDF被創建時不會有任何預設水印。
IronPDF 的 HTML 到 PDF 轉換有哪些進階功能?
IronPDF 提供進階功能,如設定自訂頁邊距、調整尺寸、添加水印、優化文件大小和提取文本。這些功能增強了庫的靈活性和實用性。
在哪裡可以找到使用 IronPDF 進行 HTML 到 PDF 轉換的例子?
您可以在 IronPDF 網站的 '代碼範例' 部分找到各種例子和詳細代碼片段,這些資源提供了有效利用 IronPDF 功能的見解。
IronPDF 用於渲染 PDF 的主要類是什麼?
ChromePdfRenderer 類是 IronPDF 用於渲染 PDF 的主要類。它提供了可靠的方法來轉換 HTML,處理外部資源,並確保如同現代瀏覽器般準確的渲染。
IronPDF 是否與 .NET 10 相容?
是的 - IronPDF 與 .NET 10 完全相容,就像與 .NET 6、7、8 和 9 等早期版本相容一樣。IronPDF 與 .NET 10 專案開箱即用,不論平台(Windows、Linux 等),並支援最新的 API 堆疊,無需特殊的變通。










