フッターコンテンツにスキップ
PYTHON用IRONPDFを使用する

PythonでPDFファイルを編集する方法

Iron Software は、Python で PDF 編集タスクを実行する際の容易さを一変させるソリューションであるIronPDF for Python ライブラリを発表しました。 署名の挿入、HTML フッターの追加、透かしの埋め込み、注釈の追加、PDF ファイルの編集などが必要な場合、IronPDF for Python は頼りになるツールです。 このライブラリにより、コードの可読性が維持され、プログラムによる PDF の作成がサポートされ、簡単なデバッグが可能になり、互換性のあるすべてのプラットフォームと環境にシームレスに展開されます。

このチュートリアル記事では、Python コード例と包括的な説明を使用して、これらの広範な機能について詳しく説明します。 このガイドを読み終える頃には、PDF 編集のあらゆるニーズに IronPDF for Python を使用する方法をしっかりと理解できるようになります。

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 ファイルを作成するオプションもあります。 1 つの PDF ファイルから 1 ページまたは複数のページを選択してコピーすることもできます。

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 を 1 つに結合したり、既存の PDF を個別のファイルに分割したりすることが簡単になります。

複数の既存の PDF を 1 つの PDF ドキュメントに結合する

入力 PDF ドキュメントと出力 PDF ドキュメントを指定することで、複数の PDF ドキュメントを 1 つのドキュメントに結合できます。

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 ドキュメントまたはページ番号を指定して、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 を使用すると、 .pfxおよび.p12 X509Certificate2 デジタル証明書を使用して、新規または既存の PDF ファイルにデジタル署名できます。 この方法を使用して PDF に署名すると、ドキュメントへの変更には証明書による検証が必要になり、ドキュメントの整合性が確保されます。

Adobe Reader を使用して署名証明書を無料で生成する方法の詳細については、Adobe の Web サイトを参照してください。

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 ドキュメントに添付ファイルを追加したり、いつでも簡単に削除したりできます。 つまり、IronPDF を使用すると、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")
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 ドキュメントにヘッダーとフッターを簡単に追加できます。 ソフトウェアには、 TextHeaderFooterHtmlHeaderFooterという 2 つの異なるタイプのHeaderFootersが用意されています。 TextHeaderFooter 、テキストのみを含み、"{ページ} / {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  # 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 を使用している場合は、これらのブックマーク(階層的に整理できます)がアプリの左側のサイドバーに表示されます。

Python 用 IronPDF ライブラリを使用すると、ブックマークの操作がさらに簡単になります。 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 のライセンスは$799から始まります。 詳細については、IronPDF の Web サイトをご覧ください。

よくある質問

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ファイルを1つにマージすることは可能ですか?

はい、IronPDFを使用すると、複数のPDFをロードしてMerge関数を利用することで、単一のドキュメントにマージできます。

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は、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。