跳至页脚内容
产品比较
IronPDF 与 iText7 进行 HTML 到 PDF 的比较

IronPDF与iText7之间的比较

优秀且简单的PDF操作工具可以简化创建和编辑PDF文档时涉及的许多任务和过程。 在.NET生态系统中,有两个受欢迎的库——IronPDF 和 iText——允许生成PDF而无需任何Adobe依赖。 它们都提供了一系列功能,如创建、编辑、转换等,但本文将重点根据三个标准比较这些库:它们所提供的功能、由它们提供的文档质量,以及这些公司为使用它们的产品而采用的定价政策。

IronPDF 和 iText 的概述

IronPDF 是一个突出的.NET PDF库,允许程序员轻松创建、修改和交互PDF文档。 它可以在不同的.NET环境中使用,包括Core、8、7、6 和 Framework,使其能够高度适应各种开发需求。 IronPDF的关键特性是其丰富的功能集,如HTML到PDF转换、合并PDF的能力、PDF加密和应用数字签名等。 文档的编写方式使用户可以毫无困难地理解,而该库本身具有强大的技术支持。

iText 是Java和.NET(C#)最受欢迎的PDF库之一。 iText Core 8 提供了企业级的可编程解决方案,用于创建和操作PDF文件。 iText支持许多不同的功能,并以开源(AGPL)许可证和商业许可证发布。 这意味着它可以通过其多功能性涵盖数字化转型项目中的广泛用例。

跨平台兼容性

IronPDF 和 iText 与多个平台兼容; 它们可以跨多个系统在.NET框架内处理PDF。 我们将在下文比较每个产品支持的框架和平台。

IronPDF:

IronPDF 支持的平台概述 支持广泛的平台和环境,确保在各种系统中无缝集成和部署:

  • .NET 版本:

    • .NET Core (8, 7, 6, 5, 和 3.1+)
    • .NET Standard (2.0+)
    • .NET Framework (4.6.2+)
  • 应用环境: IronPDF 在包括Windows、Linux、Mac、Docker、Azure 和 AWS 的应用环境中工作。

  • IDE:与 Microsoft Visual Studio、JetBrains Rider 和 ReSharper等IDE兼容。

  • 操作系统和处理器:支持多个不同的操作系统和处理器,包括Windows、Mac、Linux、x64、x86、ARM。

iText

  • .NET 版本:

    • .NET Core (2.x, 3.x)
    • .NET Framework (4.6.1+)
    • .NET 5+
  • 应用环境: iText 支持多种应用环境,得益于其对Java 和 .NET(C#)的支持,这些包括 Windows、Mac、Linux 和 Docker。

  • 操作系统:可在 Windows、macOS 和 Linux 操作系统上运行。

主要功能对比:IronPDF vs. iText

IronPDF 关键功能列表 和 iText 都提供了一系列用于处理PDF文件的功能和工具。 下一部分的重点是更仔细地检验其中的一些功能,看看这两个库在执行不同PDF相关任务方面如何比较。

IronPDF

  • HTML 到 PDF 转换: 支持 HTML、CSS、JavaScript 和图像。

  • PDF 文件操作:拆分和合并文档、更改格式和编辑现有PDF文档。

  • 安全性: PDF 加密和解密。

  • 编辑:添加注释、书签和大纲。

  • 模板:应用页眉、页脚和页码。

  • 水印:轻松将文本和图像水印应用到PDF文件中; 通过使用HTML/CSS获得完全控制。

  • PDF 盖章:使用IronPDF 将图像和文本盖章到你的PDF文档上。

有关IronPDF 提供的丰富功能集的更多信息,请访问IronPDF 功能页面

iText

  • PDF创建:支持从头创建PDF文档。

  • 表单:创建和编辑PDF表单。

  • 数字签名:对PDF文档签名。

  • 压缩:优化PDF文件大小。

  • 内容提取:从PDF中提取文本和图像。

  • 开源:可在AGPL 许可证下获得。

  • 可定制性: 高级用例的高水平定制。

IronPDF 与 iText 的 PDF 功能对比

HTML 到 PDF 转换

使用IronPDF将HTML内容转换为PDF是在许多不同的办公室和工作空间中执行的任务。 下文是比较IronPDF 和 iText 如何处理这一过程的代码示例。

IronPDF

using IronPdf;

// Configure security settings
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.
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
using IronPdf;

// Configure security settings
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.
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
$vbLabelText   $csharpLabel

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

在将HTML转换为PDF时,IronPDF 提供了一种简洁便捷的工具来完成这一任务。 利用ChromePdfRenderer 将HTML内容转换为PDF,IronPDF 在为用户提供完美的PDF文档方面表现出色。 用户可以从HTML字符串直接创建PDF,或使用可选的基本路径包含外部资源如图像,如高级示例中所示。 而iText则采取了一种基本的方法,使用其HtmlConverter类从HTML文件创建PDF文档。

加密PDF文件

使用IronPDF加密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
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
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");
$vbLabelText   $csharpLabel

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();
    }
}
$vbLabelText   $csharpLabel

IronPDF 为用户提供了一种简单的方法来加密PDF文件,同时还给用户大量控制,如编辑元数据和调整安全设置,如将文档设为只读或限制用户操作如复制和粘贴。 另一方面,iText 采用一种底层且较长的方法,在文档创建期间应用PDF加密,指定所有者和用户密码,以及使用加密标准(如AES-128)设置权限(如打印权利)。

编辑 PDF 内容

在处理机密或私人信息时,有时可能需要屏蔽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");
$vbLabelText   $csharpLabel

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) }; // 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) }; // 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();
        }
    }
}
$vbLabelText   $csharpLabel

IronPDF 的 屏蔽工具简洁易用,只需几行代码即可简化屏蔽过程。 这提升了 PDF 屏蔽任务效率,并为用户简单保护敏感数据提供了方法. 另一方面,iText 并没有提供一个与IronPDF一样的内置屏蔽工具。 然而,它仍然可以使用上述方法覆盖用户希望屏蔽的内容来覆盖敏感数据。 这可能导致潜在问题,因为这些矩形实际上并没有移除或适当屏蔽文本,意味着其他人可能会复制和粘贴被屏蔽的数据。

签名PDF文件

能够使用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");
$vbLabelText   $csharpLabel

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

在对PDF文件进行数字签名时,IronPDF提供了一种简洁而有力的工具来完成这项过程。 其简便性让该过程可以快速完成,为需要实现签名的开发者节省了时间。 iText 需要更长、更复杂的过程来将数字签名应用到PDF文件中。 虽然他们能够使用不同的接口选项和密钥为用户提供更多控制,但这种工具执行此任务的复杂性可能会阻碍其使用。

在PDF文件中应用水印

能够添加和个性化 PDF 文件上的水印与 IronPDF 在涉及机密性、版权保护、品牌化或其他与敏感信息相关的任务方面具有很大帮助。 以下是 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");
$vbLabelText   $csharpLabel

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

        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();
    }
}
$vbLabelText   $csharpLabel

IronPDF 的简单直观 API 让用户快速地在他们的 PDF 文件上应用自定义水印,过程完全可控。 它使用 HTML/CSS 进一步简化了这一过程,并没有失去任何自定义控制。 iText 的方法则需要更多手动工作,可能会拖慢整个过程。

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

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();
}
$vbLabelText   $csharpLabel

IronPDF 可以帮助您以多才多艺和可定制的方式将文本或图像添加到PDF上,提供完全控制。 其 API 易于理解和使用,特别适合熟悉 HTML/CSS 的开发者。 iText 使用其图像和文本盖章工具为用户提供对显示在 PDF 文件上的内容更大的控制,尽管这个过程可能变得更加手动。

将DOCX转换为PDF

有时,您可能需要从一种格式转换为另一种格式。 在本例中,我们正在研究IronPDF 的 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");
$vbLabelText   $csharpLabel

iText

iText 本身无法处理 DOCX 到 PDF 的转换; 相反,它依赖于外部库,如 DocX 或 Aspose.Words。

IronPDF 为开发人员提供了一种简单且简洁的工具来处理 DOCX 到 PDF 的转换任务,使其无需外部库即可轻松地将 DOCX 文件转换为 PDF 格式。 iText ,另一方面,依靠外部库来执行此任务。

代码示例比较总结

iText C# HTML到PDF的替代方案

有关更详细的示例,请访问 IronPDF 创建PDF的HTML示例

支持 Bootstrap 和现代 CSS 框架

在实际开发过程中,一个关键的考虑因素是每个库对现代CSS框架的处理能力。 Bootstrap、Tailwind CSS 和 Foundation 作为大多数现代Web应用程序的基础,框架兼容性可以显著影响您的开发工作流和输出质量。

IronPDF。:完整的现代框架支持

IronPDF的 Chrome 渲染引擎提供了对所有现代 CSS 框架的完整、生产准备支持:

  • Bootstrap 5:所有布局均原生支持 flexbox 和 CSS Grid
  • Tailwind CSS:完全支持实用性优先框架 现代 CSS3:变换、动画、自定义属性和高级选择器 -框架验证:成功渲染Bootstrap 首页Bootstrap 模板

代码示例:Bootstrap 进度指示器

using IronPdf;

var renderer = new ChromePdfRenderer();

string bootstrap ProgressBars = @"
<!DOCTYPE html>
<html>
<head>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
</head>
<body>
    <div class='container my-5'>
        <h2 class='mb-4'>Project Progress Dashboard</h2>

        <div class='mb-4'>
            <div class='d-flex justify-content-between mb-1'>
                <span>Backend Development</span>
                <span class='text-success fw-bold'>85%</span>
            </div>
            <div class='progress' style='height: 25px;'>
                <div class='progress-bar progress-bar-striped bg-success' role='progressbar'
                     style='width: 85%' aria-valuenow='85' aria-valuemin='0' aria-valuemax='100'>
                </div>
            </div>
        </div>

        <div class='mb-4'>
            <div class='d-flex justify-content-between mb-1'>
                <span>Frontend UI</span>
                <span class='text-warning fw-bold'>60%</span>
            </div>
            <div class='progress' style='height: 25px;'>
                <div class='progress-bar progress-bar-animated bg-warning' role='progressbar'
                     style='width: 60%' aria-valuenow='60' aria-valuemin='0' aria-valuemax='100'>
                </div>
            </div>
        </div>

        <div class='mb-4'>
            <div class='d-flex justify-content-between mb-1'>
                <span>Testing & QA</span>
                <span class='text-info fw-bold'>40%</span>
            </div>
            <div class='progress' style='height: 25px;'>
                <div class='progress-bar bg-info' role='progressbar'
                     style='width: 40%' aria-valuenow='40' aria-valuemin='0' aria-valuemax='100'>
                </div>
            </div>
        </div>
    </div>
</body>
</html>";

var pdf = renderer.RenderHtmlAsPdf(bootstrapProgressBars);
pdf.SaveAs("project-progress.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

string bootstrap ProgressBars = @"
<!DOCTYPE html>
<html>
<head>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
</head>
<body>
    <div class='container my-5'>
        <h2 class='mb-4'>Project Progress Dashboard</h2>

        <div class='mb-4'>
            <div class='d-flex justify-content-between mb-1'>
                <span>Backend Development</span>
                <span class='text-success fw-bold'>85%</span>
            </div>
            <div class='progress' style='height: 25px;'>
                <div class='progress-bar progress-bar-striped bg-success' role='progressbar'
                     style='width: 85%' aria-valuenow='85' aria-valuemin='0' aria-valuemax='100'>
                </div>
            </div>
        </div>

        <div class='mb-4'>
            <div class='d-flex justify-content-between mb-1'>
                <span>Frontend UI</span>
                <span class='text-warning fw-bold'>60%</span>
            </div>
            <div class='progress' style='height: 25px;'>
                <div class='progress-bar progress-bar-animated bg-warning' role='progressbar'
                     style='width: 60%' aria-valuenow='60' aria-valuemin='0' aria-valuemax='100'>
                </div>
            </div>
        </div>

        <div class='mb-4'>
            <div class='d-flex justify-content-between mb-1'>
                <span>Testing & QA</span>
                <span class='text-info fw-bold'>40%</span>
            </div>
            <div class='progress' style='height: 25px;'>
                <div class='progress-bar bg-info' role='progressbar'
                     style='width: 40%' aria-valuenow='40' aria-valuemin='0' aria-valuemax='100'>
                </div>
            </div>
        </div>
    </div>
</body>
</html>";

var pdf = renderer.RenderHtmlAsPdf(bootstrapProgressBars);
pdf.SaveAs("project-progress.pdf");
$vbLabelText   $csharpLabel

iText7:有限的框架支持

iText7 使用自定义的 HTML 到 PDF 转换器(pdfHTML),在现代 CSS 框架上存在显著限制:

-无法执行 JavaScript:无法处理动态 Bootstrap 组件

  • Flexbox 支持有限: Bootstrap 4+ 布局经常无法正确渲染(v7.1.15 仅部分支持) -不支持 CSS Grid:现代基于网格的布局将无法正常工作。 -需要手动预处理:复杂的布局需要使用 Selenium 或 Puppeteer 等外部工具。

根据 iText 的官方文档,建议开发者:

  1. 避免复杂的 CSS 布局,包括 flexbox
  2. 使用表格布局而不是现代网格系统
  3. 将 Bootstrap 组件简化为基础 HTML
  4. 进行彻底测试,因为框架兼容性有限

实际影响:如果您的应用程序使用 Bootstrap 作为其用户界面,并且您需要导出与 Web 设计相匹配的 PDF,则 iText7 需要对 HTML/CSS 进行大量重新设计才能生成 PDF,或者需要与外部浏览器自动化工具集成,这将大大增加复杂性和开发时间。

有关CSS框架兼容性的综合信息,请参阅Bootstrap & Flexbox CSS 指南

定价和授权:IronPDF vs. iText库

IronPDF。 定价和许可

IronPDF 授权选项提供了不同的级别和额外功能来购买授权。 开发人员还可以购买[Iron Suite](Iron Suite),以两倍价格获得 Iron Software 的所有产品。 如果您还不准备购买授权,IronPDF 提供一个免费试用版,为期30天。

  • 永久授权: 提供不同的永久授权,具体取决于您的团队规模、项目需求和地点数量。 每种许可证类型都配有电子邮件支持。

  • Lite许可证: 支持一名开发者、一个地点和一个项目。

  • Plus许可证:其支持三位开发者、三个地点和三个项目,价格为 $1,199。 Plus 许可证提供聊天、电话和电子邮件支持。

  • 专业许可证: 适合更大的团队,支持十名开发者、十个地点和十个项目,价格为 $2,399。 \u5b83\u63d0\u4f9b\u4e0e\u4e4b\u524d\u5c42\u6b21\u76f8\u540c\u7684\u8054\u7cfb\u652f\u6301\u6e20\u9053\uff0c\u4f46\u4e5f\u63d0\u4f9b\u5c4f\u5e55\u5171\u4eab\u652f\u6301\u3002<\/S>

  • 免版税再分发: IronPDF 还提供免版税再分发保障,额外收费为 $2,399。

  • 不间断产品支持: 以年费 $1,199 或一次性购买 $2,399获取5年覆盖,获取持续的产品更新、安全功能升级和工程团队的支持。

  • Iron Suite: 以 $1,498 的价格,您将获得Iron Software产品的全面访问,包括IronPDF、IronOCR、IronWord、IronXL、IronBarcode、IronQR、IronZIP、IronPrint 和 IronWebScraper。

IronPDF 授权对比

iText 授权

  • AGPL许可证:iText Core 库是开源的,用户可免费使用。 要在此许可模式下使用iText,用户必须遵守其条款,并且根据AGPL许可模式对iText的任何修改必须也释放。

  • 商业许可:对于那些项目不符合AGPL条款的开发者,iText 提供商业授权模式,定价基于报价。

文档和支持:IronPDF vs. iText

IronPDF。

  • 完整文档:全面且用户友好的文档,涵盖所有功能。

  • 24/5 支持:提供工程师的积极支持。

  • 视频教程:在 YouTube 上提供逐步视频指南。

  • 社区论坛:活跃的社区提供额外支持。

  • 常规更新:每月更新产品,包含最新功能和安全补丁。

iText

  • 文档:涵盖 iText 软件功能的深入文档。

  • 示例和教程: 提供针对各种功能的教程和代码示例。

  • GitHub:开发人员可以提交任何问题或错误给iText的GitHub存储库,并与iText团队沟通。

  • 更新:iText 提供定期更新和改进。

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

结论

在.NET的PDF操作工具领域,IronPDF和iText都提供了强大的功能,满足各种开发需求。 IronPDF因其在.NET Core、Framework和Standard等平台上的简便集成而脱颖而出,同时提供丰富的功能,例如HTML到PDF转换和高级安全选项。 另一方面,iText 以其在 Java 中的传统而著名,提供了在开源和商业许可下的强大 PDF 生成和操作工具,强调多功能性和定制性。

在这些工具之间进行选择最终取决于项目要求、许可偏好和所需的技术支持水平。 无论是选择IronPDF的简单性和灵活性,还是选择作为开源PDF库iText的丰富功能,开发人员都有足够的资源来有效地优化其应用程序中的PDF工作流程。

您可以尝试30天免费试用,了解其可用功能。

请注意iText 是其各自所有者的注册商标。 本网站不与iText有任何从属关系、认可或赞助。 所有产品名称、徽标和品牌均为各自所有者的财产。 比较仅供参考,反映的是撰写时的公开信息。

常见问题解答

如何在C#中将HTML转换为PDF?

你可以使用IronPDF的RenderHtmlAsPdf方法将HTML字符串转换为PDF。你还可以使用RenderHtmlFileAsPdf将HTML文件转换为PDF。

IronPDF 和 iText 之间的主要区别是什么?

IronPDF 因其易用性、全面的文档和强大的技术支持而受到称赞,使其成为开发人员的用户友好选项。而 iText 虽然功能强大,但通常需要更多的手动工作,并且在开源 (AGPL) 和商业许可下可用。

PDF 库的许可选项有哪些?

IronPDF 提供各种永久许可证和免版税选项,而 iText 提供免费的 AGPL 许可证和适用于不合规项目的商业选项。

哪个 PDF 库为开发人员提供更好的支持?

IronPDF 提供全面的文档、24/5 的工程支持和一个活跃的社区论坛,确保开发人员可以获得最新的资源和帮助。

IronPDF 兼容不同的 .NET 环境吗?

是的,IronPDF 兼容 .NET Core、.NET Standard 和 .NET Framework,并可以在 Windows、Linux、Mac、Docker、Azure 和 AWS 等环境中使用。

IronPDF 如何处理 PDF 加密?

IronPDF 提供一个简单的 API 来加密 PDF,使用户可以轻松编辑元数据和调整安全设置,从而确保文档安全和合规性。

IronPDF 可以执行 DOCX 到 PDF 的转换吗?

是的,IronPDF 擅长于 DOCX 到 PDF 的转换,提供了一个直接且高效的过程,无需外部库,从而简化了应用程序内的文档转换任务。

IronPDF 在 HTML 到 PDF 转换方面有什么突出的特点?

IronPDF 使用 ChromePdfRenderer 进行 HTML 到 PDF 转换,允许轻松集成 HTML、CSS 和 JavaScript,确保网页内容精确地渲染到 PDF 中。

IronPDF 和 iText 在跨平台兼容性方面如何比较?

两个库都支持多种操作系统和环境,但 IronPDF 为 HTML 到 PDF 转换和 PDF 加密等任务提供了更流畅的体验。

IronPDF 提供的关键功能有哪些?

IronPDF 提供的功能包括 HTML 到 PDF 转换、PDF 文件操作、加密和解密、编辑功能、添加水印、PDF 压印和数字签名。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

iText Logo

厌倦了昂贵的续订和过时的产品更新?

借助我们的技术迁移支持和更优惠的方案,轻松从iText切换而来。

IronPDF Logo