如何在 Python 中创建 PDF 文件
PDF(可移植文档格式)是最流行的在线发送和接收数据的数字文件格式。主要用于保持数据格式并通过加密密码保护数据安全。 .pdf扩展名与软件应用程序、硬件或操作系统无关。
在这篇文章中,我们将用Python编程语言来创建一个PDF文件。 网上有很多选项可用,但在这里我们将使用Python库来创建PDF文件。 以下是用Python生成单页或多页PDF文档的两大著名库:
- Reportlab
- PDFKit
从上述的PDF Python库中,我们可以使用任何一个来生成PDF。
如何在Python中创建PDF文件?
让我们逐一看看这两个库。
使用Reportlab库创建PDF文件
Reportlab库是一个免费开源的PDF工具包,可以用来轻松创建PDF文件。 它提供了一堆绘图工具,可以在多页上某个位置添加图像和文本。 您也可以使用encryptCanvas方法创建加密的PDF文件。
安装
要安装Reportlab,需要pip包管理器。 它会自动下载并通过pip命令安装请求的软件包。 只需在Windows cmd或PowerShell中输入以下命令:
pip install reportlabpip install reportlab注意:在安装Python时,必须将其添加到路径环境变量中,以便可以从cmd或PowerShell中的任何地方执行上述命令。 推荐使用Pip用于Python 3+,因为它是更新版本。
打开一个新的Python文件
为了使用Reportlab库,我们需要在Python文件中编写代码并执行以创建PDF文件。
- 从Windows搜索栏搜索并打开Python默认IDLE shell,然后按Ctrl + N或从文件标签中选择"新文件"。 这将打开文本编辑器以编写代码。
- 接下来,以适当的名称保存文件。 我将其命名为"createpdf.py"。
用于创建PDF的Python代码
以下代码将绘制文档元素,并在几秒钟内生成PDF:
# Importing required modules from ReportLab
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors
# File and document attributes
fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'
# Creating a PDF object
pdf = canvas.Canvas(fileName)
# Setting the title of the document
pdf.setTitle(documentTitle)
# Registering a TrueType font
pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf'))
# Creating the title by setting its font and placing it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)
# Creating the subtitle by setting its font, color, and placing it on the canvas
pdf.setFillColorRGB(0, 0, 255) # Set color to blue
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)
# Saving the PDF
pdf.save()# Importing required modules from ReportLab
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors
# File and document attributes
fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'
# Creating a PDF object
pdf = canvas.Canvas(fileName)
# Setting the title of the document
pdf.setTitle(documentTitle)
# Registering a TrueType font
pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf'))
# Creating the title by setting its font and placing it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)
# Creating the subtitle by setting its font, color, and placing it on the canvas
pdf.setFillColorRGB(0, 0, 255) # Set color to blue
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)
# Saving the PDF
pdf.save()代码解释
导入所有模块和包后,我们首先初始化将写入PDF文件的所有内容。
fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'现在,我们创建PDF画布,设置文档标题,然后在画布上添加居中的标题和副标题,并使用适当的字体和大小。
# Creating a PDF object
pdf = canvas.Canvas(fileName)
# Setting the title of the document
pdf.setTitle(documentTitle)
# Registering a TrueType font
pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf'))
# Creating the title by setting its font and placing it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)
# Creating the subtitle by setting its font, color, and placing it on the canvas
pdf.setFillColorRGB(0, 0, 255) # Set color to blue
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)# Creating a PDF object
pdf = canvas.Canvas(fileName)
# Setting the title of the document
pdf.setTitle(documentTitle)
# Registering a TrueType font
pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf'))
# Creating the title by setting its font and placing it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)
# Creating the subtitle by setting its font, color, and placing it on the canvas
pdf.setFillColorRGB(0, 0, 255) # Set color to blue
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)最后,当所有内容都绘制在画布上时,我们保存PDF文件。
# Saving the PDF
pdf.save()# Saving the PDF
pdf.save()我们还可以使用drawString和drawText方法在Python中使用Reportlab创建一个简单的PDF文件。
使用PDFKit库创建PDF文件
PDFKit库是创建Python PDF文件的最佳方法之一。 它可以使用HTML代码创建PDF文件。 您可以渲染简单和复杂的HTML文件或从URL获取的HTML,生成像素完美的可打印PDF页面。 然而,PDFKit集成了wkhtmltopdf功能来将HTML转换为PDF。 要为Windows、Linux和Mac安装wkhtmltopdf,请访问此链接。
注意:在Windows操作系统中,wkhtmltopdf将安装在程序文件中。
安装
使用以下命令来安装PDFKit:
pip install pdfkitpip install pdfkit从URL创建PDF文件
使用PDFKit创建PDF文件非常简单,是一个单行过程。
import pdfkit
# Convert a webpage from a URL to a PDF file
pdfkit.from_url('http://google.com', 'out.pdf')import pdfkit
# Convert a webpage from a URL to a PDF file
pdfkit.from_url('http://google.com', 'out.pdf')从HTML文件创建PDF文件
import pdfkit
# Convert an HTML file to a PDF file
pdfkit.from_file('index.html', 'out.pdf')import pdfkit
# Convert an HTML file to a PDF file
pdfkit.from_file('index.html', 'out.pdf')从HTML模板创建PDF文件
您可以将HTML模板作为字符串传递,以将其转换为PDF作为输出文件。
import pdfkit
# HTML content to convert to PDF
html_string = """
<html>
<head>
<meta name="pdfkit-page-size" content="Legal"/>
<meta name="pdfkit-orientation" content="Landscape"/>
</head>
<body>Hello World!</body>
</html>
"""
# Convert HTML string to a PDF file
pdfkit.from_string(html_string, 'out.pdf')import pdfkit
# HTML content to convert to PDF
html_string = """
<html>
<head>
<meta name="pdfkit-page-size" content="Legal"/>
<meta name="pdfkit-orientation" content="Landscape"/>
</head>
<body>Hello World!</body>
</html>
"""
# Convert HTML string to a PDF file
pdfkit.from_string(html_string, 'out.pdf')PDFKit允许您轻松使用HTML模板在Python中创建PDF。
IronPDF 库
IronPDF是一个有用的工具,用于在.NET项目中创建PDF文件。 该库的一个常见用途是"HTML到PDF"渲染,其中HTML用作渲染PDF文档的设计语言。
IronPDF 使用 .NET Chromium 引擎将 HTML 页面渲染为 PDF 文件。 使用HTML到PDF转换,无需使用复杂的API来定位或设计PDF。 IronPDF还支持所有标准的网页技术:HTML、ASPX、JS、CSS和图像。
它还使您能够使用HTML5、CSS、JavaScript和图像创建一个.NET PDF库。 您可以轻松编辑、盖章并向PDF添加页眉和页脚。 此外,它还使读取PDF文本和提取图像变得非常容易。
要开始使用IronPDF,您需要安装NuGet包(确保此步骤已验证或在.NET开发环境中运行):
pip install ironpdf
以下示例帮助您直接从URL创建PDF:
from ironpdf import ChromePdfRenderer
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from a URL
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/")
# Export to a file
pdf.SaveAs("url.pdf")from ironpdf import ChromePdfRenderer
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from a URL
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/")
# Export to a file
pdf.SaveAs("url.pdf")以下代码将帮助您使用HTML代码以及任何CSS或JavaScript来创建一个PDF文件:
from ironpdf import ChromePdfRenderer
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from an HTML string using Python
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
# Export to a file
pdf.SaveAs("output.pdf")
# Advanced Example with HTML Assets
# Load external HTML assets: Images, CSS, and JavaScript.
# An optional BasePath is set as the file location to load assets from
myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", base_path=r"C:\site\assets")
myAdvancedPdf.SaveAs("html-with-assets.pdf")from ironpdf import ChromePdfRenderer
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from an HTML string using Python
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
# Export to a file
pdf.SaveAs("output.pdf")
# Advanced Example with HTML Assets
# Load external HTML assets: Images, CSS, and JavaScript.
# An optional BasePath is set as the file location to load assets from
myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", base_path=r"C:\site\assets")
myAdvancedPdf.SaveAs("html-with-assets.pdf")您可以从上面的代码中看到,它非常简单和清晰。 很少行代码就可以从HTML代码创建一个PDF文件。 它是一个快速、可靠、节省时间并且结果准确的解决方案。
下载IronPDF并尝试免费。 试用期结束后,许可费用从$799开始。










