在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
Iron Software展示了IronPDF for Python 库一种解决方案,彻底改变了在 Python 中执行 PDF 编辑任务的便捷性。 无论您需要插入签名、添加HTML页脚、嵌入水印、包含注释或编辑PDF文件,IronPDF for Python都是您的首选工具。 该库确保您的代码保持可读性,支持以编程方式创建PDF,便于简单调试,并在所有兼容的平台和环境中无缝部署。
本教程文章将通过示例性的 Python 代码和全面的解释来探讨这些广泛的功能。 在本指南结束时,您将深入了解如何使用IronPDF for Python满足所有PDF编辑需求。
使用 pip
安装 Python PDF 库。
为 Python PDF 库应用许可证密钥。
加载 PDF 文档进行编辑。
使用不同的选项,如拆分、复制页面和其他 PDF 操作来编辑 PDF 文档。
SaveAs
函数保存修改后的文件。IronPDF 简化了在特定位置添加页面、提取特定页面或页面范围以及从任何 PDF 中删除页面的过程。 它为您处理所有复杂的流程,使您可以轻松高效地执行这些任务。
您可以通过指定页面内容、大小和位置来向PDF文档添加页面。 在进行所需更改后,您可以使用 SaveAs
函数保存输出的 PDF 文件。
from ironpdf import *
# Set a log path
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All
pdf = PdfDocument("C:\\Users\\Administrator\\Downloads\\Documents\\sample.pdf")
renderer = ChromePdfRenderer()
coverPagePdf = renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>")
pdf.PrependPdf(coverPagePdf)
pdf.SaveAs("report_with_cover.pdf")
您可以通过指定页码和目标,将页面从一个PDF文档复制到另一个现有的PDF文件中。 此外,您还可以选择从复制的PDF页面创建一个新的PDF文件。 也可以从单个 PDF 文件中选择一个或多个页面进行复制。
from ironpdf import *
pdf = PdfDocument("C:\\Users\\Administrator\\Downloads\\Documents\\sample.pdf")
# Copy pages 5 to 7 and save them as a new document.
pdf.CopyPages(2, 4).SaveAs("report_highlight.pdf")
您可以通过指定页码从输入的PDF文件中删除页面。
from ironpdf import *
pdf = PdfDocument("report.pdf")
pdf.RemovePage(pdf.PageCount-1)
pdf.SaveAs("Report-Minus-1.pdf")
IronPDF 的用户友好型 API 使得将多个 PDF 合并为一个或将现有 PDF 拆分为单独文件变得非常简单。
您可以通过指定输入PDF文档和输出PDF文档,将多个PDF文档合并为一个文档。
from ironpdf import *
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>"""
renderer = ChromePdfRenderer()
pdfdoc_a = renderer.RenderHtmlAsPdf(html_a)
pdfdoc_b = renderer.RenderHtmlAsPdf(html_b)
merged = PdfDocument.Merge(pdfdoc_a, pdfdoc_b)
merged.SaveAs("Merged.pdf")
您可以通过指定输入PDF文档和输出PDF文档或页码,将PDF文档拆分为多个文档或从PDF文件中提取特定页面。
from ironpdf import *
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>"""
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf(html)
# take the first page
page1doc = pdf.CopyPage(0)
page1doc.SaveAs("Split1.pdf")
# take pages 2 & 3
page23doc = pdf.CopyPages(1, 2)
page23doc.SaveAs("Split2.pdf")
您可以使用IronPDF for Python添加和使用PDF元数据。 这对添加版权信息、跟踪更改或只是使您的PDF文档更易于搜索可能是有益的。
PDF 元数据是存储在 PDF 文档中的一组数据。 该数据可以包括PDF文档的标题、作者、主题、关键词、创建日期和修改日期。 此外,还可以根据您的要求添加自定义数据。
from ironpdf import *
# Open an Encrypted File, alternatively create a new PDF from Html
pdf = PdfDocument.FromFile("encrypted.pdf", "password")
# Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = Now()
pdf.SaveAs("MetaData-Updated.pdf")
IronPDF允许您使用.pfx
和.p12
X509Certificate2数字证书对新的或现有的PDF文件进行数字签名。 使用此方法签署 PDF 时,对文档的任何修改都需要通过证书验证,以确保文档的完整性。
您可以在Adobe Reader上找到有关免费生成签名证书的更多指南。Adobe 网站.
除了加密签名之外,IronPDF 还支持使用手写签名图像或公司印章图像作为签署文档的替代方式。
from ironpdf import *
# Cryptographically sign an existing PDF in 1 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 signature.
# You may create a .pfx or .p12 PDF signing certificate using Adobe Acrobat Reader.
# Read https://helpx.adobe.com/acrobat/using/digital-ids.html
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. Multiple signing certificates may be used.
doc.Sign(signature)
# Step 5. The PDF is not signed until saved to file, stream or byte array.
doc.SaveAs("signed.pdf")
IronPDF使您可以非常轻松地将附件添加到您的PDF文档中,并在需要时随时删除它们。 这意味着您可以根据需要将额外的文件放入您的PDF中并取出,这一切都可以通过IronPDF实现。
from ironpdf import *
# Instantiate the Renderer and create PdfDocument from HTML
renderer = ChromePdfRenderer()
my_pdf = renderer.RenderHtmlFileAsPdf("my-content.html")
# Open PDF document to be attached
pdf = PdfDocument.FromFile("new_sample.pdf")
# Here we can add an attachment with a name and a byte []
attachment1 = my_pdf.Attachments.AddAttachment("attachment_1", pdf.BinaryData)
# And here is an example of removing an attachment
my_pdf.Attachments.RemoveAttachment(attachment1)
my_pdf.SaveAs("my-content.pdf")
IronPDF具有压缩PDF的功能,以帮助减少其文件大小。一种方法是使用CompressImages
方法减少嵌入PDF文档中的图像大小。
关于图像质量,对于JPEG图像,100%质量几乎不会丢失图像质量,而1%则会产生非常差的质量输出。 一般来说,90%或以上的图像质量被认为是高质量。 中等质量的图像介于80%到90%之间,而低质量的图像范围为70%到80%。 如果低于70%,图像质量会显著下降,但这可以极大地减少PDF文档的整体文件大小。
建议尝试不同的质量百分比,以找到适合您需求的质量与文件大小之间的最佳平衡。 请记住,缩小后质量明显下降的程度可能会因您处理的图像类型而异,因为某些图像可能比其他图像更容易失去清晰度。
from ironpdf import *
pdf = PdfDocument("document.pdf")
# Quality parameter can be 1-100, where 100 is 100% of original quality
pdf.CompressImages(60)
pdf.SaveAs("document_compressed.pdf")
# Second optional parameter can scale down the image resolution according to its visible size in the PDF document. Note that this may cause distortion with some image configurations
pdf.CompressImages(90, True)
pdf.SaveAs("document_scaled_compressed.pdf")
使用 IronPDF 向您的 PDF 文档添加页眉和页脚是非常简单的。 该软件提供两种不同类型的 HeaderFooters
:TextHeaderFooter
和 HtmlHeaderFooter
。 TextHeaderFooter
非常适合仅包含文本的页眉和页脚,并可能需要合并字段,例如“{页码}的{总页数}". 另一方面,HtmlHeaderFooter
是一个更高级的选项,可以处理任何 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
# mergeable fields are
# {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
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
# Use sufficient MarginBottom to ensure that the HtmlFooter does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginBottom = 25 # mm
# Build a header using an image asset
# Note the use of BaseUrl to set a relative path to the assets
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")
# Use sufficient MarginTop to ensure that the HtmlHeader does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginTop = 25 # mm
from ironpdf import *
# Initiate PDF Renderer
renderer = ChromePdfRenderer()
# Add a header to every page easily
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 footer too
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
# Mergeable fields are
# {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
大纲,也称为“书签”,是一种工具,可帮助您快速访问 PDF 文档中的重要页面。 如果您使用 Adobe Acrobat Reader,您可以看到这些书签。(可按层级组织)在应用程序的左侧边栏中。
IronPDF for Python 库使管理书签变得更加容易。 它可以自动导入任何现有PDF文档中的书签。 此外,您可以使用IronPDF添加更多书签、编辑书签或将其分组进行排列。
from ironpdf import *
# Create a new PDF or edit an existing document.
pdf = PdfDocument.FromFile("existing.pdf")
# Add bookmark
pdf.Bookmarks.AddBookMarkAtEnd("Author's Note", 2)
pdf.Bookmarks.AddBookMarkAtEnd("Table of Contents", 3)
# Store new bookmark in a variable to add nested bookmarks to
summaryBookmark = pdf.Bookmarks.AddBookMarkAtEnd("Summary", 17)
# Add a sub-bookmark within the summary
conclusionBookmark = summaryBookmark.Children.AddBookMarkAtStart("Conclusion", 18)
# Add another bookmark to end of highest-level bookmark list
pdf.Bookmarks.AddBookMarkAtEnd("References", 20)
pdf.SaveAs("existing.pdf")
您可以使用IronPDF for Python在PDF文档中添加和编辑注释。 可以使用注释来突出显示文本、添加评论或创建链接。 您还可以编辑现有的注释。
from ironpdf import *
# Load an existing PDF or create a new one
pdf = PdfDocument("existing.pdf")
# Create a TextAnnotation object
annotation = TextAnnotation()
annotation.Title = "This is the major title"
annotation.Subject = "This is a subtitle"
annotation.Contents = "This is the long 'sticky note' 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
pdf.SaveAs("existing.pdf")
IronPDF for Python 允许您为 PDF 文档添加背景和前景。 这对于添加水印、创建自定义模板或只是让您的PDF文档看起来更具视觉吸引力非常有用。 您可以使用图像、颜色或渐变作为背景或前景。
from ironpdf import *
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Render a PDF from a URL
pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
# Add a PDF as background
pdf.AddBackgroundPdf("MyBackground.pdf")
# Add a PDF as foreground overlay to the first page
pdf.AddForegroundOverlayPdfToPage(0, "MyForeground.pdf", 0)
# Save the merged PDF
pdf.SaveAs("Complete.pdf")
IronPDF for Python 允许您给 PDF 文档添加印章和水印。 这对于添加版权信息、防止未经授权的复制或仅仅是让您的PDF文档看起来更专业非常有用。 您可以使用文本、图像或水印为PDF文档加盖印章。 您还可以控制印章和水印的大小、位置和不透明度。
您可以使用IronPDF for Python将印章应用于PDF文档。 这对于在PDF文档中添加徽标、签名或其他识别信息非常有用。 您可以选择印章类型、位置和大小。您还可以设置印章的不透明度。
from ironpdf import *
# Create an HtmlStamper object to stamp an image onto a PDF
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 an existing PDF document and apply the stamp to it
pdf = PdfDocument.FromFile("Sample.pdf")
pdf.ApplyStamp(stamper).SaveAs("stampedimage.pdf")
IronPDF for Python允许您向PDF文档添加水印。 这可以用于防止未经授权的复制,或者只是让您的PDF文档看起来更专业。 您可以选择水印的文本、字体、大小和颜色。 您还可以设置水印的不透明度。
from ironpdf import *
# Instantiate the Renderer and create PdfDocument from URL
renderer = ChromePdfRenderer()
pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
# Apply watermark
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, VerticalAlignment.Middle, HorizontalAlignment.Center)
# Save your new PDF
pdf.SaveAs("Watermarked.pdf")
您可以使用IronPDF for Python在PDF文档中创建和编辑表单。 这对于收集用户数据或仅仅使您的PDF文档更具互动性是很有用的。您可以添加诸如文本框、复选框和单选按钮等表单字段。 您还可以从用户收集表单数据。
from ironpdf import *
# Step 1. Creating a PDF with editable forms from HTML using form and input tags
# Radio Button and Checkbox can also be implemented with input type 'radio' and 'checkbox'
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='Stoke' value='Stoke'>
<label for='condition3'> Stoke</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
renderer = ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
renderer.RenderHtmlAsPdf(form_html).SaveAs("BasicForm.pdf")
# Step 2. Reading and Writing PDF form values.
form_document = PdfDocument.FromFile("BasicForm.pdf")
# Set and read the value of the "firstname" field
first_name_field = form_document.Form.FindFormField("firstname")
first_name_field.Value = "Minnie"
print("FirstNameField value: {}".format(first_name_field.Value))
# Set and read the value of the "lastname" field
last_name_field = form_document.Form.FindFormField("lastname")
last_name_field.Value = "Mouse"
print("LastNameField value: {}".format(last_name_field.Value))
form_document.SaveAs("FilledForm.pdf")
IronPDF for Python 是一个强大的 Python PDF 库,使您能够从 Python 创建、操作和编辑 PDF 文档。 使用此库,操控 PDF 文档变得异常简单。 它提供了广泛的功能,包括编辑文档结构、操作页面、合并和拆分PDF、编辑文档属性以及添加和使用PDF元数据的能力。
IronPDF for Python 用户友好,可以无缝集成到任何 Python 项目中。 它是任何需要在 Python 中处理 PDF 文档的人的宝贵工具。 IronPDF for Python 的许可从 $749 起价。 您可以在以下位置找到更多信息IronPDF 网站.