如何在 Python 中编辑 PDF 文件
Iron Software 推出了IronPDF for Python 库,该解决方案彻底改变了在 Python 中执行 PDF 编辑任务的便捷性。 无论您需要插入签名、添加 HTML 页脚、嵌入水印、添加注释还是编辑 PDF 文件,IronPDF for Python 都是您的首选工具。 该库确保您的代码保持可读性,支持以编程方式创建 PDF,方便调试,并可在所有兼容的平台和环境中无缝部署。
本文将通过 Python 代码示例和全面解释,深入探讨这些丰富的功能。 看完本指南,您将全面了解如何使用 IronPDF for Python 来满足您的所有 PDF 编辑需求。
如何在 Python 中编辑 PDF 文件
- 使用
pipInstaller 安装 Python PDF 库。 - 应用 Python PDF 库的许可证密钥。
- 加载要编辑的 PDF 文档。
- 使用拆分、复制页面等不同选项编辑 PDF 文档,以及其他 PDF 操作。
- 使用
SaveAs功能保存修改后的文件。
编辑文档结构
操作页面
IronPDF 简化了在特定位置添加页面、提取特定页面或一系列页面以及从任何 PDF 中删除页面的过程。 它可以为您处理所有复杂的流程,让您轻松高效地完成这些任务。
添加页面
您可以通过指定页面内容、大小和位置,向 PDF 文档添加页面。 完成所需更改后,您可以使用SaveAs功能保存输出的 PDF 文件。
from ironpdf import *
# Enable debugging and set log path
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All
# Load existing PDF and Render HTML as new PDF page
pdf = PdfDocument("C:\\Users\\Administrator\\Downloads\\Documents\\sample.pdf")
renderer = ChromePdfRenderer()
coverPagePdf = renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>")
# Prepend new page to existing PDF
pdf.PrependPdf(coverPagePdf)
# Save the updated PDF document
pdf.SaveAs("report_with_cover.pdf")from ironpdf import *
# Enable debugging and set log path
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All
# Load existing PDF and Render HTML as new PDF page
pdf = PdfDocument("C:\\Users\\Administrator\\Downloads\\Documents\\sample.pdf")
renderer = ChromePdfRenderer()
coverPagePdf = renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>")
# Prepend new page to existing PDF
pdf.PrependPdf(coverPagePdf)
# Save the updated PDF document
pdf.SaveAs("report_with_cover.pdf")复制页面
您可以通过指定页码和目标位置,将一个 PDF 文档中的页面复制到另一个现有的 PDF 文件中。 此外,您还可以选择从复制的 PDF 页面创建新的 PDF 文件。 也可以从单个 PDF 文件中选择一页或多页进行复制。
from ironpdf import *
# Load the PDF document
pdf = PdfDocument("C:\\Users\\Administrator\\Downloads\\Documents\\sample.pdf")
# Copy pages 3 to 5 and save them as a new document.
pdf.CopyPages(2, 4).SaveAs("report_highlight.pdf")from ironpdf import *
# Load the PDF document
pdf = PdfDocument("C:\\Users\\Administrator\\Downloads\\Documents\\sample.pdf")
# Copy pages 3 to 5 and save them as a new document.
pdf.CopyPages(2, 4).SaveAs("report_highlight.pdf")删除页面
您可以通过指定页码从输入的 PDF 文件中删除页面。
from ironpdf import *
# Load the PDF document
pdf = PdfDocument("report.pdf")
# Remove the last page from the PDF
pdf.RemovePage(pdf.PageCount-1)
# Save the updated PDF
pdf.SaveAs("Report-Minus-1.pdf")from ironpdf import *
# Load the PDF document
pdf = PdfDocument("report.pdf")
# Remove the last page from the PDF
pdf.RemovePage(pdf.PageCount-1)
# Save the updated PDF
pdf.SaveAs("Report-Minus-1.pdf")合并和拆分 PDF
IronPDF 的用户友好型 API 可以轻松地将多个 PDF 文件合并为一个,或者将现有的 PDF 文件拆分为单独的文件。
将多个现有 PDF 文件合并为一个 PDF 文档
您可以通过指定输入 PDF 文档和输出 PDF 文档,将多个 PDF 文档合并成一个文档。
from ironpdf import *
# Define HTML content for two separate PDFs
html_a = """<p> [PDF_A] </p>
<p> [PDF_A] 1st Page </p>
<div style='page-break-after: always;'></div>
<p> [PDF_A] 2nd Page</p>"""
html_b = """<p> [PDF_B] </p>
<p> [PDF_B] 1st Page </p>
<div style='page-break-after: always;'></div>
<p> [PDF_B] 2nd Page</p>"""
# Render each HTML content as PDF
renderer = ChromePdfRenderer()
pdfdoc_a = renderer.RenderHtmlAsPdf(html_a)
pdfdoc_b = renderer.RenderHtmlAsPdf(html_b)
# Merge the PDFs into a single document
merged = PdfDocument.Merge(pdfdoc_a, pdfdoc_b)
# Save the merged PDF
merged.SaveAs("Merged.pdf")from ironpdf import *
# Define HTML content for two separate PDFs
html_a = """<p> [PDF_A] </p>
<p> [PDF_A] 1st Page </p>
<div style='page-break-after: always;'></div>
<p> [PDF_A] 2nd Page</p>"""
html_b = """<p> [PDF_B] </p>
<p> [PDF_B] 1st Page </p>
<div style='page-break-after: always;'></div>
<p> [PDF_B] 2nd Page</p>"""
# Render each HTML content as PDF
renderer = ChromePdfRenderer()
pdfdoc_a = renderer.RenderHtmlAsPdf(html_a)
pdfdoc_b = renderer.RenderHtmlAsPdf(html_b)
# Merge the PDFs into a single document
merged = PdfDocument.Merge(pdfdoc_a, pdfdoc_b)
# Save the merged PDF
merged.SaveAs("Merged.pdf")拆分 PDF 并提取页面
您可以通过指定输入 PDF 文档和输出 PDF 文档或页码,将 PDF 文档拆分为多个文档,或从 PDF 文件中提取特定页面。
from ironpdf import *
# Define the HTML structure of the document
html = """<p> Hello Iron </p>
<p> This is 1st Page </p>
<div style='page-break-after: always;'></div>
<p> This is 2nd Page</p>
<div style='page-break-after: always;'></div>
<p> This is 3rd Page</p>"""
# Render the HTML as a PDF document
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf(html)
# Create a separate document for the first page
page1doc = pdf.CopyPage(0)
page1doc.SaveAs("Split1.pdf")
# Create a separate document for pages 2 and 3
page23doc = pdf.CopyPages(1, 2)
page23doc.SaveAs("Split2.pdf")from ironpdf import *
# Define the HTML structure of the document
html = """<p> Hello Iron </p>
<p> This is 1st Page </p>
<div style='page-break-after: always;'></div>
<p> This is 2nd Page</p>
<div style='page-break-after: always;'></div>
<p> This is 3rd Page</p>"""
# Render the HTML as a PDF document
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf(html)
# Create a separate document for the first page
page1doc = pdf.CopyPage(0)
page1doc.SaveAs("Split1.pdf")
# Create a separate document for pages 2 and 3
page23doc = pdf.CopyPages(1, 2)
page23doc.SaveAs("Split2.pdf")编辑文档属性
添加和使用 PDF 元数据
您可以使用 IronPDF for Python 添加和使用 PDF 元数据。 这对于添加版权信息、跟踪更改或使 PDF 文档更易于搜索都很有用。
PDF元数据是存储在PDF文档中的数据集合。 这些数据可以包括 PDF 文档的标题、作者、主题、关键词、创建日期和修改日期。 此外,它还可以包含您根据需要添加的自定义数据。
from ironpdf import *
from datetime import datetime
# Load the encrypted PDF document
pdf = PdfDocument.FromFile("encrypted.pdf", "password")
# Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = datetime.now()
# Save the updated PDF document
pdf.SaveAs("MetaData-Updated.pdf")from ironpdf import *
from datetime import datetime
# Load the encrypted PDF document
pdf = PdfDocument.FromFile("encrypted.pdf", "password")
# Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = datetime.now()
# Save the updated PDF document
pdf.SaveAs("MetaData-Updated.pdf")数字签名
IronPDF 允许您使用.pfx和.p12 X509Certificate2 数字证书对新的或现有的 PDF 文件进行数字签名。 使用此方法对 PDF 文件进行签名后,对文档的任何修改都需要通过证书进行验证,从而确保文档的完整性。
您可以在Adobe 网站上找到更多关于如何使用 Adobe Reader 免费生成签名证书的指导。
除了加密签名外,IronPDF 还支持使用手写签名图像或公司印章图像作为签署文档的替代方式。
from ironpdf import *
# Cryptographically sign an existing PDF in one line of code!
PdfSignature(r".\certificates\IronSoftware.p12", "123456").SignPdfFile("any.pdf")
##### Advanced example for more control #####
# Step 1. Create a PDF.
renderer = ChromePdfRenderer()
doc = renderer.RenderHtmlAsPdf("<h1>Testing 2048 bit digital security</h1>")
# Step 2. Create a digital signature.
signature = PdfSignature(r"certificates\IronSoftware.pfx", "123456")
# Step 3. Optional signing options and a handwritten signature graphic.
signature.SigningContact = "support@ironsoftware.com"
signature.SigningLocation = "Chicago, USA"
signature.SigningReason = "To show how to sign a PDF"
# Step 4. Sign the PDF with the PdfSignature.
doc.Sign(signature)
# Step 5. The PDF is not signed until saved to file, stream, or byte array.
doc.SaveAs("signed.pdf")from ironpdf import *
# Cryptographically sign an existing PDF in one line of code!
PdfSignature(r".\certificates\IronSoftware.p12", "123456").SignPdfFile("any.pdf")
##### Advanced example for more control #####
# Step 1. Create a PDF.
renderer = ChromePdfRenderer()
doc = renderer.RenderHtmlAsPdf("<h1>Testing 2048 bit digital security</h1>")
# Step 2. Create a digital signature.
signature = PdfSignature(r"certificates\IronSoftware.pfx", "123456")
# Step 3. Optional signing options and a handwritten signature graphic.
signature.SigningContact = "support@ironsoftware.com"
signature.SigningLocation = "Chicago, USA"
signature.SigningReason = "To show how to sign a PDF"
# Step 4. Sign the PDF with the PdfSignature.
doc.Sign(signature)
# Step 5. The PDF is not signed until saved to file, stream, or byte array.
doc.SaveAs("signed.pdf")PDF附件
IronPDF 让您能够非常轻松地向 PDF 文档添加附件,并随时删除它们。 这意味着您可以向 PDF 文件中添加额外的文件,并根据需要将其删除,这一切都可以在 IronPDF 的帮助下完成。
from ironpdf import *
# Instantiate the Renderer and create a PdfDocument from HTML
renderer = ChromePdfRenderer()
my_pdf = renderer.RenderHtmlFileAsPdf("my-content.html")
# Open the PDF document to be attached
pdf = PdfDocument.FromFile("new_sample.pdf")
# Add an attachment with a name and a byte array
attachment1 = my_pdf.Attachments.AddAttachment("attachment_1", pdf.BinaryData)
# Remove an attachment
my_pdf.Attachments.RemoveAttachment(attachment1)
# Save the PDF with attachments
my_pdf.SaveAs("my-content.pdf")from ironpdf import *
# Instantiate the Renderer and create a PdfDocument from HTML
renderer = ChromePdfRenderer()
my_pdf = renderer.RenderHtmlFileAsPdf("my-content.html")
# Open the PDF document to be attached
pdf = PdfDocument.FromFile("new_sample.pdf")
# Add an attachment with a name and a byte array
attachment1 = my_pdf.Attachments.AddAttachment("attachment_1", pdf.BinaryData)
# Remove an attachment
my_pdf.Attachments.RemoveAttachment(attachment1)
# Save the PDF with attachments
my_pdf.SaveAs("my-content.pdf")压缩 PDF
IronPDF 具有压缩 PDF 文件的功能,可以帮助减小文件大小。其中一种方法是使用CompressImages方法减小嵌入在 PDF 文档中的图像的大小。
关于图像质量,对于 JPEG 图像,100% 的质量几乎不会造成图像质量损失,而 1% 的质量则会产生非常差的输出质量。 一般来说,图像质量达到 90% 或以上就被认为是高质量的。 中等质量图像的质量介于 80% 到 90% 之间,低质量图像的质量介于 70% 到 80% 之间。 如果低于 70%,图像质量会明显下降,但这可以大幅减小 PDF 文档的整体文件大小。
建议尝试不同的质量百分比,以找到适合您需求的质量和文件大小之间的合适平衡点。 请记住,图像压缩后质量的明显损失程度取决于图像类型,因为有些图像的清晰度损失可能比其他图像更大。
from ironpdf import *
# Load the PDF document
pdf = PdfDocument("document.pdf")
# Compress images within the PDF (quality between 1-100)
pdf.CompressImages(60)
pdf.SaveAs("document_compressed.pdf")
# Compress images with scaling image resolution
pdf.CompressImages(90, True)
pdf.SaveAs("document_scaled_compressed.pdf")from ironpdf import *
# Load the PDF document
pdf = PdfDocument("document.pdf")
# Compress images within the PDF (quality between 1-100)
pdf.CompressImages(60)
pdf.SaveAs("document_compressed.pdf")
# Compress images with scaling image resolution
pdf.CompressImages(90, True)
pdf.SaveAs("document_scaled_compressed.pdf")编辑 PDF 内容
添加页眉和页脚
使用 IronPDF 向 PDF 文档添加页眉和页脚非常简单。 该软件提供两种不同类型的HeaderFooters : TextHeaderFooter和HtmlHeaderFooter 。 TextHeaderFooter非常适合仅包含文本的页眉和页脚,并且可能需要包含合并字段,例如"{page} of {total-pages}"。 另一方面, HtmlHeaderFooter是一个更高级的选项,它可以处理任何 HTML 内容并将其格式化得整齐美观,因此更适合复杂的页眉和页脚。
HTML 页眉和页脚
使用 IronPDF for Python,您可以利用HtmlHeaderFooter功能,从 HTML 为 PDF 文档创建 HTML 标题或页脚。 这意味着您可以使用 HTML 设计页眉或页脚,IronPDF for Python 会将其完美转换为适合您的 PDF,确保每个细节都恰到好处。 因此,如果您有 HTML 设计的页眉或页脚,IronPDF for Python 可以精确地将其应用到您的 PDF 文档中。
from ironpdf import *
import os
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Build a footer using HTML to style the text
renderer.RenderingOptions.HtmlFooter = HtmlHeaderFooter()
renderer.RenderingOptions.HtmlFooter.MaxHeight = 15 # millimeters
renderer.RenderingOptions.HtmlFooter.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"
renderer.RenderingOptions.HtmlFooter.DrawDividerLine = True
# Ensure sufficient bottom margin
renderer.RenderingOptions.MarginBottom = 25 # mm
# Build a header using an image asset
renderer.RenderingOptions.HtmlHeader = HtmlHeaderFooter()
renderer.RenderingOptions.HtmlHeader.MaxHeight = 20 # millimeters
renderer.RenderingOptions.HtmlHeader.HtmlFragment = "<img src='iron.png'>"
renderer.RenderingOptions.HtmlHeader.BaseUrl = os.path.abspath("C:/Users/lyty1/OneDrive/Documents/IronPdfPythonNew")
# Ensure sufficient top margin
renderer.RenderingOptions.MarginTop = 25 # mmfrom ironpdf import *
import os
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Build a footer using HTML to style the text
renderer.RenderingOptions.HtmlFooter = HtmlHeaderFooter()
renderer.RenderingOptions.HtmlFooter.MaxHeight = 15 # millimeters
renderer.RenderingOptions.HtmlFooter.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"
renderer.RenderingOptions.HtmlFooter.DrawDividerLine = True
# Ensure sufficient bottom margin
renderer.RenderingOptions.MarginBottom = 25 # mm
# Build a header using an image asset
renderer.RenderingOptions.HtmlHeader = HtmlHeaderFooter()
renderer.RenderingOptions.HtmlHeader.MaxHeight = 20 # millimeters
renderer.RenderingOptions.HtmlHeader.HtmlFragment = "<img src='iron.png'>"
renderer.RenderingOptions.HtmlHeader.BaseUrl = os.path.abspath("C:/Users/lyty1/OneDrive/Documents/IronPdfPythonNew")
# Ensure sufficient top margin
renderer.RenderingOptions.MarginTop = 25 # mm文本页眉和页脚
from ironpdf import *
# Initiate PDF Renderer
renderer = ChromePdfRenderer()
# Add a text header to every page
renderer.RenderingOptions.FirstPageNumber = 1 # use 2 if a cover page will be appended
renderer.RenderingOptions.TextHeader.DrawDividerLine = True
renderer.RenderingOptions.TextHeader.CenterText = "{url}"
renderer.RenderingOptions.TextHeader.Font = FontTypes.Helvetica
renderer.RenderingOptions.TextHeader.FontSize = 12
renderer.RenderingOptions.MarginTop = 25 # create 25mm space for header
# Add a text footer to every page
renderer.RenderingOptions.TextFooter.DrawDividerLine = True
renderer.RenderingOptions.TextFooter.Font = FontTypes.Arial
renderer.RenderingOptions.TextFooter.FontSize = 10
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}"
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"
renderer.RenderingOptions.MarginBottom = 25 # create 25mm space for footerfrom ironpdf import *
# Initiate PDF Renderer
renderer = ChromePdfRenderer()
# Add a text header to every page
renderer.RenderingOptions.FirstPageNumber = 1 # use 2 if a cover page will be appended
renderer.RenderingOptions.TextHeader.DrawDividerLine = True
renderer.RenderingOptions.TextHeader.CenterText = "{url}"
renderer.RenderingOptions.TextHeader.Font = FontTypes.Helvetica
renderer.RenderingOptions.TextHeader.FontSize = 12
renderer.RenderingOptions.MarginTop = 25 # create 25mm space for header
# Add a text footer to every page
renderer.RenderingOptions.TextFooter.DrawDividerLine = True
renderer.RenderingOptions.TextFooter.Font = FontTypes.Arial
renderer.RenderingOptions.TextFooter.FontSize = 10
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}"
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"
renderer.RenderingOptions.MarginBottom = 25 # create 25mm space for footer大纲和书签
大纲(也称为"书签")是一种可以帮助您快速跳转到 PDF 文档中重要页面的工具。 如果您使用的是 Adobe Acrobat Reader,您可以在应用程序的左侧边栏中看到这些书签(可以按层级结构进行组织)。
IronPDF for Python 库让使用书签变得更加容易。 它可以自动导入PDF文档中已有的书签。 此外,您还可以使用 IronPDF 添加更多书签、编辑书签或将书签分组。
from ironpdf import *
# Load an existing PDF document.
pdf = PdfDocument.FromFile("existing.pdf")
# Add bookmarks to the PDF
pdf.Bookmarks.AddBookMarkAtEnd("Author's Note", 2)
pdf.Bookmarks.AddBookMarkAtEnd("Table of Contents", 3)
# Create a new bookmark and add nested bookmarks
summaryBookmark = pdf.Bookmarks.AddBookMarkAtEnd("Summary", 17)
summaryBookmark.Children.AddBookMarkAtStart("Conclusion", 18)
# Add additional bookmarks
pdf.Bookmarks.AddBookMarkAtEnd("References", 20)
# Save the PDF with new bookmarks
pdf.SaveAs("existing.pdf")from ironpdf import *
# Load an existing PDF document.
pdf = PdfDocument.FromFile("existing.pdf")
# Add bookmarks to the PDF
pdf.Bookmarks.AddBookMarkAtEnd("Author's Note", 2)
pdf.Bookmarks.AddBookMarkAtEnd("Table of Contents", 3)
# Create a new bookmark and add nested bookmarks
summaryBookmark = pdf.Bookmarks.AddBookMarkAtEnd("Summary", 17)
summaryBookmark.Children.AddBookMarkAtStart("Conclusion", 18)
# Add additional bookmarks
pdf.Bookmarks.AddBookMarkAtEnd("References", 20)
# Save the PDF with new bookmarks
pdf.SaveAs("existing.pdf")添加和编辑注释
您可以使用 IronPDF for Python 向 PDF 文档添加和编辑注释。 注释可用于突出显示文本、添加评论或创建链接。 您还可以编辑现有注释。
from ironpdf import *
# Load an existing PDF
pdf = PdfDocument("existing.pdf")
# Create a TextAnnotation object
annotation = TextAnnotation()
annotation.Title = "This is the title"
annotation.Subject = "This is a subject"
annotation.Contents = "This is the comment content..."
annotation.Icon = TextAnnotation.AnnotationIcon.Help
annotation.Opacity = 0.9
annotation.Printable = False
annotation.Hidden = False
annotation.OpenByDefault = True
annotation.ReadOnly = False
annotation.Rotateable = True
# Add the annotation to a specific page and location within the PDF
pdf.AddTextAnnotation(annotation, 1, 150, 250)
# Save the PDF with annotations
pdf.SaveAs("existing.pdf")from ironpdf import *
# Load an existing PDF
pdf = PdfDocument("existing.pdf")
# Create a TextAnnotation object
annotation = TextAnnotation()
annotation.Title = "This is the title"
annotation.Subject = "This is a subject"
annotation.Contents = "This is the comment content..."
annotation.Icon = TextAnnotation.AnnotationIcon.Help
annotation.Opacity = 0.9
annotation.Printable = False
annotation.Hidden = False
annotation.OpenByDefault = True
annotation.ReadOnly = False
annotation.Rotateable = True
# Add the annotation to a specific page and location within the PDF
pdf.AddTextAnnotation(annotation, 1, 150, 250)
# Save the PDF with annotations
pdf.SaveAs("existing.pdf")添加背景和前景
IronPDF for Python 允许您向 PDF 文档添加背景和前景。 这对于添加水印、创建自定义模板或使 PDF 文档看起来更具视觉吸引力非常有用。 您可以使用图像、颜色或渐变作为背景或前景。
from ironpdf import *
# Instantiate Renderer for PDF creation
renderer = ChromePdfRenderer()
# Render a PDF from a given URL
pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
# Add a background PDF
pdf.AddBackgroundPdf("MyBackground.pdf")
# Add a foreground overlay PDF to the first page
pdf.AddForegroundOverlayPdfToPage(0, "MyForeground.pdf", 0)
# Save the merged PDF with background and foreground
pdf.SaveAs("Complete.pdf")from ironpdf import *
# Instantiate Renderer for PDF creation
renderer = ChromePdfRenderer()
# Render a PDF from a given URL
pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
# Add a background PDF
pdf.AddBackgroundPdf("MyBackground.pdf")
# Add a foreground overlay PDF to the first page
pdf.AddForegroundOverlayPdfToPage(0, "MyForeground.pdf", 0)
# Save the merged PDF with background and foreground
pdf.SaveAs("Complete.pdf")盖章和水印
IronPDF for Python 允许您在 PDF 文档上添加水印和戳记。 这有助于添加版权信息、防止未经授权的复制,或者仅仅是让您的 PDF 文档看起来更专业。 您可以给 PDF 文档添加文字、图片或水印。 您还可以控制图章和水印的大小、位置和不透明度。
在 PDF 文件上添加印章
您可以使用 IronPDF for Python 为 PDF 文档添加图章。 这对于在 PDF 文档中添加徽标、签名或其他识别信息非常有用。 您可以选择印章类型、位置和大小,还可以设置印章的不透明度。
from ironpdf import *
# Define an HTML Stamper to apply an image stamp
stamper = HtmlStamper("<img src='https://ironpdf.com/img/products/ironpdf-logo-text-dotnet.svg'/>")
stamper.HorizontalAlignment = HorizontalAlignment.Center
stamper.VerticalAlignment = VerticalAlignment.Bottom
stamper.IsStampBehindContent = False
stamper.Opacity = 30
# Load existing PDF and apply the stamp
pdf = PdfDocument.FromFile("Sample.pdf")
pdf.ApplyStamp(stamper).SaveAs("stampedimage.pdf")from ironpdf import *
# Define an HTML Stamper to apply an image stamp
stamper = HtmlStamper("<img src='https://ironpdf.com/img/products/ironpdf-logo-text-dotnet.svg'/>")
stamper.HorizontalAlignment = HorizontalAlignment.Center
stamper.VerticalAlignment = VerticalAlignment.Bottom
stamper.IsStampBehindContent = False
stamper.Opacity = 30
# Load existing PDF and apply the stamp
pdf = PdfDocument.FromFile("Sample.pdf")
pdf.ApplyStamp(stamper).SaveAs("stampedimage.pdf")给PDF添加水印
IronPDF for Python 允许您向 PDF 文档添加水印。 这有助于防止未经授权的复制,或者只是让你的 PDF 文档看起来更专业。 您可以选择水印文字、字体、大小和颜色。 您还可以设置水印的不透明度。
from ironpdf import *
# Instantiate the Renderer and create a PdfDocument from a URL
renderer = ChromePdfRenderer()
pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
# Apply a watermark to the PDF
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, VerticalAlignment.Middle, HorizontalAlignment.Center)
# Save the watermarked PDF
pdf.SaveAs("Watermarked.pdf")from ironpdf import *
# Instantiate the Renderer and create a PdfDocument from a URL
renderer = ChromePdfRenderer()
pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
# Apply a watermark to the PDF
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, VerticalAlignment.Middle, HorizontalAlignment.Center)
# Save the watermarked PDF
pdf.SaveAs("Watermarked.pdf")在 PDF 中使用表单
您可以使用 IronPDF for Python 在 PDF 文档中创建和编辑表单。 这对于收集用户数据或增强 PDF 文档的交互性非常有用。您可以添加表单字段,例如文本框、复选框和单选按钮。 您还可以收集用户表单数据。
创建和编辑表单
from ironpdf import *
# HTML content for a form with text inputs, radio buttons, and checkboxes
form_html = """
<html>
<body>
<h2>Editable PDF Form</h2>
<form>
First name: <br> <input type='text' name='firstname' value=''> <br>
Last name: <br> <input type='text' name='lastname' value=''> <br>
<br>
<p>Please specify your gender:</p>
<input type='radio' id='female' name='gender' value= 'Female'>
<label for='female'>Female</label> <br>
<br>
<input type='radio' id='male' name='gender' value='Male'>
<label for='male'>Male</label> <br>
<br>
<input type='radio' id='non-binary/other' name='gender' value='Non-Binary / Other'>
<label for='non-binary/other'>Non-Binary / Other</label>
<br>
<p>Please select all medical conditions that apply:</p>
<input type='checkbox' id='condition1' name='Hypertension' value='Hypertension'>
<label for='condition1'> Hypertension</label><br>
<input type='checkbox' id='condition2' name='Heart Disease' value='Heart Disease'>
<label for='condition2'> Heart Disease</label><br>
<input type='checkbox' id='condition3' name='Stroke' value='Stroke'>
<label for='condition3'> Stroke</label><br>
<input type='checkbox' id='condition4' name='Diabetes' value='Diabetes'>
<label for='condition4'> Diabetes</label><br>
<input type='checkbox' id='condition5' name='Kidney Disease' value='Kidney Disease'>
<label for='condition5'> Kidney Disease</label><br>
</form>
</body>
</html>
"""
# Instantiate Renderer and enable form creation
renderer = ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
# Render the form HTML to PDF and save it
renderer.RenderHtmlAsPdf(form_html).SaveAs("BasicForm.pdf")
# Open the form PDF and update form values
form_document = PdfDocument.FromFile("BasicForm.pdf")
# Update and read the form fields
first_name_field = form_document.Form.FindFormField("firstname")
first_name_field.Value = "Minnie"
print(f"FirstNameField value: {first_name_field.Value}")
last_name_field = form_document.Form.FindFormField("lastname")
last_name_field.Value = "Mouse"
print(f"LastNameField value: {last_name_field.Value}")
# Save the filled form PDF
form_document.SaveAs("FilledForm.pdf")from ironpdf import *
# HTML content for a form with text inputs, radio buttons, and checkboxes
form_html = """
<html>
<body>
<h2>Editable PDF Form</h2>
<form>
First name: <br> <input type='text' name='firstname' value=''> <br>
Last name: <br> <input type='text' name='lastname' value=''> <br>
<br>
<p>Please specify your gender:</p>
<input type='radio' id='female' name='gender' value= 'Female'>
<label for='female'>Female</label> <br>
<br>
<input type='radio' id='male' name='gender' value='Male'>
<label for='male'>Male</label> <br>
<br>
<input type='radio' id='non-binary/other' name='gender' value='Non-Binary / Other'>
<label for='non-binary/other'>Non-Binary / Other</label>
<br>
<p>Please select all medical conditions that apply:</p>
<input type='checkbox' id='condition1' name='Hypertension' value='Hypertension'>
<label for='condition1'> Hypertension</label><br>
<input type='checkbox' id='condition2' name='Heart Disease' value='Heart Disease'>
<label for='condition2'> Heart Disease</label><br>
<input type='checkbox' id='condition3' name='Stroke' value='Stroke'>
<label for='condition3'> Stroke</label><br>
<input type='checkbox' id='condition4' name='Diabetes' value='Diabetes'>
<label for='condition4'> Diabetes</label><br>
<input type='checkbox' id='condition5' name='Kidney Disease' value='Kidney Disease'>
<label for='condition5'> Kidney Disease</label><br>
</form>
</body>
</html>
"""
# Instantiate Renderer and enable form creation
renderer = ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
# Render the form HTML to PDF and save it
renderer.RenderHtmlAsPdf(form_html).SaveAs("BasicForm.pdf")
# Open the form PDF and update form values
form_document = PdfDocument.FromFile("BasicForm.pdf")
# Update and read the form fields
first_name_field = form_document.Form.FindFormField("firstname")
first_name_field.Value = "Minnie"
print(f"FirstNameField value: {first_name_field.Value}")
last_name_field = form_document.Form.FindFormField("lastname")
last_name_field.Value = "Mouse"
print(f"LastNameField value: {last_name_field.Value}")
# Save the filled form PDF
form_document.SaveAs("FilledForm.pdf")结论
IronPDF for Python 是一个功能强大的 Python PDF 库,它使您能够使用 Python 创建、操作和编辑 PDF 文档。 有了这个库,操作 PDF 文档变得异常简单。 它提供了广泛的功能,包括编辑文档结构、操作页面、合并和拆分 PDF、编辑文档属性以及添加和使用 PDF 元数据。
IronPDF for Python 是一款用户友好的软件,可以无缝集成到任何 Python 项目中。 对于任何需要在 Python 中处理 PDF 文档的人来说,它都是一个非常有价值的工具。 IronPDF for Python 的许可证从$799开始。 您可以在IronPDF 网站上找到更多信息。
常见问题解答
如何在Python中编辑PDF文件?
您可以使用IronPDF for Python通过插入签名、添加HTML页脚、嵌入水印和程序化地包含注释来编辑PDF文件。
安装IronPDF for Python涉及哪些步骤?
要安装IronPDF for Python,可以使用pip安装器,在命令行界面中执行pip install ironpdf。
如何使用Python为PDF添加水印?
使用IronPDF for Python,您可以通过访问PDF文档并使用库的方法嵌入水印图像或文本为PDF添加水印。
我可以使用Python将多个PDF文件合并为一个吗?
是的,IronPDF允许您通过加载PDF并使用Merge功能将多个PDF合并为单个文档。
如何在Python中为PDF应用数字签名?
IronPDF支持使用.pfx和.p12证书文件应用数字签名,使您能够加密签署PDF以保证文档完整性。
可以使用IronPDF为PDF添加元数据吗?
是的,您可以通过访问PdfDocument对象的MetaData属性并设置所需字段来添加诸如作者、标题和关键词等元数据。
如何在Python中为PDF添加页眉和页脚?
您可以使用IronPDF为PDF添加文本和HTML页眉和页脚,并可以自定义其内容和外观。
我可以使用哪些方法压缩Python中的PDF文件?
IronPDF允许您通过CompressImages方法压缩PDF,减少图像大小,并可以根据各种质量级别进行配置。
如何在Python中创建交互式PDF表单?
IronPDF支持创建和编辑交互式PDF表单,允许用户填写文本字段、复选框和单选按钮。
使用IronPDF可以添加哪些类型的注释到PDF中?
IronPDF允许您在PDF文档中添加文本注释、评论、链接,并编辑现有注释。









