产品比较

IronPDF与ITextPDF的比较

Chipego
奇佩戈-卡琳达
2024年十二月16日
分享:

介绍

对于使用 PDF 的开发人员来说,拥有一个可靠的 PDF 生成和操作库至关重要。 在.NET生态系统中,两个受欢迎的PDF库脱颖而出——IronPDFiTextPdf——它们都提供了强大的工具来创建、编辑和管理PDF文档。 本文根据功能、文档质量和定价政策对这些库进行了深入比较。

IronPDF 和 iTextPdf 概述

IronPDF

IronPDF 是一个强大的 .NET PDF 管理库,与各种 .NET 环境兼容(Core 8, 7, 6, Framework 等)。 它提供全面的功能集,包括 HTML 到 PDF 的转换、合并 PDF、加密和数字签名。 IronPdf 的文档简单明了,用户可以获得可靠的技术支持。 开发人员经常通过 Stack Overflow 讨论和其他源代码共享平台找到常见问题的解决方案。

iTextPdf

iTextPdf 是 iText 库中用于 Java 和 .NET (C#) 的高级 PDF 库,专注于企业级文档处理。 该译本同时采用 AGPL 和商业许可证,为各种项目提供了灵活性。 iText 软件(如 iTextPdf)具有高度的可定制性,是文档加密、数字签名和表单创建等复杂 PDF 任务的理想选择。

跨平台兼容性

IronPDF和iTextPdf都支持跨平台功能,使它们在.NET中的各种应用需求中具有多功能性。 以下是每个库的兼容性明细。

IronPDF

  • .NET 版本:兼容 .NET Core (8, 7, 6, 5, 3.1+)、.NET Standard (2.0+) 和 .NET Framework (4.6.2+)。
  • 应用环境:无缝运行于Windows、Linux、Mac、Docker、Azure和AWS环境中。
  • 支持的集成开发环境(IDE):与微软 Visual Studio 和 JetBrains Rider & ReSharper 配合良好。
  • 操作系统与处理器:支持 Windows、Mac、Linux、x64、x86、ARM。

iTextPdf

  • .NET 版本:支持 .NET Core (2.x, 3.x)、.NET Framework (4.6.1+) 和 .NET 5+。
  • 应用环境:兼容 Windows、macOS、Linux 和 Docker。

主要功能比较:IronPDF 与 iTextPdf 的比较

以下是每个库提供的主要功能的详细比较。

IronPDF

  • HTML 到 PDF 转换:支持 HTML、CSS、JavaScript 和图像。
  • PDF 操作:拆分、合并和编辑 PDF 文档。
  • 安全:PDF加密和解密功能。
  • 编辑:允许添加注释、书签和大纲。
  • 模板:应用页眉、页脚和页码。
  • 水印:支持使用 HTML/CSS 控制的文本和图像水印。
  • PDF 盖章:将图像和文本印记添加到 PDF 文件中。

    有关 IronPDF 所提供的广泛功能集的更多信息,请访问 IronPDF 功能页面

iTextPdf

  • PDF 创建:支持从头开始创建 PDF 文档。
  • 表单:提供PDF表单的创建和编辑。
  • 数字签名:签署PDF文件。
  • 压缩:优化 PDF 文件大小。
  • 内容提取:从PDF文件中提取文本和图像。
  • 可定制性:高可定制性以适应复杂项目。

PDF 功能比较:IronPDF 与 iTextPdf 的比较

HTML 转换为 PDF

这两个库都支持 HTML 到 PDF 的转换,但在方法和易用性上有所不同。

IronPDF

using IronPdf;

// Instantiate Renderer
var renderer = new ChromePdfRenderer();

// Create a PDF from an HTML string
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
pdf.SaveAs("output.pdf");

// Advanced example with external assets
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
using IronPdf;

// Instantiate Renderer
var renderer = new ChromePdfRenderer();

// Create a PDF from an HTML string
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
pdf.SaveAs("output.pdf");

// Advanced example with external assets
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer = New ChromePdfRenderer()

' Create a PDF from an HTML string
Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
pdf.SaveAs("output.pdf")

' Advanced example with external assets
Dim myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\site\assets\")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
$vbLabelText   $csharpLabel

iTextPdf

using iText.Html2pdf;
using System.IO;

public class HtmlToPdf
{
    public static void ConvertHtmlToPdf()
    {
        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;
using System.IO;

public class HtmlToPdf
{
    public static void ConvertHtmlToPdf()
    {
        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
Imports System.IO

Public Class HtmlToPdf
	Public Shared Sub ConvertHtmlToPdf()
		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
End Class
$vbLabelText   $csharpLabel

IronPDF 提供了一种简单的方法进行HTML 转换为 PDF,包括对 HTML、CSS 和 JavaScript 的支持。 它允许用户直接从 HTML 字符串进行转换,或包含带有可选基本路径的资产。 iTextPdf 虽然有效,但需要几秒钟的额外设置,更侧重于基于文件的转换。

加密PDF文件

在安全性至关重要的场景中,加密是必不可少的。 以下是每个库的处理方法。

IronPDF

using IronPdf;

// Load an encrypted PDF or create a new one
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");

// Set document security settings
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key");
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.Password = "my-password";
pdf.SaveAs("secured.pdf");
using IronPdf;

// Load an encrypted PDF or create a new one
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");

// Set document security settings
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key");
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.Password = "my-password";
pdf.SaveAs("secured.pdf");
Imports IronPdf

' Load an encrypted PDF or create a new one
Private pdf = PdfDocument.FromFile("encrypted.pdf", "password")

' Set document security settings
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key")
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.Password = "my-password"
pdf.SaveAs("secured.pdf")
$vbLabelText   $csharpLabel

iTextPdf

using iText.Kernel.Pdf;
using System.Text;

public class EncryptPdf
{
    public static readonly String DEST = "encrypt_pdf.pdf";
    public static readonly String OWNER_PASSWORD = "World";
    public static readonly String USER_PASSWORD = "Hello";

    protected void ManipulatePdf(String dest)
    {
        PdfDocument document = new PdfDocument(new PdfReader("input.pdf"), new PdfWriter(dest,
            new WriterProperties().SetStandardEncryption(
                Encoding.UTF8.GetBytes(USER_PASSWORD),
                Encoding.UTF8.GetBytes(OWNER_PASSWORD),
                EncryptionConstants.ALLOW_PRINTING,
                EncryptionConstants.ENCRYPTION_AES_128)));
        document.Close();
    }
}
using iText.Kernel.Pdf;
using System.Text;

public class EncryptPdf
{
    public static readonly String DEST = "encrypt_pdf.pdf";
    public static readonly String OWNER_PASSWORD = "World";
    public static readonly String USER_PASSWORD = "Hello";

    protected void ManipulatePdf(String dest)
    {
        PdfDocument document = new PdfDocument(new PdfReader("input.pdf"), new PdfWriter(dest,
            new WriterProperties().SetStandardEncryption(
                Encoding.UTF8.GetBytes(USER_PASSWORD),
                Encoding.UTF8.GetBytes(OWNER_PASSWORD),
                EncryptionConstants.ALLOW_PRINTING,
                EncryptionConstants.ENCRYPTION_AES_128)));
        document.Close();
    }
}
Imports iText.Kernel.Pdf
Imports System.Text

Public Class EncryptPdf
	Public Shared ReadOnly DEST As String = "encrypt_pdf.pdf"
	Public Shared ReadOnly OWNER_PASSWORD As String = "World"
	Public Shared ReadOnly USER_PASSWORD As String = "Hello"

	Protected Sub ManipulatePdf(ByVal dest As String)
		Dim document As New PdfDocument(New PdfReader("input.pdf"), New PdfWriter(dest, (New WriterProperties()).SetStandardEncryption(Encoding.UTF8.GetBytes(USER_PASSWORD), Encoding.UTF8.GetBytes(OWNER_PASSWORD), EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_128)))
		document.Close()
	End Sub
End Class
$vbLabelText   $csharpLabel

IronPDF 的方法更为用户友好,提供简单的加密和对文档权限的控制。 iTextPdf 虽然有效,但需要进行详细设置,重点关注加密标准。

编辑 PDF 内容

对 PDF 文件中的信息进行再编辑对于保护隐私和安全至关重要。 以下是每个库支持此功能的方式。

IronPDF

using IronPdf;

PdfDocument pdf = PdfDocument.FromFile("novel.pdf");

// Redact 'are' from all pages
pdf.RedactTextOnAllPages("are");
pdf.SaveAs("redacted.pdf");
using IronPdf;

PdfDocument pdf = PdfDocument.FromFile("novel.pdf");

// Redact 'are' from all pages
pdf.RedactTextOnAllPages("are");
pdf.SaveAs("redacted.pdf");
Imports IronPdf

Private pdf As PdfDocument = PdfDocument.FromFile("novel.pdf")

' Redact 'are' from all pages
pdf.RedactTextOnAllPages("are")
pdf.SaveAs("redacted.pdf")
$vbLabelText   $csharpLabel

iTextPdf

using iText.Kernel.Pdf;
using iText.Kernel.Colors;

// Define areas to redact on each page
Rectangle[] rectanglesToRedact = { new Rectangle(100, 100, 200, 50) };

// Draw black rectangles to cover sensitive areas
using (PdfDocument pdfDoc = new PdfDocument(new PdfReader("input.pdf"), new PdfWriter("output_redacted.pdf")))
{
    for (int pageNum = 1; pageNum <= pdfDoc.GetNumberOfPages(); pageNum++)
    {
        PdfPage page = pdfDoc.GetPage(pageNum);
        PdfCanvas canvas = new PdfCanvas(page);
        foreach (Rectangle rect in rectanglesToRedact)
        {
            canvas.SetFillColor(ColorConstants.BLACK)
                  .Rectangle(rect.GetX(), rect.GetY(), rect.GetWidth(), rect.GetHeight())
                  .Fill();
        }
    }
}
using iText.Kernel.Pdf;
using iText.Kernel.Colors;

// Define areas to redact on each page
Rectangle[] rectanglesToRedact = { new Rectangle(100, 100, 200, 50) };

// Draw black rectangles to cover sensitive areas
using (PdfDocument pdfDoc = new PdfDocument(new PdfReader("input.pdf"), new PdfWriter("output_redacted.pdf")))
{
    for (int pageNum = 1; pageNum <= pdfDoc.GetNumberOfPages(); pageNum++)
    {
        PdfPage page = pdfDoc.GetPage(pageNum);
        PdfCanvas canvas = new PdfCanvas(page);
        foreach (Rectangle rect in rectanglesToRedact)
        {
            canvas.SetFillColor(ColorConstants.BLACK)
                  .Rectangle(rect.GetX(), rect.GetY(), rect.GetWidth(), rect.GetHeight())
                  .Fill();
        }
    }
}
Imports iText.Kernel.Pdf
Imports iText.Kernel.Colors

' Define areas to redact on each page
Private rectanglesToRedact() As Rectangle = { New Rectangle(100, 100, 200, 50) }

' Draw black rectangles to cover sensitive areas
Using pdfDoc As New PdfDocument(New PdfReader("input.pdf"), New PdfWriter("output_redacted.pdf"))
	Dim pageNum As Integer = 1
	Do While pageNum <= pdfDoc.GetNumberOfPages()
		Dim page As PdfPage = pdfDoc.GetPage(pageNum)
		Dim canvas As New PdfCanvas(page)
		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
$vbLabelText   $csharpLabel

IronPDF 提供了一个方便的删减工具,可以轻松隐藏所有页面上的敏感文本。 相比之下,iTextPdf 需要用户手动定义和应用黑色矩形来覆盖敏感区域。

签署PDF文件

自动签署 PDF 文档可以大大节省时间。下面是 IronPDF 和 iTextPdf 如何处理数字签名的并排比较。

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")
$vbLabelText   $csharpLabel

iTextPdf

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
$vbLabelText   $csharpLabel

当涉及到在 PDF 文件上应用数字签名时,IronPDF 提供了一种使用 X509 证书实现这一目标的简单而有效的方法。 它的 API 简化了流程,使其易于集成到工作流程中,同时又不影响对签名安全性的控制。 相比之下,iTextPDF 的文档签名流程设置更为复杂,但提供了更多自定义选项。 开发人员拥有更细粒度的控制权,不过他们在浏览 iTextPDF 的签名配置和证书处理时可能会面临更陡峭的学习曲线。

在 PDF 文档中应用水印

PDF 文件的水印对于品牌、保密和版权保护至关重要。 以下是 IronPDF 和 iTextPDF 如何在 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")
$vbLabelText   $csharpLabel

iTextPdf

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();

        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();

        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()

		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
$vbLabelText   $csharpLabel

IronPDF 的 API 通过灵活使用 HTML 和 CSS 进行自定义,使得快速和直观地应用水印成为可能。 另一方面,iTextPDF 允许通过更详细的配置选项高度自定义水印位置,但需要更多的编码工作。

在PDF上盖章图像和文字

在 PDF 上加盖内容类似于应用水印,但更侧重于添加特定元素,如图像或文本,以用于标签或品牌目的。 下面介绍 IronPDF 和 iTextPDF 如何完成这项任务。

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")
$vbLabelText   $csharpLabel

iTextPdf

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
$vbLabelText   $csharpLabel

IronPDF 的图像和文本印章方法简单而多样化,使开发人员能够轻松地向 PDF 页面添加品牌内容或标签。 API 利用熟悉的 HTML/CSS 风格元素,使定制变得简单。 iTextPDF 还提供图像和文本戳记功能,但其配置需要更多的手动设置和对 PDF 布局结构的工作知识。 iTextPDF 能够直接在 PDF 页面上对内容进行操作和排版,为开发人员提供了强大的印章工具,不过 iTextPDF 的设置可能需要更多的努力。

将DOCX转换为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")
$vbLabelText   $csharpLabel

iTextPDF

与 IronPdf 不同,iTextPDF 没有将 DOCX 转换为 PDF 的内置支持。 要进行这种转换,开发人员必须依赖 DocX 或 Aspose.Words 等第三方库,首先将 DOCX 文件转换为 PDF 兼容格式,然后再使用 iTextPDF 进行处理或修改。

IronPDF提供了一种简单的内置解决方案,用于DOCX到PDF的转换,无需额外的库。 因此,它非常适合需要快速综合方法的开发人员。 相比之下,iTextPDF 依靠外部库来转换 DOCX 文件,需要额外的设置和依赖性,这可能会增加项目的复杂性。

代码示例比较摘要

Itextpdf Alternative Html To Pdf Csharp 1 related to 代码示例比较摘要

有关更详细的示例,请访问IronPDF 示例

定价和许可:IronPDF 对比 iTextPdf 库

IronPDF 定价和许可

IronPDF拥有不同的级别和额外功能可用于购买许可证。 开发人员也可以购买Iron Suite,它以两个产品的价格为您提供使用所有 Iron Software 产品的权限。 如果您还未准备好购买许可证,IronPDF 提供免费试用

  • 永久许可证:提供多种永久许可证,具体取决于您的团队规模、项目需求和地点数量。 每种许可类型都包括电子邮件支持。
  • Lite License:该许可证费用为$749,支持一名开发人员、一个位置和一个项目。
  • Plus License:支持三位开发人员、三个地点和三个项目,这是从Lite License升级的下一步,费用为$1,499。Plus License除了提供基本的电子邮件支持外,还提供聊天支持和电话支持。
  • 专业许可证:此许可证适用于较大的团队,支持十位开发者、十个地点和十个项目,售价为$2,999。它提供与前一层级相同的联系方式支持,同时还提供屏幕共享支持。
  • 免版税重新分发:IronPDF 的许可还提供免版税重新分发保障,额外费用为 $1,999
  • 不中断的产品支持:IronPDF 提供持续产品更新、安全功能升级及其工程团队的支持,费用为 $999/年或一次性购买 $1,999,涵盖5年的支持。
  • Iron Suite:价格为 $1,498,您可以访问所有 Iron Software 产品,包括 IronPDF, IronOCR, IronWord, IronXL, IronBarcode, IronQR, IronZIP, IronPrint 和 IronWebScraper。

    Itextpdf Alternative Html To Pdf Csharp 2 related to IronPDF 定价和许可

iTextPDF 许可

  • AGPL 许可证:iTextPDF Core 库是开源的,遵循 AGPL 许可证,可以在特定条件下免费使用。 开发人员必须在相同许可下发布任何修改。
  • 商业许可证:对于不符合 AGPL 条件的开发者,iTextPDF 通过基于报价的模式提供商业许可。

文档和支持:IronPDF 与 iTextPdf 的比较

IronPDF

  • 全面的文档:涵盖所有功能的广泛且用户友好的文档。
  • 24/5 支持:提供活跃的工程师支持。
  • 视频教程:YouTube上提供了逐步视频指南。
  • 社区论坛:活跃社区以提供额外支持。
  • 定期更新:每月产品更新,以确保最新功能和安全补丁。

iTextPDF

iTextPDF 为其广泛的功能集提供了强大的文档和支持。

  • 文档:iText PDF 文档详细介绍了可用的功能。
  • 示例和教程:代码示例和教程帮助开发人员入门。
  • GitHub 社区: 开发者可以报告问题、提交拉取请求,并与 iTextPDF 团队互动。
  • 定期更新:iTextPDF 提供频繁的更新和改进。

    有关IronPDF文档和支持的更多详细信息,请访问IronPDF文档IronSoftware YouTube频道

结论

在.NET的PDF操作工具领域,IronPDF和iTextPDF都为开发人员提供了强大的解决方案。 IronPDF for .NET 凭借其跨 .NET 平台的简单集成以及 DOCX 到 PDF 的无外部依赖性转换等用户友好功能脱颖而出。 相比之下,iTextPDF 以其多功能性和丰富的功能集而著称,尽管在 DOCX 转换时需要额外的依赖性,但它仍然是一个强大的选择,尤其是在与其他工具结合使用时。

最终,在 IronPDF 和 iTextPDF 之间做出选择将取决于您项目的具体需求、许可偏好以及所需的支持水平。 这两个库都提供了在 .NET 应用程序中简化 PDF 工作流程的可靠方法。

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
IronPDF与PDFreactor的比较
下一步 >
IronPDF与GemBox.Pdf的比较