產品比較

IronPDF與ITextPDF的比較

Chipego
奇佩戈·卡林达
2024年12月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:與 Microsoft 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 vs. 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 佈局結構的工作知識。 直接在 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 vs. iTextPdf Library

IronPDF 價格和授權

IronPDF 提供不同等級的授權及額外的功能供購買。 開發人員也可以購買Iron Suite,只需支付兩個產品的價格即可使用所有Iron Software的產品。 如果您還沒有準備好購買許可證,IronPDF 提供一個免費試用

  • 永久許可證:根據您的團隊規模、專案需求和地點數量,提供一系列永久許可證。 每種授權類型均提供電子郵件支援。
  • Lite License:此授权费用为$749,支持一名开发人员、一个地点和一个项目。
  • Plus License: 支援三位開發人員、三個地點和三個項目,這是比 Lite License 更進一步的選擇,費用為 $1,499。Plus License 除了基本的電子郵件支援,還提供聊天支援和電話支援。
  • Professional License:此許可證適用於較大的團隊,支持十名開發人員、十個地點和十個項目,價格為 $2,999。它提供與先前層級相同的聯繫支持渠道,此外還提供螢幕共享支持。
  • 免版稅重發:IronPDF 的許可證還提供免版稅重發保障,額外收費 $1,999
  • 不中斷的產品支援:IronPDF 提供持續的產品更新、安全功能升級以及來自其工程團隊的支援,價格為每年 $999,或一次性支付 $1,999 即可獲得 5 年的保障。
  • Iron Suite:只需 $1,498,即可獲得包括 IronPDF、IronOCR、IronWord、IronXL、IronBarcode、IronQR、IronZIP、IronPrint 和 IronWebScraper 在內的所有 Iron Software 產品的訪問權限。

    Itextpdf Alternative Html To Pdf Csharp 2 related to IronPDF 價格和授權

iTextPDF 授權

  • AGPL 授權:iTextPDF Core library 是在 AGPL 授權下的開源軟體,可以在特定條件下免費使用。 開發者必須以相同的許可證發布任何修改。
  • 商業授權:對於不符合 AGPL 條件的開發者,iTextPDF 提供通過報價模式的商業授權。

文件與支持:IronPDF 與 iTextPdf

IronPDF

  • 全面的文件:涵蓋所有功能的詳細且易於使用的文件。
  • 24/5 支援:提供現役工程師支持。
  • 影片教學:在 YouTube 上提供逐步的影片指南。
  • 社區論壇:活躍的社群提供額外支持。
  • 定期更新:每月產品更新,確保最新功能和安全修補程式。

iTextPDF

iTextPDF 提供強大的文件和支援以涵蓋其廣泛的功能集。

  • 文件:iText PDF 文件全面涵蓋了可用的功能。
  • 範例和教程:代碼範例和教程幫助開發人員入門。
  • GitHub 社群:開發者可以回報問題、提交 pull requests,並與 iTextPDF 團隊互動。
  • 定期更新:iTextPDF 提供頻繁的更新和改進。

    有關 IronPDF 文件和支持的更多詳細資訊,請造訪IronPDF 文檔IronSoftware YouTube 頻道

結論

在 .NET 的 PDF 操作工具領域中,IronPDF 和 iTextPDF 都為開發人員提供了強大的解決方案。 IronPDF 在 .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之比較