跳至頁尾內容
USING IRONPDF FOR PYTHON

如何在 Python 中編輯 PDF 文件

Iron Software推出IronPDF for Python程式庫,這是一個可以改變PDF編輯任務在Python中執行方式的解決方案。 無論您需要插入簽名、新增HTML頁腳、嵌入浮水印、包含註釋或編輯PDF文件,IronPDF for Python都是您不可或缺的工具。 該程式庫確保您的程式碼保持可讀,支持以編程方式建立PDF,促進簡易偵錯,並能無縫部署在所有相容的平台和環境中。

本教程文章將通過具體的Python程式碼範例和全面的解釋來探討這些豐富的功能。 在完成本指南後,您將對如何使用IronPDF for Python來滿足您的所有PDF編輯需求有一個堅實的理解。

如何在Python中編輯PDF文件

  1. 使用pip安裝程式安裝Python PDF程式庫。
  2. 為Python PDF程式庫應用授權金鑰。
  3. 載入需要編輯的PDF文件。
  4. 使用分割、複製頁面和其他PDF操作選項來編輯PDF文件。
  5. 使用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")
PYTHON

複製頁面

您可以透過指定頁碼和目的地,將一個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")
PYTHON

刪除頁面

您可以透過指定頁碼,從輸入的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")
PYTHON

合併和分割PDF

IronPDF的使用者友好API使得將多個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")
PYTHON

分割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")
PYTHON

編輯文件屬性

新增和使用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")
PYTHON

數位簽名

IronPDF允許您使用.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")
PYTHON

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")
PYTHON

壓縮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")
PYTHON

編輯PDF內容

新增頁眉和頁腳

使用IronPDF可以輕鬆地將頁眉和頁腳新增到您的PDF文件中。 該軟體提供兩種不同的HtmlHeaderFooterTextHeaderFooter非常適合僅包含文字的頁眉和頁腳,可能需要合併字段如"{page} of {total-pages}"。 另一方面,HtmlHeaderFooter是一個更進階的選項,可以處理任何HTML內容並能整齊地格式化,這使得它更適合於更複雜的頁眉和頁腳。

HTML頁眉和頁腳

使用IronPDF for Python,您可以利用HtmlHeaderFooter功能從HTML建立HTML頁眉或頁腳以應用於您的PDF文件。 這意味著您可以使用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  # mm
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  # mm
PYTHON

文字頁眉和頁腳

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 footer
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 footer
PYTHON

大綱和書籤

大綱,也被稱為"書籤",是一種幫助您快速跳轉到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")
PYTHON

新增和編輯註釋

您可以使用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")
PYTHON

新增背景和前景

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")
PYTHON

蓋章和浮水印

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")
PYTHON

為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")
PYTHON

在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")
PYTHON

結論

IronPDF for Python是一個強大的Python PDF程式庫,使您可以從Python建立、操作和編輯PDF文件。 使用這個程式庫,操作PDF文件已變得極其簡單。 它提供廣泛的功能,包括編輯文件結構、操作頁面、合併和分割PDF、編輯文件屬性,以及新增和使用PDF元資料。

IronPDF for Python使用者友好,並可無縫地整合到任何Python專案中。 對於任何需要在Python中處理PDF文件的人來說,這是一個有價值的工具。 IronPDF for Python的授權起步價格為$999。 您可以在IronPDF網站上找到更多資訊。

常見問題

我如何在Python中編輯PDF文件?

您可以使用IronPDF for Python來編輯PDF文件,通過程式碼插入簽名、新增HTML頁腳、嵌入水印和包含註釋。

安裝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文件中新增文字註釋、評論、連結並編輯現有的註釋。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話