使用IRONPDF FOR PYTHON

如何在 Python 中編輯 PDF 檔案

已更新 2024年9月28日
分享:

介紹

Iron Software 推出IronPDF for Python 庫,一種解決方案,徹底改變了在 Python 中執行 PDF 編輯任務的便捷性。 無論您需要插入簽名、添加 HTML 頁腳、嵌入浮水印、包含註解或編輯 PDF 文件,IronPDF for Python 是您的理想工具。 該程式庫確保您的代碼保持可讀性,支持以程式方式創建PDF,簡化調試過程,並可在所有兼容的平台和環境中無縫部署。

這篇教學文章將通過說明性的 Python 代碼範例和全面的解釋來探討這些廣泛的功能。 完成本指南後,您將對如何使用 IronPDF for Python 滿足所有 PDF 編輯需求有深入了解。

如何在 Python 中編輯 PDF 檔案

  1. 使用 pip 安裝 Python PDF 庫。

  2. 套用 Python PDF Library 的授權金鑰。

  3. 加載 PDF 文件以進行編輯。

  4. 使用不同的選項編輯PDF文件,例如拆分、複製頁面和其他PDF操作。

  5. 使用 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")
PYTHON

複製頁面

您可以通過指定頁碼和目標,將頁面從一個 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")
PYTHON

刪除頁面

您可以透過指定頁碼來從輸入的 PDF 檔案中刪除頁面。

from ironpdf import *

pdf = PdfDocument("report.pdf")
pdf.RemovePage(pdf.PageCount-1)
pdf.SaveAs("Report-Minus-1.pdf")
PYTHON

合併和拆分PDFs

IronPDF 的使用者友善 API 令合併多個 PDF 為一個或將現有的 PDF 分解為單獨檔案變得簡單。

將多個現有的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")
PYTHON

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

編輯文件屬性

添加和使用 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")
PYTHON

數位簽名

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

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

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

編輯PDF內容

添加頁眉和頁腳

使用 IronPDF 為您的 PDF 文件添加頁眉和頁腳非常簡單。 該軟體提供兩種不同類型的 HeaderFootersTextHeaderFooterHtmlHeaderFooterTextHeaderFooter 非常適合只包含文字且可能需要包含合併欄位的頁首和頁尾,例如 "{頁面}的{總頁數}"." 另一方面,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
# 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
PYTHON

文本標頭和頁尾

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

大綱和書籤

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

添加和編輯註釋

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

添加背景和前景

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

學印和浮水印

IronPDF for Python 允許您對 PDF 文件進行蓋章和加水印。 這有助於添加版權資訊、防止未授權複製,或僅僅是讓您的 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")
PYTHON

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

在 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.GetFieldByName("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.GetFieldByName("lastname")
last_name_field.Value = "Mouse"
print("LastNameField value: {}".format(last_name_field.Value))

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 的授權價格從 $749 開始。 您可以在以下位置找到更多資訊IronPDF網站.

< 上一頁
如何在 Python 中生成 PDF 表單
下一個 >
如何在 Python 中從 PDF 提取特定文本

準備開始了嗎? 版本: 2024.9 剛剛發布

免費 pip 安裝 查看許可證 >