跳至页脚内容
使用 IRONPDF FOR PYTHON

Python PdfWriter(代码示例教程)

IronPDF是一个纯 Python PDF 文件对象库,适用于希望在应用程序中编写 PDF 文件或操作 PDF 文件的 Python 开发人员。 IronPDF 以其简洁性和多功能性脱颖而出,使其成为需要自动创建 PDF 或将 PDF 生成集成到软件系统中的任务的理想选择。

本指南将探讨如何使用纯 Python PDF 库 IronPDF 来创建 PDF 文件或 PDF 页面属性以及读取 PDF 文件。 它将包含示例和实用代码片段,让您亲身了解如何在 Python 项目中使用 IronPDF for Python 的 PdfWriter 来写入 PDF 文件和创建新的 PDF 页面。

设置IronPDF

安装

要开始使用 IronPDF,您需要通过 Python 包索引安装它。 在终端中运行以下命令:

 pip install ironpdf

编写和操作 PDF 文件

创建新的PDF

IronPDF 简化了创建新 PDF 文件和处理现有 PDF 文件的过程。 它提供了一个简单的界面来生成文档,无论是简单的单页 PDF 文档,还是包含用户密码等各种元素的更复杂的文档。 此功能对于生成报告、创建发票等任务至关重要。

from ironpdf import ChromePdfRenderer, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Basic HTML content for the PDF
html = """
<html>
   <head>
      <title>IronPDF for Python!</title>
      <link rel='stylesheet' href='assets/style.css'>
   </head>
   <body>
      <h1>It's IronPDF World!!</h1>
      <a href="https://ironpdf.com/python/"><img src='assets/logo.png' /></a>
   </body>
</html>
"""

# Create a PDF renderer
renderer = ChromePdfRenderer()
# Render the HTML content as a PDF
pdf = renderer.RenderHtmlAsPdf(html)
# Save the rendered PDF to a file
pdf.SaveAs("New PDF File.pdf")
from ironpdf import ChromePdfRenderer, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Basic HTML content for the PDF
html = """
<html>
   <head>
      <title>IronPDF for Python!</title>
      <link rel='stylesheet' href='assets/style.css'>
   </head>
   <body>
      <h1>It's IronPDF World!!</h1>
      <a href="https://ironpdf.com/python/"><img src='assets/logo.png' /></a>
   </body>
</html>
"""

# Create a PDF renderer
renderer = ChromePdfRenderer()
# Render the HTML content as a PDF
pdf = renderer.RenderHtmlAsPdf(html)
# Save the rendered PDF to a file
pdf.SaveAs("New PDF File.pdf")
PYTHON

Python PDFWriter(代码示例教程),图 1:输出文件 输出文件

合并 PDF 文件

IronPDF 简化了将多个 PDF 文件合并为一个文件的任务。 此功能有利于汇总各种报告、组装扫描文档或整理属于同一类别的信息。 例如,当您从多个来源创建综合报告时,或者当您有一系列需要作为单个文件呈现的文档时,您可能需要合并 PDF 文件。

from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load existing PDF documents
pdfOne = PdfDocument("Report First.pdf")
pdfTwo = PdfDocument("Report Second.pdf")
# Merge the PDFs into a single document
merged = PdfDocument.Merge(pdfOne, pdfTwo)
# Save the merged PDF
merged.SaveAs("Merged.pdf")
from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load existing PDF documents
pdfOne = PdfDocument("Report First.pdf")
pdfTwo = PdfDocument("Report Second.pdf")
# Merge the PDFs into a single document
merged = PdfDocument.Merge(pdfOne, pdfTwo)
# Save the merged PDF
merged.SaveAs("Merged.pdf")
PYTHON

将现有 PDF 文件合并到新的 PDF 文件中的功能在数据科学等领域也很有用,因为合并后的 PDF 文档可以作为训练 AI 模块的数据集。 IronPDF 可以轻松完成这项任务,保持原始文档每一页的完整性和格式,从而生成无缝且连贯的输出 PDF 文件。

Python PDFWriter(代码示例教程),图 2:合并后的 PDF 输出 合并 PDF 输出

拆分单个 PDF

反之,IronPDF 也非常擅长将现有的 PDF 文件分割成多个新文件。 当您需要从大型 PDF 文档中提取特定部分,或者将文档分成更小、更易于管理的部分时,此功能非常有用。

from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load the PDF document
pdf = PdfDocument("Report.pdf")
# Extract the first page
page1doc = pdf.CopyPage(0)
# Save the extracted page as a new PDF
page1doc.SaveAs("Split1.pdf")
from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load the PDF document
pdf = PdfDocument("Report.pdf")
# Extract the first page
page1doc = pdf.CopyPage(0)
# Save the extracted page as a new PDF
page1doc.SaveAs("Split1.pdf")
PYTHON

例如,您可能希望从大型报告中分离出某些 PDF 页面,或者从一本书的不同章节创建单独的文档。 IronPDF 允许您选择要转换为新 PDF 文件的所需多页,确保您可以根据需要操作和管理 PDF 内容。

Python PDFWriter(代码示例教程),图 3:拆分 PDF 输出 拆分 PDF 输出

实施安全功能

处理敏感或机密信息时,保护PDF文档的安全至关重要。 IronPDF 通过提供强大的安全功能(包括用户密码保护和加密)来满足这一需求。 这样可以确保您的 PDF 文件安全无虞,只有授权用户才能访问。

from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load the PDF document
pdf = PdfDocument("Report.pdf")
# Adjust security settings to make the PDF read-only and set permissions
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key")
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights
# Set the document encryption passwords
pdf.SecuritySettings.OwnerPassword = "top-secret"  # password to edit the PDF
pdf.SecuritySettings.UserPassword = "sharable"  # password to open the PDF
# Save the secured PDF
pdf.SaveAs("secured.pdf")
from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load the PDF document
pdf = PdfDocument("Report.pdf")
# Adjust security settings to make the PDF read-only and set permissions
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key")
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights
# Set the document encryption passwords
pdf.SecuritySettings.OwnerPassword = "top-secret"  # password to edit the PDF
pdf.SecuritySettings.UserPassword = "sharable"  # password to open the PDF
# Save the secured PDF
pdf.SaveAs("secured.pdf")
PYTHON

通过设置用户密码,您可以控制谁可以查看或编辑您的 PDF 文档。 加密选项增加了一层额外的安全保障,保护您的数据免受未经授权的访问,使 IronPDF 成为管理 PDF 格式敏感信息的可靠选择。

从PDF中提取文本

IronPDF的另一个关键特性是能够从PDF文档中提取文本。 此功能对于数据检索、内容分析,甚至将现有 PDF 中的文本内容重新用于新文档都特别有用。

from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load the PDF document
pdf = PdfDocument("Report.pdf")
# Extract all text from the PDF document
allText = pdf.ExtractAllText()
# Extract text from a specific page in the document
specificPage = pdf.ExtractTextFromPage(3)
from ironpdf import PdfDocument, License, Logger

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load the PDF document
pdf = PdfDocument("Report.pdf")
# Extract all text from the PDF document
allText = pdf.ExtractAllText()
# Extract text from a specific page in the document
specificPage = pdf.ExtractTextFromPage(3)
PYTHON

无论您是提取数据进行分析、在大文档中搜索特定信息,还是将内容从 PDF 转换为文本文件进行进一步处理,IronPDF 都能让这一切变得简单高效。 该库确保提取的文本保持其原始格式和结构,使其能够立即用于您的特定需求。

管理文档信息

高效管理PDF文件不仅仅关乎其内容。 IronPDF 可以有效地管理文档元数据和属性,例如作者姓名、文档标题、创建日期等。 此功能对于组织和编目 PDF 文档至关重要,尤其是在文档来源和元数据很重要的环境中。

from ironpdf import PdfDocument, License, Logger
from datetime import datetime

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load an existing PDF or create a new one
pdf = PdfDocument("Report.pdf")
# Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = datetime.now()
# Save the PDF with updated metadata
pdf.SaveAs("MetaData Updated.pdf")
from ironpdf import PdfDocument, License, Logger
from datetime import datetime

# Set the IronPDF license key
License.LicenseKey = "Your-License-Key"
# Enable logging for debugging purposes
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load an existing PDF or create a new one
pdf = PdfDocument("Report.pdf")
# Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = datetime.now()
# Save the PDF with updated metadata
pdf.SaveAs("MetaData Updated.pdf")
PYTHON

例如,在学术或企业环境中,能够跟踪文档的创建日期和作者对于记录保存和文档检索至关重要。 IronPDF 让管理这些信息变得轻松,它提供了一种简化的方式来处理和更新 Python 应用程序中的文档信息。

结论

Python PDFWriter(代码示例教程),图 4:许可证 License

本教程介绍了在 Python 中使用 IronPDF 进行 PDF 处理的基础知识。 从创建新的 PDF 文件到合并现有文件,再到添加安全功能,IronPDF 对于任何 Python 开发人员来说都是一款功能全面的工具。

IronPDF for Python 还提供以下功能:

IronPDF for Python 提供免费试用版,供用户探索其功能。 试用期结束后,如需继续使用,许可证起价为$799 。 这种定价方式让开发人员能够在他们的项目中充分利用 IronPDF 的全部功能。

常见问题解答

我如何在 Python 中创建 PDF 文件?

您可以使用 IronPDF 的 CreatePdf 方法生成新的 PDF 文件。此方法允许您从头开始使用 Python 创建自定义 PDF 文档。

安装 IronPDF for Python 的步骤是什么?

要安装 IronPDF for Python,您可以通过执行以下命令使用 Python 包索引:pip install ironpdf

如何使用 Python 将多个 PDF 合并为一个?

IronPDF 提供合并多个 PDF 文件的功能。您可以使用 MergePdfFiles 方法将多个 PDF 合并为一个文档。

我可以用 IronPDF 将 PDF 拆分为单独的页面吗?

是的,IronPDF 提供 SplitPdf 函数,允许您将 PDF 分成单独的页面或部分,为每个部分创建单独的文件。

IronPDF 支持哪些 PDF 安全功能?

IronPDF 支持多个安全功能,包括密码保护和加密,以确保您的 PDF 文件安全并仅限授权用户访问。

我如何在 Python 中从 PDF 文档中提取文本?

使用 IronPDF,您可以轻松地从 PDF 文档中提取文本,使用 ExtractText 方法,这对于数据检索和分析非常有用。

IronPDF 提供了哪些关键的 PDF 操作功能?

IronPDF 允许您创建、合并和拆分 PDF,应用安全措施,提取文本以及管理文档元数据,如作者姓名和创建日期。

IronPDF 是否提供免费试用,并且我该如何访问它?

是的,IronPDF 提供免费试用。您可以在试用期内探索其功能,之后可购买许可证以继续使用。

在 Python 项目中 IronPDF 有哪些实际应用场景?

IronPDF 非常适合生成报告、创建发票、保护文档以及管理 PDF 元数据的各种 Python 项目。

我如何使用 IronPDF 管理 PDF 元数据?

IronPDF 使您能够管理 PDF 元数据,包括作者姓名、文档标题和创建日期,这对于文档组织和编目非常重要。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。