如何在 Python 中編輯 PDF 文件
Iron Software推出了IronPDF for Python 函式庫,徹底改變了在 Python 中執行 PDF 編輯任務的便利性。 無論您需要插入簽名、新增 HTML 頁腳、嵌入浮水印、新增註解或編輯 PDF 文件, IronPDF for Python 都是您的首選工具。 該庫確保您的程式碼保持可讀性,支援以程式設計方式建立 PDF,方便調試,並可在所有相容的平台和環境中無縫部署。
本文將透過 Python 程式碼範例和全面解釋,深入探討這些豐富的功能。 看完本指南,您將全面了解如何使用IronPDF for Python 來滿足您所有的 PDF 編輯需求。
如何在 Python 中編輯 PDF 文件
- 使用
pip安裝程式安裝 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 文件進行簽署後,對文件的任何修改都需要透過證書進行驗證,從而確保文件的完整性。
您可以在AdAdobe 網站上找到更多關於如何使用 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 專案中。 對於任何需要在 Python 中處理 PDF 文件的人來說,它都是一個非常有價值的工具。 IronPDF for Python 授權以 $799 開頭。 您可以在IronPDF網站上找到更多資訊。
常見問題解答
我如何在 Python 中编辑 PDF 文件?
您可以使用 IronPDF for Python 通過程序插入签名、添加 HTML 頁脚、嵌入水印和包含注释来编辑 PDF 文件。
安装 IronPDF for Python 包括哪些步骤?
要安装 IronPDF for Python,可以在命令行界面中执行 pip install ironpdf 使用 pip 安装程序。
如何使用 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 文檔中添加文本注释、评论、链接和编辑現有注释。










