如何在C#中編輯PDF
介紹
Iron Software 已將許多不同的 PDF 編輯功能簡化為 IronPDF 庫中易於閱讀和理解的方法。無論是添加簽名、添加 HTML 頁腳、加蓋水印還是添加註釋,IronPDF 都是適合您的工具,它使您能夠編寫可讀的代碼,生成程式化 PDF,輕鬆進行調試,並輕鬆部署到任何受支持的環境或平台。
IronPDF 在編輯 PDF 時擁有無數功能。在這篇教學文章中,我們將通過一些主要功能的代碼示例和一些解釋來逐步了解。
通過這篇文章,您將對如何使用 IronPDF 在 C# 中編輯您的 PDF 有良好的理解。
目錄
<
編輯文件結構
操作頁面
在特定索引添加PDF,將頁面作為範圍或逐頁複製,從任何PDF中刪除頁面,使用IronPDF都如同閒庭信步,因為該工具處理了幕後的一切。
添加頁面
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-1.cs
var pdf = new PdfDocument("report.pdf");
var renderer = new ChromePdfRenderer();
var coverPagePdf = renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>");
pdf.PrependPdf(coverPagePdf);
pdf.SaveAs("report_with_cover.pdf");
Dim pdf = New PdfDocument("report.pdf")
Dim renderer = New ChromePdfRenderer()
Dim coverPagePdf = renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>")
pdf.PrependPdf(coverPagePdf)
pdf.SaveAs("report_with_cover.pdf")
複製頁面
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-2.cs
var pdf = new PdfDocument("report.pdf");
// Copy pages 5 to 7 and save them as a new document.
pdf.CopyPages(4, 6).SaveAs("report_highlight.pdf");
Dim pdf = New PdfDocument("report.pdf")
' Copy pages 5 to 7 and save them as a new document.
pdf.CopyPages(4, 6).SaveAs("report_highlight.pdf")
刪除頁面
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-3.cs
var pdf = new PdfDocument("report.pdf");
// Remove the last page from the PDF and save again
pdf.RemovePage(pdf.PageCount - 1);
pdf.SaveAs("report_minus_one_page.pdf");
Dim pdf = New PdfDocument("report.pdf")
' Remove the last page from the PDF and save again
pdf.RemovePage(pdf.PageCount - 1)
pdf.SaveAs("report_minus_one_page.pdf")
合併和拆分PDF
通過IronPDF的直觀API,可以輕鬆將多個PDF合併為一個PDF或拆分現有的PDF。
將多個現有的PDF合併成單一PDF文件
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-4.cs
var pdfs = new List<PdfDocument>
{
PdfDocument.FromFile("A.pdf"),
PdfDocument.FromFile("B.pdf"),
PdfDocument.FromFile("C.pdf")
};
PdfDocument mergedPdf = PdfDocument.Merge(pdfs);
mergedPdf.SaveAs("merged.pdf");
foreach (var pdf in pdfs)
{
pdf.Dispose();
}
Dim pdfs = New List(Of PdfDocument) From {PdfDocument.FromFile("A.pdf"), PdfDocument.FromFile("B.pdf"), PdfDocument.FromFile("C.pdf")}
Dim mergedPdf As PdfDocument = PdfDocument.Merge(pdfs)
mergedPdf.SaveAs("merged.pdf")
For Each pdf In pdfs
pdf.Dispose()
Next pdf
如果要查看我們程式碼範例頁面上的兩個或多個PDF如何合併,請訪問 這裡.
分割PDF並提取頁面
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-5.cs
var pdf = new PdfDocument("sample.pdf");
// Take the first page
var pdf_page1 = pdf.CopyPage(0);
pdf_page1.SaveAs("Split1.pdf");
// Take the pages 2 & 3
var pdf_page2_3 = pdf.CopyPages(1, 2);
pdf_page2_3.SaveAs("Spli2t.pdf");
Dim pdf = New PdfDocument("sample.pdf")
' Take the first page
Dim pdf_page1 = pdf.CopyPage(0)
pdf_page1.SaveAs("Split1.pdf")
' Take the pages 2 & 3
Dim pdf_page2_3 = pdf.CopyPages(1, 2)
pdf_page2_3.SaveAs("Spli2t.pdf")
要查看我們程式碼範例頁面上的分割和提取頁面,請訪問 這裡.
編輯文件屬性
添加和使用 PDF 元數據
您可以輕鬆地使用 IronPDF 瀏覽和編輯 PDF 元數據:
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-6.cs
// Open an Encrypted File, alternatively create a new PDF from Html
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");
// Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = System.DateTime.Now;
// Edit file security settings
// The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption();
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key");
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;
// Change or set the document encryption password
pdf.SecuritySettings.OwnerPassword = "top-secret"; // password to edit the pdf
pdf.SecuritySettings.UserPassword = "shareable"; // password to open the pdf
pdf.SaveAs("secured.pdf");
Imports System
' Open an Encrypted File, alternatively create a new PDF from Html
Dim pdf = PdfDocument.FromFile("encrypted.pdf", "password")
' Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = DateTime.Now
' Edit file security settings
' The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key")
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights
' Change or set the document encryption password
pdf.SecuritySettings.OwnerPassword = "top-secret" ' password to edit the pdf
pdf.SecuritySettings.UserPassword = "shareable" ' password to open the pdf
pdf.SaveAs("secured.pdf")
數位簽章
IronPDF 具有使用 .pfx 和 .p12 X509Certificate2 數位證書來簽署新PDF或現有PDF文檔的選項。
一旦PDF文件被簽署,未經證書驗證就不能修改它。這保證了文件的真實性。
若要使用Adobe Reader免費生成簽署證書,請閱讀 https://helpx.adobe.com/acrobat/using/digital-ids.html
除了密碼學簽名,還可以使用手寫簽名圖片或公司印章圖片與 IronPDF 簽署文件。
在一行代碼中對現有PDF進行密碼學簽名。!
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-7.cs
using IronPdf;
using IronPdf.Signing;
new IronPdf.Signing.PdfSignature("Iron.p12", "123456").SignPdfFile("any.pdf");
Imports IronPdf
Imports IronPdf.Signing
Call (New IronPdf.Signing.PdfSignature("Iron.p12", "123456")).SignPdfFile("any.pdf")
更高級的範例,具有更多的控制:
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-8.cs
using IronPdf;
// Step 1. Create a PDF
var renderer = new ChromePdfRenderer();
var doc = renderer.RenderHtmlAsPdf("<h1>Testing 2048 bit digital security</h1>");
// Step 2. Create a Signature.
// You may create a .pfx or .p12 PDF signing certificate using Adobe Acrobat Reader.
// Read: https://helpx.adobe.com/acrobat/using/digital-ids.html
var signature = new IronPdf.Signing.PdfSignature("Iron.pfx", "123456")
{
// Step 3. Optional signing options and a handwritten signature graphic
SigningContact = "support@ironsoftware.com",
SigningLocation = "Chicago, USA",
SigningReason = "To show how to sign a PDF"
};
//Step 4. Sign the PDF with the PdfSignature. Multiple signing certificates may be used
doc.Sign(signature);
//Step 5. The PDF is not signed until saved to file, steam or byte array.
doc.SaveAs("signed.pdf");
Imports IronPdf
' Step 1. Create a PDF
Private renderer = New ChromePdfRenderer()
Private doc = renderer.RenderHtmlAsPdf("<h1>Testing 2048 bit digital security</h1>")
' Step 2. Create a Signature.
' You may create a .pfx or .p12 PDF signing certificate using Adobe Acrobat Reader.
' Read: https://helpx.adobe.com/acrobat/using/digital-ids.html
Private signature = New IronPdf.Signing.PdfSignature("Iron.pfx", "123456") With {
.SigningContact = "support@ironsoftware.com",
.SigningLocation = "Chicago, USA",
.SigningReason = "To show how to sign a PDF"
}
'Step 4. Sign the PDF with the PdfSignature. Multiple signing certificates may be used
doc.Sign(signature)
'Step 5. The PDF is not signed until saved to file, steam or byte array.
doc.SaveAs("signed.pdf")
PDF 附件
IronPDF完全支援添加和移除PDF文件的附件。
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-9.cs
var Renderer = new ChromePdfRenderer();
var myPdf = Renderer.RenderHtmlFileAsPdf("my-content.html");
// Here we can add an attachment with a name and byte[]
var attachment1 = myPdf.Attachments.AddAttachment("attachment_1", example_attachment);
// And here is an example of removing an attachment
myPdf.Attachments.RemoveAttachment(attachment1);
myPdf.SaveAs("my-content.pdf");
Dim Renderer = New ChromePdfRenderer()
Dim myPdf = Renderer.RenderHtmlFileAsPdf("my-content.html")
' Here we can add an attachment with a name and byte[]
Dim attachment1 = myPdf.Attachments.AddAttachment("attachment_1", example_attachment)
' And here is an example of removing an attachment
myPdf.Attachments.RemoveAttachment(attachment1)
myPdf.SaveAs("my-content.pdf")
壓縮 PDF
IronPDF 支援壓縮 PDF 檔案。一種減少 PDF 檔案大小的方法是減小 PdfDocument 中嵌入圖片的大小。在 IronPDF 中,我們可以調用 CompressImages
方法。
調整 JPEG 圖片大小的方式是:100% 品質幾乎沒有損失,而 1% 是非常低品質的輸出圖片。一般來說,90% 以上被認為是高品質,80%-90% 被認為是中等品質,70%-80% 被認為是低品質。低於 70% 會產生低品質圖片,但這樣做可能會大幅減少 PdfDocument 的總檔案大小。
請嘗試不同的值來了解品質範圍與檔案大小之間的平衡,從而獲得最佳平衡效果。品質降低的明顯程度最終取決於輸入圖片的類型,有些圖片可能在清晰度上會有更顯著的降低。
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-10.cs
var pdf = new PdfDocument("document.pdf");
// Quality parameter can be 1-100, where 100 is 100% of original quality
pdf.CompressImages(60);
pdf.SaveAs("document_compressed.pdf");
Dim pdf = New PdfDocument("document.pdf")
' Quality parameter can be 1-100, where 100 is 100% of original quality
pdf.CompressImages(60)
pdf.SaveAs("document_compressed.pdf")
有第二個可選參數,可以根據圖像在PDF文件中的可見大小縮小圖像解析度。請注意,這可能會在某些圖像配置中導致失真:
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-11.cs
var pdf = new PdfDocument("document.pdf");
pdf.CompressImages(90, true);
pdf.SaveAs("document_scaled_compressed.pdf");
Dim pdf = New PdfDocument("document.pdf")
pdf.CompressImages(90, True)
pdf.SaveAs("document_scaled_compressed.pdf")
編輯PDF內容
添加页眉和页脚
您可以輕松地向 PDF 添加頁眉和頁腳。IronPDF 有兩種不同類型的 "HeaderFooters",即 TextHeaderFooter
和 HtmlHeaderFooter
。TextHeaderFooter 更適合僅包含文本的頁眉和頁腳,並且可以使用合併域,如 "{頁面} 的 {總頁數}
. HtmlHeaderFooter 是一個先進的頁首和頁尾功能,可以處理其中的任何 HTML 並整齊地格式化。
HTML 頁首和頁尾
HTML 頁首和頁尾將使用渲染版本的 HTML 作為 PDF 文件的頁首或頁尾,以實現像素級精確的佈局。
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-12.cs
var renderer = new ChromePdfRenderer();
// Build a footer using html to style the text
// mergeable fields are:
// {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
MaxHeight = 15, //millimeters
HtmlFragment = "<center><i>{page} of {total-pages}<i></center>",
DrawDividerLine = true
};
// Build a header using an image asset
// Note the use of BaseUrl to set a relative path to the assets
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
MaxHeight = 20, //millimeters
HtmlFragment = "<img src='logo.png'>",
BaseUrl = new System.Uri(@"C:\assets\images").AbsoluteUri
};
Dim renderer = New ChromePdfRenderer()
' Build a footer using html to style the text
' mergeable fields are:
' {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {
.MaxHeight = 15,
.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>",
.DrawDividerLine = True
}
' Build a header using an image asset
' Note the use of BaseUrl to set a relative path to the assets
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
.MaxHeight = 20,
.HtmlFragment = "<img src='logo.png'>",
.BaseUrl = (New System.Uri("C:\assets\images")).AbsoluteUri
}
參閱以下教學範例,以獲取包含多個使用案例的完整深入示例: 這裡.
文字頁首和頁尾
基本的頁首和頁尾是 TextHeaderFooter,請參閱以下範例。
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-13.cs
var renderer = new ChromePdfRenderer
{
RenderingOptions =
{
FirstPageNumber = 1, // use 2 if a cover-page will be appended
// Add a header to every page easily:
TextHeader =
{
DrawDividerLine = true,
CenterText = "{url}",
Font = IronSoftware.Drawing.FontTypes.Helvetica,
FontSize = 12
},
// Add a footer too:
TextFooter =
{
DrawDividerLine = true,
Font = IronSoftware.Drawing.FontTypes.Arial,
FontSize = 10,
LeftText = "{date} {time}",
RightText = "{page} of {total-pages}"
}
}
};
Dim renderer = New ChromePdfRenderer With {
.RenderingOptions = {
FirstPageNumber = 1, TextHeader = {
DrawDividerLine = True,
CenterText = "{url}",
Font = IronSoftware.Drawing.FontTypes.Helvetica,
FontSize = 12
},
TextFooter = {
DrawDividerLine = True,
Font = IronSoftware.Drawing.FontTypes.Arial,
FontSize = 10,
LeftText = "{date} {time}",
RightText = "{page} of {total-pages}"
}
}
}
我們還有以下合併欄位,渲染時將替換為值:{頁面},
{總頁數},
{網址},
{日期},
{時間},
{html-標題},
{pdf-title}```
### 在 PDF 中查找和替換文字
在您的 PDF 中製作佔位符並以程式化的方式替換它們,或者只需使用我們的 `ReplaceTextOnPage` 方法替換所有出現的文字短語。
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-14.cs
如需查看我們「尋找及替換文字」範例,請造訪我們的「程式碼範例」頁面。 這裡
大綱和書籤
大綱或「書籤」提供了一種導航到PDF重要頁面的方法。在Adobe Acrobat Reader中,這些書籤 (可以嵌套) 顯示在應用程式的左側邊欄。IronPDF 將自動導入現有的 PDF 文件中的書籤,並允許添加、編輯和嵌套更多書籤。
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-15.cs
// Create a new PDF or edit an existing document.
PdfDocument pdf = PdfDocument.FromFile("existing.pdf");
// Add bookmark
pdf.Bookmarks.AddBookMarkAtEnd("Author's Note", 2);
pdf.Bookmarks.AddBookMarkAtEnd("Table of Contents", 3);
// Store new bookmark in a variable to add nested bookmarks to
var summaryBookmark = pdf.Bookmarks.AddBookMarkAtEnd("Summary", 17);
// Add a sub-bookmark within the summary
var conclusionBookmark = summaryBookmark.Children.AddBookMarkAtStart("Conclusion", 18);
// Add another bookmark to end of highest-level bookmark list
pdf.Bookmarks.AddBookMarkAtEnd("References", 20);
pdf.SaveAs("existing.pdf");
' Create a new PDF or edit an existing document.
Dim pdf As PdfDocument = PdfDocument.FromFile("existing.pdf")
' Add bookmark
pdf.Bookmarks.AddBookMarkAtEnd("Author's Note", 2)
pdf.Bookmarks.AddBookMarkAtEnd("Table of Contents", 3)
' Store new bookmark in a variable to add nested bookmarks to
Dim summaryBookmark = pdf.Bookmarks.AddBookMarkAtEnd("Summary", 17)
' Add a sub-bookmark within the summary
Dim conclusionBookmark = summaryBookmark.Children.AddBookMarkAtStart("Conclusion", 18)
' Add another bookmark to end of highest-level bookmark list
pdf.Bookmarks.AddBookMarkAtEnd("References", 20)
pdf.SaveAs("existing.pdf")
要查看我們代碼範例頁面上的大綱和書籤範例,請訪問 這裡.
新增和編輯註解
IronPDF在PDF註解方面擁有豐富的自訂功能。請參考以下範例以展示其功能:
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-16.cs
// create a new PDF or load and edit an existing document.
var pdf = PdfDocument.FromFile("existing.pdf");
// Create a PDF annotation object
var textAnnotation = new IronPdf.Annotations.TextAnnotation(PageIndex: 0)
{
Title = "This is the major title",
Contents = "This is the long 'sticky note' comment content...",
Subject = "This is a subtitle",
Icon = IronPdf.Annotations.TextAnnotation.AnnotationIcon.Help,
Opacity = 0.9,
Printable = false,
Hidden = false,
OpenByDefault = true,
ReadOnly = false,
Rotatable = true,
};
// Add the annotation "sticky note" to a specific page and location within any new or existing PDF.
pdf.Annotations.Add(textAnnotation);
pdf.SaveAs("existing.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
PDF 註釋允許添加類似“便利貼”樣式的評論到 PDF 頁面。TextAnnotation
類允許以程式方式添加註釋。支援的進階文字註釋功能包括大小調整、不透明度、圖標和編輯。
添加背景和前景
使用 IronPDF,我們可以輕鬆合併兩個 PDF 文件,將其中一個作為背景或前景:
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-17.cs
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.AddBackgroundPdf(@"MyBackground.pdf");
pdf.AddForegroundOverlayPdfToPage(0, @"MyForeground.pdf", 0);
pdf.SaveAs(@"C:\Path\To\Complete.pdf");
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.AddBackgroundPdf("MyBackground.pdf")
pdf.AddForegroundOverlayPdfToPage(0, "MyForeground.pdf", 0)
pdf.SaveAs("C:\Path\To\Complete.pdf")
加蓋和浮水印
加蓋和浮水印功能是任何 PDF 編輯器的基本功能。IronPDF 擁有一個驚人的 API,可以創建各種蓋章,例如圖片蓋章和 HTML 蓋章。這些蓋章都可以使用對齊和偏移進行高度自訂定位,可以在這裡查看:
Stamper 抽象類別
Stamper
抽象類別用作 IronPDF 所有增添印記方法的參數。
根據不同使用情況有許多類別:
TextStamper
用於增添文字印記 - 範例文字ImageStamper
用於加蓋圖像 - 圖像範例HtmlStamper
以蓋章 HTML - HTML 範例BarcodeStamper
用於加蓋條碼 - 條碼範例- 使用
BarcodeStamper
來蓋上 QR Code - QR Code 範例
請參見浮水印 這裡。
要應用其中任何一個,使用我們的 ApplyStamp ()
方法。參見: 本教程的應用印章部分.
Stamper 類別屬性
abstract class Stamper
└─── int : Opacity
└─── int : Rotation
└─── double : Scale
└─── Length : HorizontalOffset
└─── Length : VerticalOffset
└─── Length : MinWidth
└─── Length : MaxWidth
└─── Length : MinHeight
└─── Length : MaxHeight
└─── string : Hyperlink
└─── bool : IsStampBehindContent (default : false)
└─── HorizontalAlignment : HorizontalAlignment
│ │ Left
│ │ Center (default)
│ │ Right
│
└─── VerticalAlignment : VerticalAlignment
│ Top
│ Middle (default)
│ Bottom
加蓋範例
下面我們展示了 Stamper 的每個子類別及其代碼範例。
在 PDF 上加蓋文字
用兩種不同的方式來创建兩個不同的文本印章並應用它們:
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-18.cs
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>");
TextStamper stamper1 = new TextStamper
{
Text = "Hello World! Stamp One Here!",
FontFamily = "Bungee Spice",
UseGoogleFont = true,
FontSize = 100,
IsBold = true,
IsItalic = true,
VerticalAlignment = VerticalAlignment.Top
};
TextStamper stamper2 = new TextStamper()
{
Text = "Hello World! Stamp Two Here!",
FontFamily = "Bungee Spice",
UseGoogleFont = true,
FontSize = 30,
VerticalAlignment = VerticalAlignment.Bottom
};
Stamper[] stampersToApply = { stamper1, stamper2 };
pdf.ApplyMultipleStamps(stampersToApply);
pdf.ApplyStamp(stamper2);
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>")
Dim stamper1 As New TextStamper With {
.Text = "Hello World! Stamp One Here!",
.FontFamily = "Bungee Spice",
.UseGoogleFont = True,
.FontSize = 100,
.IsBold = True,
.IsItalic = True,
.VerticalAlignment = VerticalAlignment.Top
}
Dim stamper2 As New TextStamper() With {
.Text = "Hello World! Stamp Two Here!",
.FontFamily = "Bungee Spice",
.UseGoogleFont = True,
.FontSize = 30,
.VerticalAlignment = VerticalAlignment.Bottom
}
Dim stampersToApply() As Stamper = { stamper1, stamper2 }
pdf.ApplyMultipleStamps(stampersToApply)
pdf.ApplyStamp(stamper2)
將圖像蓋印到 PDF 上
將圖像蓋印應用到現有 PDF 文件的各種頁面組合:
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-19.cs
var pdf = new PdfDocument("/attachments/2022_Q1_sales.pdf");
ImageStamper logoImageStamper = new ImageStamper("/assets/logo.png");
// Apply to every page, one page, or some pages
pdf.ApplyStamp(logoImageStamper);
pdf.ApplyStamp(logoImageStamper, 0);
pdf.ApplyStamp(logoImageStamper, new[] { 0, 3, 11 });
Dim pdf = New PdfDocument("/attachments/2022_Q1_sales.pdf")
Dim logoImageStamper As New ImageStamper("/assets/logo.png")
' Apply to every page, one page, or some pages
pdf.ApplyStamp(logoImageStamper)
pdf.ApplyStamp(logoImageStamper, 0)
pdf.ApplyStamp(logoImageStamper, { 0, 3, 11 })
在 PDF 上加蓋 HTML
撰寫您自己的 HTML 以用作印章:
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-20.cs
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<p>Hello World, example HTML body.</p>");
HtmlStamper stamper = new HtmlStamper($"<p>Example HTML Stamped</p><div style='width:250pt;height:250pt;background-color:red;'></div>")
{
HorizontalOffset = new Length(-3, MeasurementUnit.Inch),
VerticalAlignment = VerticalAlignment.Bottom
};
pdf.ApplyStamp(stamper);
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<p>Hello World, example HTML body.</p>")
Dim stamper As New HtmlStamper($"<p>Example HTML Stamped</p><div style='width:250pt;height:250pt;background-color:red;'></div>")
If True Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: HorizontalOffset = new Length(-3, MeasurementUnit.Inch), VerticalAlignment = VerticalAlignment.Bottom
New Length(-3, MeasurementUnit.Inch), VerticalAlignment = VerticalAlignment.Bottom
HorizontalOffset = New Length(-3, MeasurementUnit.Inch), VerticalAlignment
End If
pdf.ApplyStamp(stamper)
將條碼加蓋至PDF
建立並加蓋條碼的範例:
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-21.cs
BarcodeStamper bcStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.Code39);
bcStamp.HorizontalAlignment = HorizontalAlignment.Left;
bcStamp.VerticalAlignment = VerticalAlignment.Bottom;
var pdf = new PdfDocument("example.pdf");
pdf.ApplyStamp(bcStamp);
Dim bcStamp As New BarcodeStamper("IronPDF", BarcodeEncoding.Code39)
bcStamp.HorizontalAlignment = HorizontalAlignment.Left
bcStamp.VerticalAlignment = VerticalAlignment.Bottom
Dim pdf = New PdfDocument("example.pdf")
pdf.ApplyStamp(bcStamp)
將 QR 碼蓋章到 PDF 上
創建和蓋章 QR 碼的示例:
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-22.cs
BarcodeStamper qrStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.QRCode);
qrStamp.Height = 50; // pixels
qrStamp.Width = 50; // pixels
qrStamp.HorizontalAlignment = HorizontalAlignment.Left;
qrStamp.VerticalAlignment = VerticalAlignment.Bottom;
var pdf = new PdfDocument("example.pdf");
pdf.ApplyStamp(qrStamp);
Dim qrStamp As New BarcodeStamper("IronPDF", BarcodeEncoding.QRCode)
qrStamp.Height = 50 ' pixels
qrStamp.Width = 50 ' pixels
qrStamp.HorizontalAlignment = HorizontalAlignment.Left
qrStamp.VerticalAlignment = VerticalAlignment.Bottom
Dim pdf = New PdfDocument("example.pdf")
pdf.ApplyStamp(qrStamp)
在 PDF 文件中添加水印
水印是一種適用於每個頁面的印章,可以使用 ApplyWatermark
方法輕鬆應用。
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-23.cs
var pdf = new PdfDocument("/attachments/design.pdf");
string html = "<h1> Example Title <h1/>";
int rotation = 0;
int watermarkOpacity = 30;
pdf.ApplyWatermark(html, rotation, watermarkOpacity);
Dim pdf = New PdfDocument("/attachments/design.pdf")
Dim html As String = "<h1> Example Title <h1/>"
Dim rotation As Integer = 0
Dim watermarkOpacity As Integer = 30
pdf.ApplyWatermark(html, rotation, watermarkOpacity)
要查看我們程式碼範例頁中的浮水印範例,請訪問 這裡.
將印章應用到 PDF 上
有幾個 ApplyStamp 方法的過載可以用來將你的印章應用到 PDF。
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-24.cs
var pdf = new PdfDocument("/assets/example.pdf");
// Apply one stamp to all pages
pdf.ApplyStamp(myStamper);
// Apply one stamp to a specific page
pdf.ApplyStamp(myStamper, 0);
// Apply one stamp to specific pages
pdf.ApplyStamp(myStamper, new[] { 0, 3, 5 });
// Apply a stamp array to all pages
pdf.ApplyMultipleStamps(stampArray);
// Apply a stamp array to a specific page
pdf.ApplyMultipleStamps(stampArray, 0);
// Apply a stamp array to specific pages
pdf.ApplyMultipleStamps(stampArray, new[] { 0, 3, 5 });
// And some Async versions of the above
await pdf.ApplyStampAsync(myStamper, 4);
await pdf.ApplyMultipleStampsAsync(stampArray);
// Additional Watermark apply method
string html = "<h1> Example Title <h1/>";
int rotation = 0;
int watermarkOpacity = 30;
pdf.ApplyWatermark(html, rotation, watermarkOpacity);
Dim pdf = New PdfDocument("/assets/example.pdf")
' Apply one stamp to all pages
pdf.ApplyStamp(myStamper)
' Apply one stamp to a specific page
pdf.ApplyStamp(myStamper, 0)
' Apply one stamp to specific pages
pdf.ApplyStamp(myStamper, { 0, 3, 5 })
' Apply a stamp array to all pages
pdf.ApplyMultipleStamps(stampArray)
' Apply a stamp array to a specific page
pdf.ApplyMultipleStamps(stampArray, 0)
' Apply a stamp array to specific pages
pdf.ApplyMultipleStamps(stampArray, { 0, 3, 5 })
' And some Async versions of the above
Await pdf.ApplyStampAsync(myStamper, 4)
Await pdf.ApplyMultipleStampsAsync(stampArray)
' Additional Watermark apply method
Dim html As String = "<h1> Example Title <h1/>"
Dim rotation As Integer = 0
Dim watermarkOpacity As Integer = 30
pdf.ApplyWatermark(html, rotation, watermarkOpacity)
Length 類別
Length 類別有兩個屬性:Unit
和 Value
。決定了使用來自 MeasurementUnit
列舉中的哪個單位後 (默認為頁面的Percentage
)然後選擇 Value
來決定作為基礎單位倍數使用的長度。
長度類屬性
class Length
└─── double : Value (default : 0)
└─── MeasurementUnit : Unit
Inch
Millimeter
Centimeter
Percentage (default)
Pixel
Points
長度範例
創建長度
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-25.cs
new Length(value: 5, unit: MeasurementUnit.Inch); // 5 inches
new Length(value: 25, unit: MeasurementUnit.Pixel);// 25px
new Length(); // 0% of the page dimension because value is defaulted to zero and unit is defaulted to percentage
new Length(value: 20); // 20% of the page dimension
Dim tempVar As New Length(value:= 5, unit:= MeasurementUnit.Inch) ' 5 inches
Dim tempVar2 As New Length(value:= 25, unit:= MeasurementUnit.Pixel) ' 25px
Dim tempVar3 As New Length() ' 0% of the page dimension because value is defaulted to zero and unit is defaulted to percentage
Dim tempVar4 As New Length(value:= 20) ' 20% of the page dimension
使用長度作為參數
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-26.cs
HtmlStamper logoStamper = new HtmlStamper
{
VerticalOffset = new Length(15, MeasurementUnit.Percentage),
HorizontalOffset = new Length(1, MeasurementUnit.Inch)
// set other properties...
};
Dim logoStamper As New HtmlStamper With {
.VerticalOffset = New Length(15, MeasurementUnit.Percentage),
.HorizontalOffset = New Length(1, MeasurementUnit.Inch)
}
在 PDF 中使用表單
創建和編輯表單
使用 IronPDF 創建一個包含內嵌表單欄位的 PDF:
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-27.cs
// Step 1. Creating a PDF with editable forms from HTML using form and input tags
const string formHtml = @"
<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=''>
</form>
</body>
</html>";
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
renderer.RenderHtmlAsPdf(formHtml).SaveAs("BasicForm.pdf");
// Step 2. Reading and Writing PDF form values.
var formDocument = PdfDocument.FromFile("BasicForm.pdf");
// Read the value of the "firstname" field
var firstNameField = formDocument.Form.FindFormField("firstname");
// Read the value of the "lastname" field
var lastNameField = formDocument.Form.FindFormField("lastname");
' Step 1. Creating a PDF with editable forms from HTML using form and input tags
Const formHtml As String = "
<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=''>
</form>
</body>
</html>"
' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
renderer.RenderHtmlAsPdf(formHtml).SaveAs("BasicForm.pdf")
' Step 2. Reading and Writing PDF form values.
Dim formDocument = PdfDocument.FromFile("BasicForm.pdf")
' Read the value of the "firstname" field
Dim firstNameField = formDocument.Form.FindFormField("firstname")
' Read the value of the "lastname" field
Dim lastNameField = formDocument.Form.FindFormField("lastname")
要查看我們程式碼範例頁面上的 PDF 表單範例,請訪問 這裡.
填寫現有表格
使用 IronPDF,您可以輕鬆訪問 PDF 中所有現有的表單欄位並填寫以重新保存:
:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-28.cs
var formDocument = PdfDocument.FromFile("BasicForm.pdf");
// Set and Read the value of the "firstname" field
var firstNameField = formDocument.Form.FindFormField("firstname");
firstNameField.Value = "Minnie";
Console.WriteLine("FirstNameField value: {0}", firstNameField.Value);
// Set and Read the value of the "lastname" field
var lastNameField = formDocument.Form.FindFormField("lastname");
lastNameField.Value = "Mouse";
Console.WriteLine("LastNameField value: {0}", lastNameField.Value);
formDocument.SaveAs("FilledForm.pdf");
Dim formDocument = PdfDocument.FromFile("BasicForm.pdf")
' Set and Read the value of the "firstname" field
Dim firstNameField = formDocument.Form.FindFormField("firstname")
firstNameField.Value = "Minnie"
Console.WriteLine("FirstNameField value: {0}", firstNameField.Value)
' Set and Read the value of the "lastname" field
Dim lastNameField = formDocument.Form.FindFormField("lastname")
lastNameField.Value = "Mouse"
Console.WriteLine("LastNameField value: {0}", lastNameField.Value)
formDocument.SaveAs("FilledForm.pdf")
要查看我們程式碼範例頁面上的 PDF 表單範例,請訪問 這裡.
結論
以上範例清單顯示了 IronPDF 在編輯 PDF 時具有開箱即用的主要功能。
如果您想提出功能請求或對 IronPDF 或許可有任何一般問題,請 聯絡我們的支援團隊我們將非常樂意協助您。