Przejdź do treści stopki
KORZYSTANIE Z IRONPDF FOR PYTHON

Jak edytować plik PDF w Python

Firma Iron Software przedstawia bibliotekę IronPDF for Python — rozwiązanie, które rewolucjonizuje łatwość wykonywania zadań związanych z edycją plików PDF w języku Python. Niezależnie od tego, czy chcesz wstawiać podpisy, dodawać stopki HTML, osadzać znaki wodne, dodawać adnotacje czy edytować pliki PDF, IronPDF for Python jest narzędziem, którego potrzebujesz. Biblioteka zapewnia czytelność kodu, umożliwia programowe tworzenie plików PDF, ułatwia proste debugowanie oraz zapewnia płynne wdrażanie na wszystkich kompatybilnych platformach i srodowiskach.

W tym artykule instruktażowym omówimy te rozbudowane funkcje, posługując się ilustracyjnymi przykładami kodu w języku Python oraz wyczerpującymi objaśnieniami. Po przeczytaniu tego przewodnika będziesz dobrze rozumieć, jak korzystać z IronPDF for Python do wszystkich swoich potrzeb związanych z edycją plików PDF.

Jak edytować pliki PDF w języku Python

  1. Zainstaluj bibliotekę Python PDF Library za pomocą instalatora pip.
  2. Zastosuj klucz licencyjny dla biblioteki Python PDF.
  3. Załaduj dokument PDF do edycji.
  4. Edytuj dokument PDF, korzystając z różnych opcji, takich jak Podziel, Kopiuj strony i inne operacje na plikach PDF.
  5. Zapisz zmodyfikowany plik za pomocą funkcji SaveAs.

Edytuj strukturę dokumentu

Manipulowanie stronami

IronPDF upraszcza proces dodawania stron w określonych miejscach, wyodrębniania konkretnych stron lub zakresu stron oraz usuwania stron z dowolnego pliku PDF. Obsługuje za Ciebie wszystkie złożone procesy, ułatwiając wydajne wykonywanie tych zadań.

Dodaj strony

Można dodawać strony do dokumentów PDF, określając zawartość strony, rozmiar i położenie. Po wprowadzeniu pożądanych zmian można zapisać plik PDF za pomocą funkcji SaveAs.

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

Skopiuj strony

Można kopiować strony z jednego dokumentu PDF do innego istniejącego pliku PDF, określając numer strony i miejsce docelowe. Dodatkowo masz możliwość utworzenia nowego pliku PDF na podstawie skopiowanych stron PDF. Możliwe jest również wybranie jednej lub wielu stron z pojedynczego pliku PDF do skopiowania.

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

Usuń strony

Możesz usunąć strony z pliku PDF, podając numer strony.

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

Łączenie i dzielenie plików PDF

Przyjazny dla użytkownika interfejs API IronPDF ułatwia łączenie wielu plików PDF w jeden lub dzielenie istniejącego pliku PDF na osobne pliki.

Połącz wiele istniejących plików PDF w jeden dokument PDF

Można połączyć wiele dokumentów PDF w jeden dokument, określając dokumenty PDF wejściowe i wyjściowe.

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

Dzielenie pliku PDF i wyodrębnianie stron

Można podzielić dokument PDF na wiele dokumentów lub wyodrębnić określone strony z plików PDF, określając dokument PDF wejściowy oraz dokumenty PDF wyjściowe lub numery stron.

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

Edytuj właściwości dokumentu

Dodawanie i używanie metadanych PDF

Za pomocą IronPDF for Python można dodawać i wykorzystywać metadane plików PDF. Może to być przydatne do dodawania informacji o prawach autorskich, śledzenia zmian lub po prostu ułatwienia wyszukiwania w dokumentach PDF.

Metadane PDF to zbiór danych przechowywanych w dokumencie PDF. Dane te mogą obejmować tytuł, autora, temat, słowa kluczowe, datę utworzenia i datę modyfikacji dokumentu PDF. Dodatkowo może zawierać dane niestandardowe, które dodasz zgodnie ze swoimi wymaganiami.

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

Podpisy cyfrowe

IronPDF umożliwia cyfrowe podpisywanie nowych lub istniejących plików PDF przy użyciu certyfikatów cyfrowych .pfx i .p12 X509Certificate2. Gdy plik PDF zostanie podpisany tą metodą, wszelkie modyfikacje dokumentu będą wymagały weryfikacji za pomocą certyfikatu, co zapewni integralność dokumentu.

Więcej wskazówek dotyczących bezpłatnego generowania certyfikatu podpisu za pomocą programu Adobe Reader można znaleźć na stronie internetowej firmy Adobe.

Oprócz podpisu kryptograficznego IronPDF obsługuje również wykorzystanie obrazu podpisu odręcznego lub obrazu pieczęci firmowej jako alternatywnego sposobu podpisywania dokumentu.

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

Załączniki w formacie PDF

IronPDF znacznie ułatwia dodawanie załączników do dokumentów PDF oraz usuwanie ich w dowolnym momencie. Oznacza to, że za pomocą IronPDF możesz dodawać dodatkowe pliki do swoich plików PDF i usuwać je w razie potrzeby.

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

Kompresja plików PDF

IronPDF posiada funkcję kompresji plików PDF, która pomaga zmniejszyć ich rozmiar. Jedną z metod jest zmniejszenie rozmiaru obrazów osadzonych w dokumencie PDF przy użyciu metody CompressImages.

Jeśli chodzi o jakość obrazu, w przypadku obrazów JPEG jakość 100% zapewnia niemal zerową utratę jakości obrazu, podczas gdy 1% daje bardzo słabą jakość wyjściową. Ogólnie rzecz biorąc, jakość obrazu na poziomie 90% lub wyższym jest uważana za wysoką. Obraz o średniej jakości mieści się w przedziale od 80% do 90%, a obraz o niskiej jakości – od 70% do 80%. Jeśli wartość spadnie poniżej 70%, jakość obrazu znacznie się pogorszy, ale może to pomóc w znacznym zmniejszeniu ogólnego rozmiaru pliku PDF.

Zaleca się wypróbowanie różnych poziomów jakości, aby znaleźć odpowiednią równowagę między jakością a rozmiarem pliku, która odpowiada Twoim potrzebom. Należy pamiętać, że zauważalna utrata jakości po zmniejszeniu może się różnić w zależności od typu obrazu, ponieważ niektóre obrazy mogą stracić na wyrazistości bardziej niż inne.

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

Edycja treści plików PDF

Dodaj nagłówki i stopki

Dodawanie nagłówków i stopek do dokumentów PDF jest proste dzięki IronPDF. Oprogramowanie udostępnia dwa odrębne typy HeaderFooters: TextHeaderFooter oraz HtmlHeaderFooter. TextHeaderFooter idealnie nadaje się do nagłówków i stopek, które zawierają wyłącznie tekst i mogą wymagać wstawienia pól scalania, takich jak "{page} z {total-pages}". Z drugiej strony HtmlHeaderFooter jest bardziej zaawansowaną opcją, która może obsługiwać dowolną zawartość HTML i formatować ją w przejrzysty sposób, dzięki czemu nadaje się do bardziej złożonych nagłówków i stopek.

Nagłówek i stopka HTML

Dzięki IronPDF for Python możesz użyć funkcji HtmlHeaderFooter do tworzenia nagłówków lub stopek HTML dla dokumentu PDF na podstawie kodu HTML. Oznacza to, że możesz zaprojektować nagłówek lub stopkę przy użyciu HTML, a IronPDF for Python idealnie przekonwertuje je do formatu PDF, zapewniając, że każdy szczegół będzie dokładnie taki, jak powinien. Jeśli więc masz projekt HTML nagłówka lub stopki, IronPDF for Python może precyzyjnie zastosować go w Twoim dokumencie 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

Nagłówek i stopka tekstu

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

Zarys i zakładki

Spis treści, znany również jako "zakładka", to narzędzie, które pomaga szybko przejść do ważnych stron w dokumencie PDF. Jeśli korzystasz z programu Adobe Acrobat Reader, możesz zobaczyć te zakładki (które można uporządkować hierarchicznie) na lewym pasku bocznym aplikacji.

Biblioteka IronPDF for Python jeszcze bardziej ułatwia pracę z zakładkami. Może automatycznie pobrać wszelkie istniejące zakładki z dokumentów PDF. Plus, za pomocą IronPDF można dodawać kolejne zakładki, edytować je lub porządkować w grupy.

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

Dodawanie i edycja adnotacji

Za pomocą IronPDF for Python można dodawać i edytować adnotacje w dokumentach PDF. Adnotacje mogą służyć do wyróżniania tekstu, dodawania komentarzy lub tworzenia linków. Możesz również edytować istniejące adnotacje.

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

Dodaj tło i pierwszy plan

IronPDF for Python pozwala dodawać tła i elementy pierwszego planu do dokumentów PDF. Może to być przydatne do dodawania znaków wodnych, tworzenia niestandardowych szablonów lub po prostu do poprawy wyglądu dokumentów PDF. Można używać obrazów, kolorów lub gradientów jako tła lub pierwszego planu.

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

Stemplowanie i znakowanie wodne

IronPDF for Python umożliwia umieszczanie pieczątek i znaków wodnych w dokumentach PDF. Może to być przydatne do dodawania informacji o prawach autorskich, zapobiegania nieautoryzowanemu kopiowaniu lub po prostu nadania dokumentom PDF bardziej profesjonalnego wyglądu. Możesz opatrzyć dokumenty PDF tekstem, obrazami lub znakami wodnymi. Można również kontrolować rozmiar, położenie i krycie stempli oraz znaków wodnych.

Zastosuj stempel na pliku PDF

Za pomocą IronPDF for Python można umieścić stempel na dokumencie PDF. Może to być przydatne do dodania logo, podpisu lub innych informacji identyfikacyjnych do dokumentu PDF. Możesz wybrać typ, położenie i rozmiar stempla. Możesz również ustawić jego przezroczystość.

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

Dodaj znak wodny do pliku PDF

IronPDF for Python umożliwia dodawanie znaku wodnego do dokumentu PDF. Może to być przydatne w zapobieganiu nieautoryzowanemu kopiowaniu lub po prostu sprawić, że dokumenty PDF będą wyglądały bardziej profesjonalnie. Możesz wybrać tekst, czcionkę, rozmiar i kolor znaku wodnego. Można również ustawić krycie znaku wodnego.

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

Korzystanie z formularzy w plikach PDF

Za pomocą IronPDF for Python można tworzyć i edytować formularze w dokumentach PDF. Może to być przydatne do zbierania danych od użytkowników lub po prostu do uczynienia dokumentów PDF bardziej interaktywnymi. Można dodawać pola formularza, takie jak pola tekstowe, pola wyboru i przyciski opcji. Można również zbierać dane z formularzy od użytkowników.

Tworzenie i edycja formularzy

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

Wnioski

IronPDF for Python to potężna biblioteka PDF dla języka Python, która umożliwia tworzenie, manipulowanie i edytowanie dokumentów PDF z poziomu języka Python. Dzięki tej bibliotece manipulowanie dokumentami PDF stało się niezwykle łatwe. Oferuje szeroki zakres funkcji, w tym możliwość edycji struktury dokumentu, manipulowania stronami, łączenia i dzielenia plików PDF, edycji właściwości dokumentu oraz dodawania i wykorzystywania metadanych PDF.

IronPDF for Python jest przyjazny dla użytkownika i można go płynnie zintegrować z dowolnym projektem w języku Python. Jest to cenne narzędzie dla każdego, kto musi pracować z dokumentami PDF w języku Python. Cena licencji IronPDF for Python zaczyna się od $799. Więcej informacji można znaleźć na stronie internetowej IronPDF.

Często Zadawane Pytania

Jak edytować pliki PDF w języku Python?

Możesz użyć IronPDF for Python do edycji plików PDF poprzez programowe wstawianie podpisów, dodawanie stopek HTML, osadzanie znaków wodnych oraz dodawanie adnotacji.

Jakie kroki należy wykonać, aby zainstalować IronPDF for Python?

Aby zainstalować IronPDF for Python, można użyć instalatora pip, wykonując polecenie pip install ironpdf w interfejsie wiersza poleceń.

Jak dodać znak wodny do pliku PDF za pomocą języka Python?

Dzięki IronPDF for Python możesz dodawać znaki wodne do plików PDF, uzyskując dostęp do dokumentu PDF i używając metod biblioteki do osadzania obrazów lub tekstu znaku wodnego.

Czy mogę połączyć wiele plików PDF w jeden za pomocą języka Python?

Tak, IronPDF umożliwia scalanie wielu plików PDF w jeden dokument poprzez załadowanie plików PDF i skorzystanie z funkcji scalania.

Jak mogę zastosować podpis cyfrowy do pliku PDF w języku Python?

IronPDF obsługuje stosowanie podpisów cyfrowych przy użyciu plików certyfikatów .pfx i .p12, umożliwiając kryptograficzne podpisywanie plików PDF w celu zapewnienia integralności dokumentów.

Czy za pomocą IronPDF można dodać metadane do pliku PDF?

Tak, można dodać metadane, takie jak autor, tytuł i słowa kluczowe, uzyskując dostęp do właściwości MetaData obiektu PdfDocument i ustawiając żądane pola.

Jak dodać nagłówki i stopki do pliku PDF w języku Python?

Za pomocą IronPDF można dodawać nagłówki i stopki tekstowe oraz HTML do plików PDF, z opcjami dostosowania ich treści i wyglądu.

Jakie metody mogę wykorzystać do kompresji plików PDF w języku Python?

IronPDF umożliwia kompresję plików PDF za pomocą metody CompressImages, która zmniejsza rozmiar obrazów i może być skonfigurowana dla różnych poziomów jakości.

Jak mogę tworzyć interaktywne formularze PDF w języku Python?

IronPDF umożliwia tworzenie i edycję interaktywnych formularzy PDF, pozwalając użytkownikom na wypełnianie pól tekstowych, zaznaczanie pól wyboru i przycisków opcji.

Jakie rodzaje adnotacji można dodawać do plików PDF za pomocą IronPDF?

IronPDF umożliwia dodawanie adnotacji tekstowych, komentarzy i linków oraz edycję istniejących adnotacji w dokumentach PDF.

Curtis Chau
Autor tekstów technicznych

Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podrę...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie