Jak edytować pliki PDF w C#
Iron Software uprościło różne funkcje edycji PDF w łatwe do zrozumienia metody w bibliotece IronPDF. Niezależnie czy dodajemy podpisy, dodajemy stopki HTML, stemplujemy znaki wodne, czy dodajemy komentarze. IronPDF jest narzędziem dla Ciebie, pozwalającym na czytelny kod, programistyczne generowanie PDF, łatwe debugowanie i płynne wdrażanie do dowolnego obsługiwanego środowiska lub platformy.
IronPDF posiada liczne funkcje do edytowania PDF. W tym artykułe opiszemy niektóre z głównych funkcji, dostarczając przykłady kodu i wyjaśnienia.
Dzięki temu artykułowi zrozumiesz, jak używać IronPDF do edytowania swoich PDF-ów w C#.
Szybki start: Edytuj swoje pliki PDF w kilka sekundBez wysiłku edytuj dokumenty PDF w C# za pomocą IronPDF. Ten szybki przewodnik pokazuje, jak dodać stempel tekstowy do istniejącego pliku PDF. Zaledwie kilka linii kodu pozwala na modyfikację PDF i natychmiastowe zapisanie zmian. Idealne dla deweloperów potrzebujących szybkiego i wydajnego rozwiązania do edytowania PDF.
-
1Zainstaluj IronPDF z NuGet Package Manager
-
2Skopiuj i uruchom ten fragment kodu.
var pdf = IronPdf.PdfDocument.FromFile("example.pdf"); pdf.ApplyStamp(new IronPdf.Editing.TextStamper("Confidential")); pdf.SaveAs("edited_example.pdf");Dim pdf = IronPdf.PdfDocument.FromFile("example.pdf") pdf.ApplyStamp(New IronPdf.Editing.TextStamper("Confidential")) pdf.SaveAs("edited_example.pdf")Dim pdf = IronPdf.PdfDocument.FromFile("example.pdf") pdf.ApplyStamp(New IronPdf.Editing.TextStamper("Confidential")) pdf.SaveAs("edited_example.pdf") -
3Wdrożenie do testowania w środowisku produkcyjnym
Rozpocznij korzystanie z IronPDF w swoim projekcie już dziś z darmową wersją próbną
- Edytuj strukturę dokumentu
- Edytuj właściwości dokumentu
- Ulepsz projekt PDF
Edytuj strukturę dokumentu
Dostęp do obiektu DOM PDF
Manipulacja i dostęp do obiektów PDF jest szybki i prosty. IronPDF upraszcza sposób interakcji programistów z obiektami DOM, czyniąc je znanymi pod kątem manipulacji @DOM stronami sieciowymi, umożliwiając programistom dostęp do różnych elementów, takich jak tekst, i manipulowanie nimi programistycznie.
using IronPdf;
using System.Linq;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Create a PDF from a URL
PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");
// Access DOM Objects
var objects = pdf.Pages.First().ObjectModel;using IronPdf;
using System.Linq;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Create a PDF from a URL
PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");
// Access DOM Objects
var objects = pdf.Pages.First().ObjectModel;Imports IronPdf
Imports System.Linq
' Instantiate Renderer
Private renderer As New ChromePdfRenderer()
' Create a PDF from a URL
Private pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com/")
' Access DOM Objects
Private objects = pdf.Pages.First().ObjectModelImports IronPdf
Imports System.Linq
' Instantiate Renderer
Private renderer As New ChromePdfRenderer()
' Create a PDF from a URL
Private pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com/")
' Access DOM Objects
Private objects = pdf.Pages.First().ObjectModelPo bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Praca z warstwami PDF
Warstwowe PDF-y (plany CAD, rysunki inżynieryjne i eksport map) zachowują swoją zawartość w nazwanych Grupach Zawartości Opcjonalnej. IronPDF udostępnia je przez PdfDocument.Layers, dzięki czemu można wyliczać warstwy, znaleźć jedną po nazwie i wydobyć tekst przypisany do niej.
using IronPdf;
using IronSoftware;
using System;
// Load a layered PDF, such as a CAD plan, engineering drawing, or map export
using PdfDocument pdf = new PdfDocument("blueprint.pdf");
// Enumerate every Optional Content Group (OCG) layer in the document
Console.WriteLine($"Document has {pdf.Layers.Count} layers");
foreach (PdfLayer layer in pdf.Layers)
{
Console.WriteLine($" {layer.Id}: \"{layer.Name}\" visible={layer.IsVisible} parent={layer.ParentId}");
}
// Look a layer up by name (case-sensitive) and extract just its text
PdfLayer titleBlock = pdf.Layers.FindByName("Title Block");
if (titleBlock != null)
{
string headerText = pdf.ExtractTextFromLayer(titleBlock.Id);
Console.WriteLine(headerText);
}using IronPdf;
using IronSoftware;
using System;
// Load a layered PDF, such as a CAD plan, engineering drawing, or map export
using PdfDocument pdf = new PdfDocument("blueprint.pdf");
// Enumerate every Optional Content Group (OCG) layer in the document
Console.WriteLine($"Document has {pdf.Layers.Count} layers");
foreach (PdfLayer layer in pdf.Layers)
{
Console.WriteLine($" {layer.Id}: \"{layer.Name}\" visible={layer.IsVisible} parent={layer.ParentId}");
}
// Look a layer up by name (case-sensitive) and extract just its text
PdfLayer titleBlock = pdf.Layers.FindByName("Title Block");
if (titleBlock != null)
{
string headerText = pdf.ExtractTextFromLayer(titleBlock.Id);
Console.WriteLine(headerText);
}Imports IronPdf
Imports IronSoftware
Imports System
' Load a layered PDF, such as a CAD plan, engineering drawing, or map export
Using pdf As New PdfDocument("blueprint.pdf")
' Enumerate every Optional Content Group (OCG) layer in the document
Console.WriteLine($"Document has {pdf.Layers.Count} layers")
For Each layer As PdfLayer In pdf.Layers
Console.WriteLine($" {layer.Id}: ""{layer.Name}"" visible={layer.IsVisible} parent={layer.ParentId}")
Next
' Look a layer up by name (case-sensitive) and extract just its text
Dim titleBlock As PdfLayer = pdf.Layers.FindByName("Title Block")
If titleBlock IsNot Nothing Then
Dim headerText As String = pdf.ExtractTextFromLayer(titleBlock.Id)
Console.WriteLine(headerText)
End If
End UsingImports IronPdf
Imports IronSoftware
Imports System
' Load a layered PDF, such as a CAD plan, engineering drawing, or map export
Using pdf As New PdfDocument("blueprint.pdf")
' Enumerate every Optional Content Group (OCG) layer in the document
Console.WriteLine($"Document has {pdf.Layers.Count} layers")
For Each layer As PdfLayer In pdf.Layers
Console.WriteLine($" {layer.Id}: ""{layer.Name}"" visible={layer.IsVisible} parent={layer.ParentId}")
Next
' Look a layer up by name (case-sensitive) and extract just its text
Dim titleBlock As PdfLayer = pdf.Layers.FindByName("Title Block")
If titleBlock IsNot Nothing Then
Dim headerText As String = pdf.ExtractTextFromLayer(titleBlock.Id)
Console.WriteLine(headerText)
End If
End UsingPo bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Zapisz i eksportuj dokumenty
Aby zapisać i eksportować dokumenty, IronPDF pozwala użytkownikom szybko zapisać zmieniony dokument PdfDocument.SaveAs na dysku, jednocześnie umożliwiając eksport do innych formatów, takich jak dane binarne i strumienie w pamięci.
Po bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Załaduj PDF-y z pamięci
IronPDF idealnie integruje się z istniejącymi aplikacjami C# .NET; możemy wczytywać i tworzyć pliki PDF z MemoryStream poprzez obiekt MemoryStream.
using IronPdf;
using System.IO;
// Read PDF file as stream
var fileByte = File.ReadAllBytes("sample.pdf");
// Instantiate PDF object from stream
PdfDocument pdf = new PdfDocument(fileByte);using IronPdf;
using System.IO;
// Read PDF file as stream
var fileByte = File.ReadAllBytes("sample.pdf");
// Instantiate PDF object from stream
PdfDocument pdf = new PdfDocument(fileByte);Imports IronPdf
Imports System.IO
' Read PDF file as stream
Private fileByte = File.ReadAllBytes("sample.pdf")
' Instantiate PDF object from stream
Private pdf As New PdfDocument(fileByte)Imports IronPdf
Imports System.IO
' Read PDF file as stream
Private fileByte = File.ReadAllBytes("sample.pdf")
' Instantiate PDF object from stream
Private pdf As New PdfDocument(fileByte)Po bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Eksportuj PDF-y do pamięci
Podobnie możemy eksportować PDF-y do MemoryStream w C# .NET poprzez obiekt MemoryStream.
using IronPdf;
using System.IO;
var renderer = new ChromePdfRenderer();
// Convert the URL into PDF
PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");
// Export PDF as Stream
MemoryStream pdfAsStream = pdf.Stream;
// Export PDF as Byte Array
byte[] pdfAsByte = pdf.BinaryData;using IronPdf;
using System.IO;
var renderer = new ChromePdfRenderer();
// Convert the URL into PDF
PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");
// Export PDF as Stream
MemoryStream pdfAsStream = pdf.Stream;
// Export PDF as Byte Array
byte[] pdfAsByte = pdf.BinaryData;Imports IronPdf
Imports System.IO
Private renderer = New ChromePdfRenderer()
' Convert the URL into PDF
Private pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com/")
' Export PDF as Stream
Private pdfAsStream As MemoryStream = pdf.Stream
' Export PDF as Byte Array
Private pdfAsByte() As Byte = pdf.BinaryDataImports IronPdf
Imports System.IO
Private renderer = New ChromePdfRenderer()
' Convert the URL into PDF
Private pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com/")
' Export PDF as Stream
Private pdfAsStream As MemoryStream = pdf.Stream
' Export PDF as Byte Array
Private pdfAsByte() As Byte = pdf.BinaryDataPo bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Edytuj tekst w dokumencie
Parse PDFs in C#
Wyciąganie tekstu z PDF-a jest szybkie i łatwe przy użyciu IronPDF. Po prostu użyj metody ExtractAllText, aby pobrać cały tekst z każdej strony, co umożliwia łatwy dostęp i wykorzystanie zawartości dokumentu. Ta potężna funkcja zwiększa wydajność i upraszcza przepływ pracy!
using IronPdf;
// Select the desired PDF File
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");
// Extract all text from an pdf
string allText = pdf.ExtractAllText();
// Extract all text from page 1
string page1Text = pdf.ExtractTextFromPage(0);using IronPdf;
// Select the desired PDF File
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");
// Extract all text from an pdf
string allText = pdf.ExtractAllText();
// Extract all text from page 1
string page1Text = pdf.ExtractTextFromPage(0);Imports IronPdf
' Select the desired PDF File
Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")
' Extract all text from an pdf
Private allText As String = pdf.ExtractAllText()
' Extract all text from page 1
Private page1Text As String = pdf.ExtractTextFromPage(0)Imports IronPdf
' Select the desired PDF File
Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")
' Extract all text from an pdf
Private allText As String = pdf.ExtractAllText()
' Extract all text from page 1
Private page1Text As String = pdf.ExtractTextFromPage(0)Po bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Wyodrębnij tekst i obrazy
Z IronPDF nie jesteś ograniczony tylko do wyodrębniania tekstu; jest również niesamowicie łatwe wydobywanie obrazów z twoich PDF-ów! Dzięki funkcji ExtractAllImages możesz szybko uchwycić wszystkie potrzebne wizualizacje.
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");
// Extract images
var images = pdf.ExtractAllImages();
for(int i = 0; i < images.Count; i++)
{
// Export the extracted images
images[i].SaveAs($"images/image{i}.png");
}using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");
// Extract images
var images = pdf.ExtractAllImages();
for(int i = 0; i < images.Count; i++)
{
// Export the extracted images
images[i].SaveAs($"images/image{i}.png");
}Imports IronPdf
Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")
' Extract images
Private images = pdf.ExtractAllImages()
For i As Integer = 0 To images.Count - 1
' Export the extracted images
images(i).SaveAs($"images/image{i}.png")
Next iImports IronPdf
Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")
' Extract images
Private images = pdf.ExtractAllImages()
For i As Integer = 0 To images.Count - 1
' Export the extracted images
images(i).SaveAs($"images/image{i}.png")
Next iPo bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Zaczerniaj teksty i obszary
W sytuacjach, gdzie musimy chronić poufne informacje, redagując je, mamy potężne narzędzie na wyciągnięcie ręki: RedactTextOnAllPages. Dzięki tej funkcji możemy łatwo zidentyfikować i ukryć każde wystąpienie określonego słowa kluczowego w całym PDF-ie. To skuteczny sposób na zapewnienie, że poufne szczegóły pozostaną chronione, a jednocześnie, że możemy udostępnić dokument z pewnością.
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("novel.pdf");
// Redact 'Alaric' phrase from all pages
pdf.RedactTextOnAllPages("Alaric");
pdf.SaveAs("redacted.pdf");using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("novel.pdf");
// Redact 'Alaric' phrase from all pages
pdf.RedactTextOnAllPages("Alaric");
pdf.SaveAs("redacted.pdf");Imports IronPdf
Private pdf As PdfDocument = PdfDocument.FromFile("novel.pdf")
' Redact 'Alaric' phrase from all pages
pdf.RedactTextOnAllPages("Alaric")
pdf.SaveAs("redacted.pdf")Imports IronPdf
Private pdf As PdfDocument = PdfDocument.FromFile("novel.pdf")
' Redact 'Alaric' phrase from all pages
pdf.RedactTextOnAllPages("Alaric")
pdf.SaveAs("redacted.pdf")Po bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Zamień tekst w PDF
Aby poprawić dokumenty PDF za pomocą IronPDF, można łatwo zastąpić tekst w całym pliku. Używając funkcji ReplaceTextOnAllPages, można podać oldText, który należy zastąpić, oraz newText, który będzie jego zamiennikiem. Ta metoda efektywnie aktualizuje wszystkie przypadki oldText w dokumencie, zapewniając spójny i profesjonalny wygląd.
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>.NET6</h1>");
string oldText = ".NET6";
string newText = ".NET7";
// Replace text on all pages
pdf.ReplaceTextOnAllPages(oldText, newText);
pdf.SaveAs("replaceText.pdf");using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>.NET6</h1>");
string oldText = ".NET6";
string newText = ".NET7";
// Replace text on all pages
pdf.ReplaceTextOnAllPages(oldText, newText);
pdf.SaveAs("replaceText.pdf");Imports IronPdf
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>.NET6</h1>")
Private oldText As String = ".NET6"
Private newText As String = ".NET7"
' Replace text on all pages
pdf.ReplaceTextOnAllPages(oldText, newText)
pdf.SaveAs("replaceText.pdf")Imports IronPdf
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>.NET6</h1>")
Private oldText As String = ".NET6"
Private newText As String = ".NET7"
' Replace text on all pages
pdf.ReplaceTextOnAllPages(oldText, newText)
pdf.SaveAs("replaceText.pdf")Po bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Zwieksz projekt PDF
Dodaj i edytuj komentarze
IronPDF oferuje szerokie opcje dostosowywania dla komentarzy PDF, pozwalając użytkownikom na dodawanie komentarzy w stylu 'przypiętych notatek' bezpośrednio na stronach PDF. Za pomocą klasy TextAnnotation można programistycznie dodawać adnotacje, korzystając z zaawansowanych opcji, takich jak rozmiarowanie, przezroczystość, wybór ikony i możliwości edycji. Klasa LinkAnnotation dodaje klikalne linki nawigacyjne wewnętrzne, takie jak niestandardowe spisy treści i przyciski powrotu do góry, za pomocą tej samej kolekcji adnotacji.
using IronPdf;
using IronPdf.Annotations;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Annotation</h1>");
// Create a PDF annotation object on a specified page index
TextAnnotation annotation = new TextAnnotation(0)
{
Title = "This is the title",
Contents = "This is the long 'sticky note' comment content...",
X = 50,
Y = 700,
};
// Add the annotation
pdf.Annotations.Add(annotation);
pdf.SaveAs("annotation.pdf");using IronPdf;
using IronPdf.Annotations;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Annotation</h1>");
// Create a PDF annotation object on a specified page index
TextAnnotation annotation = new TextAnnotation(0)
{
Title = "This is the title",
Contents = "This is the long 'sticky note' comment content...",
X = 50,
Y = 700,
};
// Add the annotation
pdf.Annotations.Add(annotation);
pdf.SaveAs("annotation.pdf");Imports IronPdf
Imports IronPdf.Annotations
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Annotation</h1>")
' Create a PDF annotation object on a specified page index
Dim annotation As New TextAnnotation(0) With {
.Title = "This is the title",
.Contents = "This is the long 'sticky note' comment content...",
.X = 50,
.Y = 700
}
' Add the annotation
pdf.Annotations.Add(annotation)
pdf.SaveAs("annotation.pdf")Imports IronPdf
Imports IronPdf.Annotations
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Annotation</h1>")
' Create a PDF annotation object on a specified page index
Dim annotation As New TextAnnotation(0) With {
.Title = "This is the title",
.Contents = "This is the long 'sticky note' comment content...",
.X = 50,
.Y = 700
}
' Add the annotation
pdf.Annotations.Add(annotation)
pdf.SaveAs("annotation.pdf")Po bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Stempluj tekst i obrazy
IronPDF oferuje szerokie opcje dostosowywania, jak stemplować tekst i obrazy na PDF-ie. W tym przykładzie użyjemy klasy TextStamper, aby nałożyć stempel na PDF, używając metody ApplyStamp, jak pokazano poniżej.
using IronPdf;
using IronPdf.Editing;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>");
// Create text stamper
TextStamper textStamper = new TextStamper()
{
Text = "Text Stamper!",
FontFamily = "Bungee Spice",
UseGoogleFont = true,
FontSize = 30,
IsBold = true,
IsItalic = true,
VerticalAlignment = VerticalAlignment.Top,
};
// Stamp the text stamper
pdf.ApplyStamp(textStamper);
pdf.SaveAs("stampText.pdf");using IronPdf;
using IronPdf.Editing;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>");
// Create text stamper
TextStamper textStamper = new TextStamper()
{
Text = "Text Stamper!",
FontFamily = "Bungee Spice",
UseGoogleFont = true,
FontSize = 30,
IsBold = true,
IsItalic = true,
VerticalAlignment = VerticalAlignment.Top,
};
// Stamp the text stamper
pdf.ApplyStamp(textStamper);
pdf.SaveAs("stampText.pdf");Imports IronPdf
Imports IronPdf.Editing
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>")
' Create text stamper
Private textStamper As New TextStamper() With {
.Text = "Text Stamper!",
.FontFamily = "Bungee Spice",
.UseGoogleFont = True,
.FontSize = 30,
.IsBold = True,
.IsItalic = True,
.VerticalAlignment = VerticalAlignment.Top
}
' Stamp the text stamper
pdf.ApplyStamp(textStamper)
pdf.SaveAs("stampText.pdf")Imports IronPdf
Imports IronPdf.Editing
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>")
' Create text stamper
Private textStamper As New TextStamper() With {
.Text = "Text Stamper!",
.FontFamily = "Bungee Spice",
.UseGoogleFont = True,
.FontSize = 30,
.IsBold = True,
.IsItalic = True,
.VerticalAlignment = VerticalAlignment.Top
}
' Stamp the text stamper
pdf.ApplyStamp(textStamper)
pdf.SaveAs("stampText.pdf")Po bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Niestandardowe znaki wodne
Możemy również zastosować metodę ApplyWatermark do zintegrowania znaku wodnego zarówno z nowo generowanymi PDF-ami, jak i istniejącymi dokumentami. Ta funkcjonalność umożliwia wzmocnioną rozpoznawalność marki, zapewniając, że twoje materiały przekazują profesjonalny wizerunek.
using IronPdf;
string watermarkHtml = @"
<img src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>
<h1>Iron Software</h1>";
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Watermark</h1>");
// Apply watermark
pdf.ApplyWatermark(watermarkHtml);
pdf.SaveAs("watermark.pdf");using IronPdf;
string watermarkHtml = @"
<img src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>
<h1>Iron Software</h1>";
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Watermark</h1>");
// Apply watermark
pdf.ApplyWatermark(watermarkHtml);
pdf.SaveAs("watermark.pdf");Imports IronPdf
Private watermarkHtml As String = "
<img src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>
<h1>Iron Software</h1>"
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Watermark</h1>")
' Apply watermark
pdf.ApplyWatermark(watermarkHtml)
pdf.SaveAs("watermark.pdf")Imports IronPdf
Private watermarkHtml As String = "
<img src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>
<h1>Iron Software</h1>"
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Watermark</h1>")
' Apply watermark
pdf.ApplyWatermark(watermarkHtml)
pdf.SaveAs("watermark.pdf")Po bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Tła i pierwszy plan
Oprócz znaków wodnych i stempli możemy także dodać tło, aby całkowicie dostosować PDF przy użyciu AddBackgroundPdf.
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Main HTML content</h1>");
// Render background
PdfDocument background = renderer.RenderHtmlAsPdf("<body style='background-color: cyan;'></body>");
// Add background
pdf.AddBackgroundPdf(background);
pdf.SaveAs("addBackground.pdf");using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Main HTML content</h1>");
// Render background
PdfDocument background = renderer.RenderHtmlAsPdf("<body style='background-color: cyan;'></body>");
// Add background
pdf.AddBackgroundPdf(background);
pdf.SaveAs("addBackground.pdf");Imports IronPdf
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Main HTML content</h1>")
' Render background
Private background As PdfDocument = renderer.RenderHtmlAsPdf("<body style='background-color: cyan;'></body>")
' Add background
pdf.AddBackgroundPdf(background)
pdf.SaveAs("addBackground.pdf")Imports IronPdf
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Main HTML content</h1>")
' Render background
Private background As PdfDocument = renderer.RenderHtmlAsPdf("<body style='background-color: cyan;'></body>")
' Add background
pdf.AddBackgroundPdf(background)
pdf.SaveAs("addBackground.pdf")Po bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Rysuj tekst i bitmapy
Rysowanie tekstu na PDF-ach jest intuicyjne i proste; używamy DrawText i dostarczamy mu niezbędne parametry. W tym przykładzie dodajemy nowe wyrażenie Some text czcionką Times New Roman.
using IronPdf;
using IronSoftware.Drawing;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");
// Draw text on PDF
pdf.DrawText("Some text", FontTypes.TimesNewRoman.Name, FontSize: 12, PageIndex: 0, X: 100, Y: 100, Color.Black, Rotation: 0);
pdf.SaveAs("drawText.pdf");using IronPdf;
using IronSoftware.Drawing;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");
// Draw text on PDF
pdf.DrawText("Some text", FontTypes.TimesNewRoman.Name, FontSize: 12, PageIndex: 0, X: 100, Y: 100, Color.Black, Rotation: 0);
pdf.SaveAs("drawText.pdf");Imports IronPdf
Imports IronSoftware.Drawing
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>testing</h1>")
' Draw text on PDF
pdf.DrawText("Some text", FontTypes.TimesNewRoman.Name, FontSize:=12, PageIndex:=0, X:=100, Y:=100, Color.Black, Rotation:=0)
pdf.SaveAs("drawText.pdf")Imports IronPdf
Imports IronSoftware.Drawing
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>testing</h1>")
' Draw text on PDF
pdf.DrawText("Some text", FontTypes.TimesNewRoman.Name, FontSize:=12, PageIndex:=0, X:=100, Y:=100, Color.Black, Rotation:=0)
pdf.SaveAs("drawText.pdf")Po bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Rysuj linie i prostokąty
IronPDF również obsługuje rysowanie linii na PDF-ie. Najpierw tworzymy punkty początkowy i końcowy, inicjując dwie klasy PointF, a następnie stosujemy je metodą DrawLine, jak pokazano poniżej.
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");
// Configure the required parameters
int pageIndex = 0;
var start = new IronSoftware.Drawing.PointF(200,150);
var end = new IronSoftware.Drawing.PointF(1000,150);
int width = 10;
var color = new IronSoftware.Drawing.Color("#000000");
// Draw line on PDF
pdf.DrawLine(pageIndex, start, end, width, color);
pdf.SaveAs("drawLine.pdf");using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");
// Configure the required parameters
int pageIndex = 0;
var start = new IronSoftware.Drawing.PointF(200,150);
var end = new IronSoftware.Drawing.PointF(1000,150);
int width = 10;
var color = new IronSoftware.Drawing.Color("#000000");
// Draw line on PDF
pdf.DrawLine(pageIndex, start, end, width, color);
pdf.SaveAs("drawLine.pdf");Imports IronPdf
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>testing</h1>")
' Configure the required parameters
Private pageIndex As Integer = 0
Private start = New IronSoftware.Drawing.PointF(200,150)
Private [end] = New IronSoftware.Drawing.PointF(1000,150)
Private width As Integer = 10
Private color = New IronSoftware.Drawing.Color("#000000")
' Draw line on PDF
pdf.DrawLine(pageIndex, start, [end], width, color)
pdf.SaveAs("drawLine.pdf")Imports IronPdf
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>testing</h1>")
' Configure the required parameters
Private pageIndex As Integer = 0
Private start = New IronSoftware.Drawing.PointF(200,150)
Private [end] = New IronSoftware.Drawing.PointF(1000,150)
Private width As Integer = 10
Private color = New IronSoftware.Drawing.Color("#000000")
' Draw line on PDF
pdf.DrawLine(pageIndex, start, [end], width, color)
pdf.SaveAs("drawLine.pdf")Po bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Obracaj tekst i strony
Aby obrócić strony PDF, możemy użyć metody SetPageRotation, aby obrócić określone strony. W poniższym przykładzie obracamy tylko strony od 2 do 4, pozostawiając stronę 1 niezmienioną, aby pokazać możliwości.
using IronPdf;
using IronPdf.Rendering;
using System.Linq;
// Import PDF
PdfDocument pdf = PdfDocument.FromFile("multi-page.pdf");
// Set rotation for a single page
pdf.SetPageRotation(0, PdfPageRotation.Clockwise90);
// Set rotation for multiple pages
pdf.SetPageRotations(Enumerable.Range(1,3), PdfPageRotation.Clockwise270);
// Set rotation for the entire document
pdf.SetAllPageRotations(PdfPageRotation.Clockwise180);
pdf.SaveAs("rotated.pdf");using IronPdf;
using IronPdf.Rendering;
using System.Linq;
// Import PDF
PdfDocument pdf = PdfDocument.FromFile("multi-page.pdf");
// Set rotation for a single page
pdf.SetPageRotation(0, PdfPageRotation.Clockwise90);
// Set rotation for multiple pages
pdf.SetPageRotations(Enumerable.Range(1,3), PdfPageRotation.Clockwise270);
// Set rotation for the entire document
pdf.SetAllPageRotations(PdfPageRotation.Clockwise180);
pdf.SaveAs("rotated.pdf");Imports IronPdf
Imports IronPdf.Rendering
Imports System.Linq
' Import PDF
Private pdf As PdfDocument = PdfDocument.FromFile("multi-page.pdf")
' Set rotation for a single page
pdf.SetPageRotation(0, PdfPageRotation.Clockwise90)
' Set rotation for multiple pages
pdf.SetPageRotations(Enumerable.Range(1,3), PdfPageRotation.Clockwise270)
' Set rotation for the entire document
pdf.SetAllPageRotations(PdfPageRotation.Clockwise180)
pdf.SaveAs("rotated.pdf")Imports IronPdf
Imports IronPdf.Rendering
Imports System.Linq
' Import PDF
Private pdf As PdfDocument = PdfDocument.FromFile("multi-page.pdf")
' Set rotation for a single page
pdf.SetPageRotation(0, PdfPageRotation.Clockwise90)
' Set rotation for multiple pages
pdf.SetPageRotations(Enumerable.Range(1,3), PdfPageRotation.Clockwise270)
' Set rotation for the entire document
pdf.SetAllPageRotations(PdfPageRotation.Clockwise180)
pdf.SaveAs("rotated.pdf")Listę dostępnych enumów dotyczących kąta obrotu można znaleźć tutaj.
Po bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Przekształcaj strony PDF
Oprócz obrotów, możemy również przekształcać strony PDF, dostarczając zakres parametrów. W poniższym przykładzie wybieramy pierwszą stronę PDF i używając Transform, przesuwamy zawartość pierwszej strony o 50 punktów w prawo i w dół i skalujemy ją do 80% jej pierwotnego rozmiaru.
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("basic.pdf");
pdf.Pages[0].Transform(50, 50, 0.8, 0.8);
pdf.SaveAs("transformPage.pdf");using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("basic.pdf");
pdf.Pages[0].Transform(50, 50, 0.8, 0.8);
pdf.SaveAs("transformPage.pdf");Imports IronPdf
Dim pdf As PdfDocument = PdfDocument.FromFile("basic.pdf")
pdf.Pages(0).Transform(50, 50, 0.8, 0.8)
pdf.SaveAs("transformPage.pdf")Imports IronPdf
Dim pdf As PdfDocument = PdfDocument.FromFile("basic.pdf")
pdf.Pages(0).Transform(50, 50, 0.8, 0.8)
pdf.SaveAs("transformPage.pdf")Po bardziej szczegółowe wyjaśnienie tego fragmentu kodu i eksplorację jego dodatkowej funkcjonalności, zapoznaj się z naszym obszernym przewodnikiem.
Wnioski
Powyższa lista przykładów pokazuje, że IronPDF ma kluczowe funkcje, które działają natychmiast, jeśli chodzi o edycję PDF.
Jeśli chcesz złożyć prośbę o funkcję lub masz jakiekolwiek ogólne pytania dotyczące IronPDF lub licencjonowania, prosimy skontaktować się z naszym zespołem wsparcia. Będziemy bardziej niż szczęśliwi, aby Ci pomóc.
Najczęściej zadawane pytania
Jak mogę dodać stempel tekstowy do PDF za pomocą IronPDF?
Można dodać stempel tekstowy, używając klasy TextStamper w IronPDF. Utwórz obiekt PdfDocument, zastosuj stempel za pomocą metody ApplyStamp, a następnie zapisz zmiany. Dzięki temu można efektywnie modyfikować pliki PDF programowo.
Jaką metodę oferuje IronPDF do ekstrakcji obrazów z PDF?
IronPDF udostępnia metodę ExtractAllImages. Funkcja ta pozwala łatwo wyodrębniać i zapisywać wszystkie obrazy z PDF, upraszczając proces zarządzania zawartością wizualną.
Czy IronPDF obsługuje redakcję tekstu w PDF?
Tak, za pomocą funkcji RedactTextOnAllPages, IronPDF może redagować konkretne frazy lub słowa kluczowe na wszystkich stronach PDF, zapewniając kompleksowe ukrycie poufnych informacji w całym dokumencie.
Czy IronPDF obsługuje obracanie stron w PDF?
IronPDF umożliwia obracanie stron za pomocą metod takich jak SetPageRotation lub SetAllPageRotations, umożliwiając obracanie konkretnych stron lub całego dokumentu do różnych kątów programowo.
Jak wyeksportować PDF do strumienia pamięci używając IronPDF?
Możesz wyeksportować PDF do strumienia pamięci w IronPDF poprzez utworzenie obiektu MemoryStream i użycie metody PdfDocument.Stream do eksportu, co pozwala na łatwą integrację z innymi częściami aplikacji.
Jakie opcje do anotacji PDF oferuje IronPDF?
IronPDF obsługuje szerokie możliwości anotacji, w tym klasy TextAnnotation i LinkAnnotation do dodawania notatek samoprzylepnych oraz interaktywnych linków nawigacyjnych, zwiększając interaktywność PDF i zaangażowanie użytkowników.
Jak można dodać własne znaki wodne do PDF za pomocą IronPDF?
Dzięki metodzie ApplyWatermark w IronPDF, można dodawać znaki wodne oparte na HTML do nowych i istniejących PDF, ułatwiając rozpoznawalność marki i profesjonalną prezentację dokumentów.
Czy można zamieniać tekst w PDF za pomocą IronPDF?
Tak, funkcja ReplaceTextOnAllPages w IronPDF pozwala zastępować tekst w całym dokumencie, co ułatwia aktualizację powtarzającej się treści w sposób wydajny.
Czy IronPDF można zintegrować z istniejącymi aplikacjami C#?
IronPDF można zintegrować z istniejącymi aplikacjami .NET napisanymi w C#, z funkcjami umożliwiającymi ładowanie i tworzenie PDF bezpośrednio ze strumieni, wspierając tym samym niezawodny rozwój aplikacji.
Jakie możliwości oferuje IronPDF do transformacji zawartości stron PDF?
IronPDF udostępnia metody Transform do tłumaczenia i skalowania zawartości stron PDF, pozwalając na precyzyjne zarządzanie i dostosowywanie prezentacji dokumentu programowo.
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ęczników.