在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
一个体面且简单的PDF操作工具可以简化许多涉及创建和编辑PDF文档的任务和流程。在.NET生态系统中,有两个流行的库—— IronPDF 和 iText – 它们都允许生成 PDF 而无需依赖 Adobe。它们都有各种功能,如创建、编辑、转换等,但本文将重点比较这些库基于三个标准:它们提供的功能能力、提供的文档质量、这些公司针对其产品使用所采用的定价政策。
IronPDF 是一个著名的 .NET PDF 库,它允许程序员轻松创建、修改和操作 PDF 文档。它可以在不同的 .NET 环境中使用,包括 Core、8、7、6 和 Framework,这使其在各种开发需求中具有很高的灵活性。关键功能... IronPDF 其丰富的功能集,包括HTML到PDF转换、PDF合并、PDF加密和数字签名的应用等。文档编写得很容易理解,而库本身也有强大的技术支持。
iText是Java和.NET平台上最受欢迎的PDF库之一。 (C#). iText Core 8 提供了一个企业级的可编程解决方案,用于创建和操作 PDF 文件。iText 支持许多不同的功能,并且以开源形式发布 (AGPL) 许可证和商业许可证。这意味着由于其多功能性,它能够在数字化转型项目中涵盖广泛的用例。
IronPDF 和 iText 兼容多种平台;它们可以跨许多不同的系统处理 PDF 文件,并且可以在 .NET 框架内处理。正因为如此,我们将在下文中比较每个产品支持的框架和平台。
IronPDF 支持广泛的平台和环境,确保在各种系统中无缝集成和部署:
.NET 版本:
(C#, VB.NET, F#)
.NET Core (8、7、6、5 和 3.1+)
.NET 版本:
.NET Core (2.x, 3.x)
IronPDF iText 和 IronPDF 都提供了一系列功能和工具, 可用于处理 PDF 文件;下一部分的重点将是仔细看看这些功能,以及这两个库在执行不同 PDF 相关任务时的对比。
有关IronPDF提供的广泛功能的更多信息,请访问 IronPDF功能页面.
HTML 转换 将HTML内容转换为PDF 在许多不同的办公室和工作空间中, 是一项非常简单的任务。下面是一些代码示例,比较了IronPDF和iText如何处理这一过程。
IronPDF
using IronPdf;
// Disable local disk access or cross-origin requests
Installation.EnableWebSecurity = true;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from an HTML string using C#
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
pdf.SaveAs("output.pdf");
// Advanced Example with HTML Assets
// Load external html assets: images, CSS and JavaScript.
// An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
using IronPdf;
// Disable local disk access or cross-origin requests
Installation.EnableWebSecurity = true;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from an HTML string using C#
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
pdf.SaveAs("output.pdf");
// Advanced Example with HTML Assets
// Load external html assets: images, CSS and JavaScript.
// An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
Imports IronPdf
' Disable local disk access or cross-origin requests
Installation.EnableWebSecurity = True
' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()
' Create a PDF from an HTML string using C#
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
pdf.SaveAs("output.pdf")
' Advanced Example with HTML Assets
' Load external html assets: images, CSS and JavaScript.
' An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
Dim myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\site\assets\")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
iText
using iText.Html2pdf;
static void Main(string[] args)
{
using (FileStream htmlSource = File.Open("input.html", FileMode.Open))
using (FileStream pdfDest = File.Open("output.pdf", FileMode.Create))
{
ConverterProperties converterProperties = new ConverterProperties();
HtmlConverter.ConvertToPdf(htmlSource, pdfDest, converterProperties);
}
}
using iText.Html2pdf;
static void Main(string[] args)
{
using (FileStream htmlSource = File.Open("input.html", FileMode.Open))
using (FileStream pdfDest = File.Open("output.pdf", FileMode.Create))
{
ConverterProperties converterProperties = new ConverterProperties();
HtmlConverter.ConvertToPdf(htmlSource, pdfDest, converterProperties);
}
}
Imports iText.Html2pdf
Shared Sub Main(ByVal args() As String)
Using htmlSource As FileStream = File.Open("input.html", FileMode.Open)
Using pdfDest As FileStream = File.Open("output.pdf", FileMode.Create)
Dim converterProperties As New ConverterProperties()
HtmlConverter.ConvertToPdf(htmlSource, pdfDest, converterProperties)
End Using
End Using
End Sub
在将HTML转换为PDF时,IronPDF 提供了一种简洁且方便的工具来完成这项任务。使用ChromePdfRenderer将HTML内容转换为PDF,IronPDF在提供像素级精准的PDF文档方面表现出色。用户可以直接从HTML字符串创建PDF,如第一个示例所示,或者在高级示例中,利用可选的基路径包含外部资源如图像。iText 采用基本方法,使用其HtmlConverter类从HTML文件创建PDF文档。
加密 PDF文档的加密和解密在许多工作场所都至关重要。为了轻松处理这项任务,需要一个方便的工具。在下面的代码中,我们将看到iText和IronPDF如何处理PDF的加密。
IronPDF
using IronPdf;
using System;
// 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 = 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.Password = "my-password";
pdf.SaveAs("secured.pdf");
using IronPdf;
using System;
// 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 = 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.Password = "my-password";
pdf.SaveAs("secured.pdf");
Imports IronPdf
Imports System
' Open an Encrypted File, alternatively create a new PDF from Html
Private 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.Password = "my-password"
pdf.SaveAs("secured.pdf")
iText
using System;
using System.IO;
using System.Text;
using iText.Kernel.Pdf;
public class EncryptPdf
{
public static readonly String DEST = "results/sandbox/security/encrypt_pdf.pdf";
public static readonly String SRC = "../../../resources/pdfs/hello.pdf";
public static readonly String OWNER_PASSWORD = "World";
public static readonly String USER_PASSWORD = "Hello";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new EncryptPdf().ManipulatePdf(DEST);
}
protected void ManipulatePdf(String dest)
{
PdfDocument document = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest,
new WriterProperties().SetStandardEncryption(
Encoding.UTF8.GetBytes(USER_PASSWORD),
Encoding.UTF8.GetBytes(OWNER_PASSWORD),
EncryptionConstants.ALLOW_PRINTING,
EncryptionConstants.ENCRYPTION_AES_128
EncryptionConstants.DO_NOT_ENCRYPT_METADATA
)));
document.Close();
}
}
using System;
using System.IO;
using System.Text;
using iText.Kernel.Pdf;
public class EncryptPdf
{
public static readonly String DEST = "results/sandbox/security/encrypt_pdf.pdf";
public static readonly String SRC = "../../../resources/pdfs/hello.pdf";
public static readonly String OWNER_PASSWORD = "World";
public static readonly String USER_PASSWORD = "Hello";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new EncryptPdf().ManipulatePdf(DEST);
}
protected void ManipulatePdf(String dest)
{
PdfDocument document = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest,
new WriterProperties().SetStandardEncryption(
Encoding.UTF8.GetBytes(USER_PASSWORD),
Encoding.UTF8.GetBytes(OWNER_PASSWORD),
EncryptionConstants.ALLOW_PRINTING,
EncryptionConstants.ENCRYPTION_AES_128
EncryptionConstants.DO_NOT_ENCRYPT_METADATA
)));
document.Close();
}
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
IronPDF 为用户提供了一种简单的方法来加密 PDF 文件,同时还为用户提供了大量的过程控制,包括编辑元数据和调整安全设置,例如使文档只读或限制用户操作如复制和粘贴。另一方面,iText 采用了一种更底层和更长的方法,其中在文档创建过程中应用 PDF 加密,指定所有者和用户密码以及使用像 AES-128 这样的加密标准设置权限,如打印权限。
有时候,在处理机密或私人信息时,可能有必要 编辑 PDF文件的一部分。下面的代码示例将演示如何使用IronPDF对文本进行修改并与iText进行比较。
IronPDF
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("novel.pdf");
// Redact 'are' phrase from all pages
pdf.RedactTextOnAllPages("are");
pdf.SaveAs("redacted.pdf");
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("novel.pdf");
// Redact 'are' phrase from all pages
pdf.RedactTextOnAllPages("are");
pdf.SaveAs("redacted.pdf");
Imports IronPdf
Private pdf As PdfDocument = PdfDocument.FromFile("novel.pdf")
' Redact 'are' phrase from all pages
pdf.RedactTextOnAllPages("are")
pdf.SaveAs("redacted.pdf")
iText
using System;
using System.IO;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using iText.Kernel.Colors;
string src = "input.pdf";
string dest = "output_redacted.pdf";
using (PdfReader reader = new PdfReader(src))
{
using (PdfWriter writer = new PdfWriter(dest))
{
using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
{
// Iterate through each page
for (int pageNum = 1; pageNum <= pdfDoc.GetNumberOfPages(); pageNum++)
{
PdfPage page = pdfDoc.GetPage(pageNum);
PdfCanvas canvas = new PdfCanvas(page);
Rectangle[] rectanglesToRedact = { new Rectangle(100, 100, 200, 50) }; // Example: Define rectangles to redact
// Overlay black rectangles to simulate redaction
foreach (Rectangle rect in rectanglesToRedact)
{
canvas.SetFillColor(ColorConstants.BLACK)
.Rectangle(rect.GetX(), rect.GetY(), rect.GetWidth(), rect.GetHeight())
.Fill();
}
}
}
}
using System;
using System.IO;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using iText.Kernel.Colors;
string src = "input.pdf";
string dest = "output_redacted.pdf";
using (PdfReader reader = new PdfReader(src))
{
using (PdfWriter writer = new PdfWriter(dest))
{
using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
{
// Iterate through each page
for (int pageNum = 1; pageNum <= pdfDoc.GetNumberOfPages(); pageNum++)
{
PdfPage page = pdfDoc.GetPage(pageNum);
PdfCanvas canvas = new PdfCanvas(page);
Rectangle[] rectanglesToRedact = { new Rectangle(100, 100, 200, 50) }; // Example: Define rectangles to redact
// Overlay black rectangles to simulate redaction
foreach (Rectangle rect in rectanglesToRedact)
{
canvas.SetFillColor(ColorConstants.BLACK)
.Rectangle(rect.GetX(), rect.GetY(), rect.GetWidth(), rect.GetHeight())
.Fill();
}
}
}
}
Imports System
Imports System.IO
Imports iText.Kernel.Pdf
Imports iText.Layout
Imports iText.Layout.Element
Imports iText.Layout.Properties
Imports iText.Kernel.Colors
Private src As String = "input.pdf"
Private dest As String = "output_redacted.pdf"
Using reader As New PdfReader(src)
Using writer As New PdfWriter(dest)
Using pdfDoc As New PdfDocument(reader, writer)
' Iterate through each page
Dim pageNum As Integer = 1
Do While pageNum <= pdfDoc.GetNumberOfPages()
Dim page As PdfPage = pdfDoc.GetPage(pageNum)
Dim canvas As New PdfCanvas(page)
Dim rectanglesToRedact() As Rectangle = { New Rectangle(100, 100, 200, 50) } ' Example: Define rectangles to redact
' Overlay black rectangles to simulate redaction
For Each rect As Rectangle In rectanglesToRedact
canvas.SetFillColor(ColorConstants.BLACK).Rectangle(rect.GetX(), rect.GetY(), rect.GetWidth(), rect.GetHeight()).Fill()
Next rect
pageNum += 1
Loop
End Using
End Using
IronPDF 的编辑工具简明易用,只需要几行代码即可简化编辑过程。这有助于提高PDF编辑任务的效率,并为用户提供了一种轻松保护其敏感和私人数据的方式。
另一方面,iText 并没有像 IronPDF 那样提供内置的编辑工具。然而,它仍然可以通过上述方法覆盖敏感数据,画出用户希望编辑的内容。但这可能会导致问题,因为这些矩形实际上并不能移除或正确编辑文本,这意味着其他人可能会复制和粘贴那些尝试被编辑的数据。
能够 签名 将数字文档(如PDF文件)自动化处理可以节省时间。以下是一些代码片段,这些代码将比较IronPDF在执行文档数字签名方面与iText的差异。
IronPDF
using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;
// Create X509Certificate2 object with X509KeyStorageFlags set to Exportable
X509Certificate2 cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);
// Create PdfSignature object
var sig = new PdfSignature(cert);
// Sign PDF document
PdfDocument pdf = PdfDocument.FromFile("document.pdf");
pdf.Sign(sig);
pdf.SaveAs("signed.pdf");
using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;
// Create X509Certificate2 object with X509KeyStorageFlags set to Exportable
X509Certificate2 cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);
// Create PdfSignature object
var sig = new PdfSignature(cert);
// Sign PDF document
PdfDocument pdf = PdfDocument.FromFile("document.pdf");
pdf.Sign(sig);
pdf.SaveAs("signed.pdf");
Imports IronPdf
Imports IronPdf.Signing
Imports System.Security.Cryptography.X509Certificates
' Create X509Certificate2 object with X509KeyStorageFlags set to Exportable
Private cert As New X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable)
' Create PdfSignature object
Private sig = New PdfSignature(cert)
' Sign PDF document
Private pdf As PdfDocument = PdfDocument.FromFile("document.pdf")
pdf.Sign(sig)
pdf.SaveAs("signed.pdf")
iText
using System;
using System.IO;
using iText.Kernel.Pdf;
using iText.Signatures;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;
class Program
{
static void Main(string[] args)
{
string src = "input.pdf";
string dest = "output_signed.pdf";
string pfxFile = "your_certificate.pfx";
string pfxPassword = "your_password";
try
{
// Load your certificate
Pkcs12Store ks = new Pkcs12Store(new FileStream(pfxFile, FileMode.Open), pfxPassword.ToCharArray());
string alias = null;
foreach (string al in ks.Aliases)
{
if (ks.IsKeyEntry(al))
{
alias = al;
break;
}
}
ICipherParameters pk = ks.GetKey(alias).Key;
X509CertificateEntry[] chain = ks.GetCertificateChain(alias);
X509Certificate2 cert = new X509Certificate2(chain[0].Certificate.GetEncoded());
// Create output PDF with signed content
using (PdfReader reader = new PdfReader(src))
{
using (PdfWriter writer = new PdfWriter(dest))
{
using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
{
// Create the signer
PdfSigner signer = new PdfSigner(pdfDoc, writer, new StampingProperties().UseAppendMode());
// Configure signature appearance
PdfSignatureAppearance appearance = signer.GetSignatureAppearance();
appearance.SetReason("Digital Signature");
appearance.SetLocation("Your Location");
appearance.SetContact("Your Contact");
// Create signature
IExternalSignature pks = new PrivateKeySignature(pk, "SHA-256");
signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS);
}
}
}
Console.WriteLine($"PDF digitally signed successfully: {dest}");
}
catch (Exception ex)
{
Console.WriteLine($"Error signing PDF: {ex.Message}");
}
}
}
using System;
using System.IO;
using iText.Kernel.Pdf;
using iText.Signatures;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;
class Program
{
static void Main(string[] args)
{
string src = "input.pdf";
string dest = "output_signed.pdf";
string pfxFile = "your_certificate.pfx";
string pfxPassword = "your_password";
try
{
// Load your certificate
Pkcs12Store ks = new Pkcs12Store(new FileStream(pfxFile, FileMode.Open), pfxPassword.ToCharArray());
string alias = null;
foreach (string al in ks.Aliases)
{
if (ks.IsKeyEntry(al))
{
alias = al;
break;
}
}
ICipherParameters pk = ks.GetKey(alias).Key;
X509CertificateEntry[] chain = ks.GetCertificateChain(alias);
X509Certificate2 cert = new X509Certificate2(chain[0].Certificate.GetEncoded());
// Create output PDF with signed content
using (PdfReader reader = new PdfReader(src))
{
using (PdfWriter writer = new PdfWriter(dest))
{
using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
{
// Create the signer
PdfSigner signer = new PdfSigner(pdfDoc, writer, new StampingProperties().UseAppendMode());
// Configure signature appearance
PdfSignatureAppearance appearance = signer.GetSignatureAppearance();
appearance.SetReason("Digital Signature");
appearance.SetLocation("Your Location");
appearance.SetContact("Your Contact");
// Create signature
IExternalSignature pks = new PrivateKeySignature(pk, "SHA-256");
signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS);
}
}
}
Console.WriteLine($"PDF digitally signed successfully: {dest}");
}
catch (Exception ex)
{
Console.WriteLine($"Error signing PDF: {ex.Message}");
}
}
}
Imports System
Imports System.IO
Imports iText.Kernel.Pdf
Imports iText.Signatures
Imports Org.BouncyCastle.Crypto
Imports Org.BouncyCastle.Pkcs
Imports Org.BouncyCastle.X509
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim src As String = "input.pdf"
Dim dest As String = "output_signed.pdf"
Dim pfxFile As String = "your_certificate.pfx"
Dim pfxPassword As String = "your_password"
Try
' Load your certificate
Dim ks As New Pkcs12Store(New FileStream(pfxFile, FileMode.Open), pfxPassword.ToCharArray())
Dim [alias] As String = Nothing
For Each al As String In ks.Aliases
If ks.IsKeyEntry(al) Then
[alias] = al
Exit For
End If
Next al
Dim pk As ICipherParameters = ks.GetKey([alias]).Key
Dim chain() As X509CertificateEntry = ks.GetCertificateChain([alias])
Dim cert As New X509Certificate2(chain(0).Certificate.GetEncoded())
' Create output PDF with signed content
Using reader As New PdfReader(src)
Using writer As New PdfWriter(dest)
Using pdfDoc As New PdfDocument(reader, writer)
' Create the signer
Dim signer As New PdfSigner(pdfDoc, writer, (New StampingProperties()).UseAppendMode())
' Configure signature appearance
Dim appearance As PdfSignatureAppearance = signer.GetSignatureAppearance()
appearance.SetReason("Digital Signature")
appearance.SetLocation("Your Location")
appearance.SetContact("Your Contact")
' Create signature
Dim pks As IExternalSignature = New PrivateKeySignature(pk, "SHA-256")
signer.SignDetached(pks, chain, Nothing, Nothing, Nothing, 0, PdfSigner.CryptoStandard.CMS)
End Using
End Using
End Using
Console.WriteLine($"PDF digitally signed successfully: {dest}")
Catch ex As Exception
Console.WriteLine($"Error signing PDF: {ex.Message}")
End Try
End Sub
End Class
在为PDF文件进行数字签名时,IronPDF提供了一种简洁而强大的工具来完成这一过程。其简便性使得操作快速进行,为任何开发人员节省了签名所需时间。iText则需要更长、更复杂的过程来为PDF文件应用数字签名,虽然可以使用不同的接口选项和密钥给用户提供更多控制,但其复杂的操作方式可能会成为阻碍。
拥有添加和个性化 水印 通过软件对PDF进行操作可以极大地帮助保密、版权保护、品牌或其他涉及敏感信息的任务。以下是IronPDF和iText如何将水印应用于PDF文件的对比。
IronPDF
using IronPdf;
// Stamps a Watermark onto a new or existing PDF
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs(@"C:\Path\To\Watermarked.pdf");
using IronPdf;
// Stamps a Watermark onto a new or existing PDF
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs(@"C:\Path\To\Watermarked.pdf");
Imports IronPdf
' Stamps a Watermark onto a new or existing PDF
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center)
pdf.SaveAs("C:\Path\To\Watermarked.pdf")
iText
using iText.IO.Font;
using iText.IO.Font.Constants;
using iText.Kernel.Colors;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Extgstate;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
public class TransparentWatermark
{
public static readonly String DEST = "results/sandbox/stamper/transparent_watermark.pdf";
public static readonly String SRC = "../../../resources/pdfs/hero.pdf";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new TransparentWatermark().ManipulatePdf(DEST);
}
protected void ManipulatePdf(String dest)
{
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
PdfCanvas under = new PdfCanvas(pdfDoc.GetFirstPage().NewContentStreamBefore(), new PdfResources(), pdfDoc);
PdfFont font = PdfFontFactory.CreateFont(FontProgramFactory.CreateFont(StandardFonts.HELVETICA));
Paragraph paragraph = new Paragraph("This watermark is added UNDER the existing content")
.SetFont(font)
.SetFontSize(15);
Canvas canvasWatermark1 = new Canvas(under, pdfDoc.GetDefaultPageSize())
.ShowTextAligned(paragraph, 297, 550, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
canvasWatermark1.Close();
PdfCanvas over = new PdfCanvas(pdfDoc.GetFirstPage());
over.SetFillColor(ColorConstants.BLACK);
paragraph = new Paragraph("This watermark is added ON TOP OF the existing content")
.SetFont(font)
.SetFontSize(15);
Canvas canvasWatermark2 = new Canvas(over, pdfDoc.GetDefaultPageSize())
.ShowTextAligned(paragraph, 297, 500, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
canvasWatermark2.Close();
paragraph = new Paragraph("This TRANSPARENT watermark is added ON TOP OF the existing content")
.SetFont(font)
.SetFontSize(15);
over.SaveState();
// Creating a dictionary that maps resource names to graphics state parameter dictionaries
PdfExtGState gs1 = new PdfExtGState();
gs1.SetFillOpacity(0.5f);
over.SetExtGState(gs1);
Canvas canvasWatermark3 = new Canvas(over, pdfDoc.GetDefaultPageSize())
.ShowTextAligned(paragraph, 297, 450, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
canvasWatermark3.Close();
over.RestoreState();
pdfDoc.Close();
}
}
using iText.IO.Font;
using iText.IO.Font.Constants;
using iText.Kernel.Colors;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Extgstate;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
public class TransparentWatermark
{
public static readonly String DEST = "results/sandbox/stamper/transparent_watermark.pdf";
public static readonly String SRC = "../../../resources/pdfs/hero.pdf";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new TransparentWatermark().ManipulatePdf(DEST);
}
protected void ManipulatePdf(String dest)
{
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
PdfCanvas under = new PdfCanvas(pdfDoc.GetFirstPage().NewContentStreamBefore(), new PdfResources(), pdfDoc);
PdfFont font = PdfFontFactory.CreateFont(FontProgramFactory.CreateFont(StandardFonts.HELVETICA));
Paragraph paragraph = new Paragraph("This watermark is added UNDER the existing content")
.SetFont(font)
.SetFontSize(15);
Canvas canvasWatermark1 = new Canvas(under, pdfDoc.GetDefaultPageSize())
.ShowTextAligned(paragraph, 297, 550, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
canvasWatermark1.Close();
PdfCanvas over = new PdfCanvas(pdfDoc.GetFirstPage());
over.SetFillColor(ColorConstants.BLACK);
paragraph = new Paragraph("This watermark is added ON TOP OF the existing content")
.SetFont(font)
.SetFontSize(15);
Canvas canvasWatermark2 = new Canvas(over, pdfDoc.GetDefaultPageSize())
.ShowTextAligned(paragraph, 297, 500, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
canvasWatermark2.Close();
paragraph = new Paragraph("This TRANSPARENT watermark is added ON TOP OF the existing content")
.SetFont(font)
.SetFontSize(15);
over.SaveState();
// Creating a dictionary that maps resource names to graphics state parameter dictionaries
PdfExtGState gs1 = new PdfExtGState();
gs1.SetFillOpacity(0.5f);
over.SetExtGState(gs1);
Canvas canvasWatermark3 = new Canvas(over, pdfDoc.GetDefaultPageSize())
.ShowTextAligned(paragraph, 297, 450, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
canvasWatermark3.Close();
over.RestoreState();
pdfDoc.Close();
}
}
Imports iText.IO.Font
Imports iText.IO.Font.Constants
Imports iText.Kernel.Colors
Imports iText.Kernel.Font
Imports iText.Kernel.Pdf
Imports iText.Kernel.Pdf.Canvas
Imports iText.Kernel.Pdf.Extgstate
Imports iText.Layout
Imports iText.Layout.Element
Imports iText.Layout.Properties
Public Class TransparentWatermark
Public Shared ReadOnly DEST As String = "results/sandbox/stamper/transparent_watermark.pdf"
Public Shared ReadOnly SRC As String = "../../../resources/pdfs/hero.pdf"
Public Shared Sub Main(ByVal args() As String)
Dim file As New FileInfo(DEST)
file.Directory.Create()
Call (New TransparentWatermark()).ManipulatePdf(DEST)
End Sub
Protected Sub ManipulatePdf(ByVal dest As String)
Dim pdfDoc As New PdfDocument(New PdfReader(SRC), New PdfWriter(dest))
Dim under As New PdfCanvas(pdfDoc.GetFirstPage().NewContentStreamBefore(), New PdfResources(), pdfDoc)
Dim font As PdfFont = PdfFontFactory.CreateFont(FontProgramFactory.CreateFont(StandardFonts.HELVETICA))
Dim paragraph As Paragraph = (New Paragraph("This watermark is added UNDER the existing content")).SetFont(font).SetFontSize(15)
Dim canvasWatermark1 As Canvas = (New Canvas(under, pdfDoc.GetDefaultPageSize())).ShowTextAligned(paragraph, 297, 550, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0)
canvasWatermark1.Close()
Dim over As New PdfCanvas(pdfDoc.GetFirstPage())
over.SetFillColor(ColorConstants.BLACK)
paragraph = (New Paragraph("This watermark is added ON TOP OF the existing content")).SetFont(font).SetFontSize(15)
Dim canvasWatermark2 As Canvas = (New Canvas(over, pdfDoc.GetDefaultPageSize())).ShowTextAligned(paragraph, 297, 500, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0)
canvasWatermark2.Close()
paragraph = (New Paragraph("This TRANSPARENT watermark is added ON TOP OF the existing content")).SetFont(font).SetFontSize(15)
over.SaveState()
' Creating a dictionary that maps resource names to graphics state parameter dictionaries
Dim gs1 As New PdfExtGState()
gs1.SetFillOpacity(0.5F)
over.SetExtGState(gs1)
Dim canvasWatermark3 As Canvas = (New Canvas(over, pdfDoc.GetDefaultPageSize())).ShowTextAligned(paragraph, 297, 450, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0)
canvasWatermark3.Close()
over.RestoreState()
pdfDoc.Close()
End Sub
End Class
IronPDF 简单直观的 API 让用户可以快速将自定义水印应用到他们的 PDF 文件中,同时完全控制整个过程。它使用 HTML/CSS 进一步简化了过程,而不会失去对定制的控制。 iText 添加水印到 PDF 的方法需要更多的手动工作来完成任务,这可能会减慢进程。
有时需要在PDF页面上添加 盖章 将内容应用于 PDF 文件,就像需要在 PDF 文件上添加水印一样。现在我们将比较 IronPDF 和 iText 在 PDF 文档上加盖内容的表现。
IronPDF
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");
// Create image stamper
ImageStamper imageStamper = new ImageStamper(new Uri("https://ironpdf.com/img/svgs/iron-pdf-logo.svg"))
{
VerticalAlignment = VerticalAlignment.Top,
};
// Stamp the image stamper
pdf.ApplyStamp(imageStamper, 0);
pdf.SaveAs("stampImage.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");
// Create image stamper
ImageStamper imageStamper = new ImageStamper(new Uri("https://ironpdf.com/img/svgs/iron-pdf-logo.svg"))
{
VerticalAlignment = VerticalAlignment.Top,
};
// Stamp the image stamper
pdf.ApplyStamp(imageStamper, 0);
pdf.SaveAs("stampImage.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")
' Create image stamper
Dim imageStamper As New ImageStamper(New Uri("https://ironpdf.com/img/svgs/iron-pdf-logo.svg")) With {.VerticalAlignment = VerticalAlignment.Top}
' Stamp the image stamper
pdf.ApplyStamp(imageStamper, 0)
pdf.SaveAs("stampImage.pdf")
iText
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
public void StampPDF(string inputPdfPath, string outputPdfPath, string stampText)
{
PdfDocument pdfDoc = new PdfDocument(new PdfReader(inputPdfPath), new PdfWriter(outputPdfPath));
Document doc = new Document(pdfDoc);
// Add stamp (text) to each page
int numPages = pdfDoc.GetNumberOfPages();
for (int i = 1; i <= numPages; i++)
{
doc.ShowTextAligned(new Paragraph(stampText),
36, 36, i, iText.Layout.Properties.TextAlignment.LEFT,
iText.Layout.Properties.VerticalAlignment.TOP, 0);
}
doc.Close();
}
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
public void StampPDF(string inputPdfPath, string outputPdfPath, string stampText)
{
PdfDocument pdfDoc = new PdfDocument(new PdfReader(inputPdfPath), new PdfWriter(outputPdfPath));
Document doc = new Document(pdfDoc);
// Add stamp (text) to each page
int numPages = pdfDoc.GetNumberOfPages();
for (int i = 1; i <= numPages; i++)
{
doc.ShowTextAligned(new Paragraph(stampText),
36, 36, i, iText.Layout.Properties.TextAlignment.LEFT,
iText.Layout.Properties.VerticalAlignment.TOP, 0);
}
doc.Close();
}
Imports iText.Kernel.Pdf
Imports iText.Layout
Imports iText.Layout.Element
Public Sub StampPDF(ByVal inputPdfPath As String, ByVal outputPdfPath As String, ByVal stampText As String)
Dim pdfDoc As New PdfDocument(New PdfReader(inputPdfPath), New PdfWriter(outputPdfPath))
Dim doc As New Document(pdfDoc)
' Add stamp (text) to each page
Dim numPages As Integer = pdfDoc.GetNumberOfPages()
For i As Integer = 1 To numPages
doc.ShowTextAligned(New Paragraph(stampText), 36, 36, i, iText.Layout.Properties.TextAlignment.LEFT, iText.Layout.Properties.VerticalAlignment.TOP, 0)
Next i
doc.Close()
End Sub
IronPDF 可以帮助你在 PDF 上添加文本或图像,方式非常灵活和可定制;它让你完全掌控。这对于熟悉 HTML/CSS 的开发人员来说,理解和使用这个 API 非常容易。iText 使用图像和文本印章工具,为用户提供更多对 PDF 文件中显示内容的控制,尽管这个过程中可能会更为手动。
有时,您可能需要将 PDF 从一种格式转换为另一种格式。在这种情况下,我们正在查看 DOCX 转换为 PDF 比较 IronPDF 和 iText 如何在此过程中处理不同。
IronPDF
using IronPdf;
// Instantiate Renderer
DocxToPdfRenderer renderer = new DocxToPdfRenderer();
// Render from DOCX file
PdfDocument pdf = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx");
// Save the PDF
pdf.SaveAs("pdfFromDocx.pdf");
using IronPdf;
// Instantiate Renderer
DocxToPdfRenderer renderer = new DocxToPdfRenderer();
// Render from DOCX file
PdfDocument pdf = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx");
// Save the PDF
pdf.SaveAs("pdfFromDocx.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer As New DocxToPdfRenderer()
' Render from DOCX file
Private pdf As PdfDocument = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx")
' Save the PDF
pdf.SaveAs("pdfFromDocx.pdf")
iText
iText本身无法处理DOCX到PDF的转换;相反,它依赖于外部库,如DocX或Aspose.Words。
IronPDF为开发人员提供了一种处理DOCX到PDF转换任务的简单明了的工具,使得无需外部库即可轻松地将DOCX文件转换为PDF格式。而iText则需要依赖外部库来执行这项任务。
有关更详细的示例,请访问 IronPDF 示例.
IronPDF 有不同等级和额外功能的许可证供购买。开发者还可以购买 Iron Suite 这将让您以两个产品的价格获取所有IronSoftware的产品。如果您还没准备好购买许可证,IronPDF提供一个 免费试用 有效期为30天。
有关IronPDF文档和支持的更多详细信息,请访问 IronPDF文档 和 IronSoftware YouTube频道.
在 .NET 的 PDF 操作工具领域,IronPDF 和 iText 都提供了强大的功能,以满足各种开发需求。IronPDF 以其在 .NET Core、Framework 和 Standard 等平台上的简单集成而脱颖而出,同时还具备全面的功能,如 HTML 转 PDF 转换和高级安全选项。另一方面,iText 以其 Java 背景而闻名,为 PDF 的生成和操作提供了强大的工具,无论是开源还是商业许可,都强调了其多功能性和定制化。
最终在这些工具之间的选择取决于项目需求、许可偏好和所需的技术支持水平。无论是选择 IronPDF 的简单性和灵活性,还是选择功能广泛的开源 PDF 库 iText,开发人员都有充足的资源来有效简化其应用程序中的 PDF 工作流。