PYTHON PDF 工具 如何在 Python 中创建 PDF 文件 Curtis Chau 已更新:六月 22, 2025 Download IronPDF pip 下载 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 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 reportlab pip install reportlab SHELL 注意:在安装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() PYTHON 代码解释 导入所有模块和包后,我们首先初始化将写入PDF文件的所有内容。 fileName = 'sample.pdf' documentTitle = 'sample' title = 'Create PDF' subTitle = 'Using ReportLab !!' fileName = 'sample.pdf' documentTitle = 'sample' title = 'Create PDF' subTitle = 'Using ReportLab !!' PYTHON 现在,我们创建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) PYTHON 最后,当所有内容都绘制在画布上时,我们保存PDF文件。 # Saving the PDF pdf.save() # Saving the PDF pdf.save() PYTHON 我们还可以使用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 pdfkit pip install pdfkit SHELL 从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') PYTHON 从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') PYTHON 从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') PYTHON PDFKit允许您轻松使用HTML模板在Python中创建PDF。 IronPDF 库 IronPDF is a useful tool to 创建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") PYTHON 以下代码将帮助您使用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") PYTHON 您可以从上面的代码中看到,它非常简单和清晰。 很少行代码就可以从HTML代码创建一个PDF文件。 它是一个快速、可靠、节省时间并且结果准确的解决方案。 下载IronPDF并尝试免费。 试用期结束后,许可费用从$799开始。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已更新六月 22, 2025 在 Python 中查找列表中的项 本文探索了使用 Python 在列表中查找任何元素时的各种方法,它将为您提供可用选项及其应用的全面理解。 阅读更多 已更新六月 22, 2025 Spyder Python IDE:完整指南 在本文中,我们将探索什么是 Spyder,如何安装它,以及如何使用其关键功能。 阅读更多 已更新七月 28, 2025 在 Python 中使用 Pytest 编写测试 PyTest 是一个强大、灵活且用户友好的测试框架,在 Python 社区中非常受欢迎 阅读更多 如何使用 PyCharm(开发人员指南)如何在 Python 中读取 PDF 文件