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. 安装 IronPDF PDF 库用于 Python
要为 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 文档,适用于三个关键场景:
- 将 HTML 字符串/标记转换为 PDF
- 将 HTML 文件/压缩包转换为 PDF
- 将网址转换为 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[{i:(Logger.LogFilePath 应在使用任何 PDF 转换和操作方法之前调用。
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 文档,其中引用了一个 CSS 文件和一个存储在 assets 文件夹中的图像:
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 方法提供第二个参数,以便指定引用网络资产的基本路径。该路径可以指向文件系统上的本地目录,甚至是 URL 路径。
要更好地理解如何使用 RenderHtmlAsPdf 方法,你可以参考这个代码示例或查阅 API 参考页面以获取更详细的信息。
2.5 从 URL 创建 PDF
要将网站网址转换为 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 将示例 HTML 文件转换为 PDF,使用以下 Python 代码:
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 文件中的相对 URLs,确保任何引用的样式表和脚本被正确应用到生成的 PDF 文档中。 这确保了网页的视觉外观在 PDF 文件中准确再现。
3. 深入阅读
通过深入我们的代码示例部分来探索 IronPDF 的 HTML 到 PDF 渲染的广泛能力。
- 阅读这个代码示例以了解如何在转换过程中自定义PDF文档的外观。
- 了解如何生成带有个性化页眉和页脚的 PDF 文件,调整边距尺寸和纸张尺寸,添加水印等。
- 此外,探索提取文本、优化文件大小和以编程方式打印 PDF等技术。
下载软件产品。
常见问题解答
如何使用 Python 将 HTML 转换为 PDF?
您可以使用 IronPDF 的 RenderHtmlAsPdf 方法在 Python 中将 HTML 字符串转换为 PDF 文档。此方法确保包括 CSS 和 JavaScript 的 HTML 被准确地渲染为高质量的 PDF。
支持在 Python 中进行 HTML 到 PDF 转换的库是什么?
IronPDF 是一个强大的库,支持在 Python 中进行 HTML 到 PDF 转换。它提供多种方法,将 HTML 字符串、URL 和文件转换为 PDF 文档,同时保持格式。
如何安装 IronPDF 以进行 Python 中的 HTML 到 PDF 转换?
要在 Python 中安装 IronPDF,请在终端中使用命令 pip install ironpdf。请注意,您需要安装 .NET 6.0 SDK,因为 IronPDF 依赖于它。
我可以在 Python 中将网页 URL 转换为 PDF 吗?
是的,您可以使用 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 一样。它可以在 .NET 10 项目中开箱即用,不受平台(Windows、Linux 等)的限制,并且支持最新的 API 堆栈,无需任何特殊变通方法。










