跳過到頁腳內容
產品比較

Compdfkit與IronPDF之間的比較

PDF,即Portable Document Format,是Adobe创建的一种文件类型,以确保共享文档时的格式一致性。 此格式在不同设备和操作系统上保持布局、文本和图像的一致性。 PDF以其安全性、互动功能和紧凑的大小而闻名,非常适合分发文档而不更改原始内容。

对于使用C#的开发人员,PDF库提供了处理PDF文件的PDF解决方案。 这些库支持文档创建、内容修改以及文本和图像的提取。 它们还支持表单处理、数字签名和跨不同平台的兼容性等功能。 这些库设计为实现最佳性能,使PDF处理更高效。

In this article, we will compare two C# PDF libraries: IronPDF and ComPDFKit. 此比较将涵盖功能、功能性、代码示例和许可。 通过检查这些方面,你可以确定哪个库最适合你的PDF相关项目。

1. ComPDFKit SDK

Compdfkit与IronPDF的比较:图1 - ComPDFKIT SDK主页

ComPDFKit PDF SDK是一个强大的C# PDF SDK,允许开发人员将全面的PDF功能集成到他们的应用程序中。 此库支持处理PDF文档所需的大量PDF功能。 其设计旨在用于各种环境,包括网络、桌面和移动平台,使其成为开发人员在跨平台项目中工作的多功能工具。 在示例解决方案中有多个函数。 你可以选择任何想要尝试的相关ComPDFKit PDF SDK函数。

1.1 ComPDFKit的主要功能

  1. PDF查看:ComPDFKit提供了强大的PDF查看器,允许用户高保真度地查看PDF文档。 查看器支持平滑滚动、缩放和导航,确保无缝的用户体验。
  2. 注释:该库包括工具以便平滑地集成PDF注释功能。 用户可以为文本加亮显示、添加注释,并创建各种类型的注释,这对于协作工作流至关重要。
  3. 表单处理:该库提供广泛的互动表单支持。 开发人员可以创建、填写和从PDF表单中提取数据,使其成为需要表单处理的应用程序的理想选择。
  4. PDF编辑:ComPDFKit允许广泛的PDF编辑功能,包括修改PDF文件中的文本、图像和其他内容。 此功能对于需要更新或定制现有PDF文档的应用程序非常有用。
  5. 转换:该库支持将PDF文件转换为各种格式,如Word、Excel、PowerPoint和图像,以及反向转换。 这种灵活性对需要将PDF内容转用于不同用途的应用程序来说至关重要。
  6. 安全性:ComPDFKit包括强大的安全功能,如加密和权限管理。 开发人员可以保护PDF文档以防止未经授权的访问,保护敏感信息。
  7. 光学字符识别(OCR):该库包括OCR功能,将扫描的文档转换为可编辑和可搜索的PDF。 此功能对纸质文件的数字化和电子化无障碍访问至关重要。

ComPDFKit提供了一套全面的API,简化了这些功能在各种应用程序中的集成。 其广泛的文档和支持使其成为希望在项目中集成高级PDF功能的开发人员的绝佳选择。

2. IronPDF库

Compdfkit与IronPDF的比较:图2 - IronPDF主页

IronPDF是一个适用于.NET的多功能PDF库,允许开发人员使用C#创建、编辑和管理PDF文档。 它提供全面的PDF功能。 它的设计简化了PDF的生成,通过从HTML、CSS、JavaScript和各种图像格式渲染PDF。 这使其成为希望将强大PDF功能集成到其.NET应用程序中的开发人员的理想工具。

IronPDF的核心特性

  1. HTML到PDF转换:IronPDF在将HTML、CSS和JavaScript内容转换为高质量PDF文档方面表现出色。 此功能支持HTML字符串到PDF、URL、ASPX webforms和MVC视图,使其成为多种网页内容的灵活解决方案。
  2. PDF编辑:该库提供广泛的编辑功能,包括添加、复制和删除页面,合并和拆分PDF,以及操作文本和图像。 开发人员还可以为PDF文档添加页眉、页脚、水印和数字签名。
  3. 表单处理:IronPDF支持智能表单创建和以编程方式填写PDF表单。 此功能对于需要动态生成表单和从用户提交的表单中提取数据的应用程序至关重要。
  4. 安全功能:IronPDF提供了强大的安全选项,如设置密码和权限、加密文档、添加数字签名。 这些功能确保PDF文档中的敏感信息受到保护,防止未经授权的访问。
  5. OCR和数据提取:该库包括光学字符识别(OCR)功能,允许将扫描的文档转换为可编辑和可搜索的PDF。 此外,IronPDF还可以从现有PDF中提取文本、图像和其他数据,方便了内容重用和分析。
  6. 图像转换:IronPDF支持将各种图像格式(包括JPG、PNG、GIF、BMP和SVG)转换为PDF文档。 它还提供将PDF页面呈现为图像的能力,对于需要PDF内容视觉预览的应用程序非常有用。
  7. 跨平台兼容性:IronPDF与多个.NET平台兼容,包括.NET Core、.NET Framework和.NET Standard。 它支持在Windows、Linux、macOS和Azure上部署,使其成为在不同环境中工作的开发人员的多才多艺选择。
  8. 性能优化:该库设计为高性能,支持多线程和异步操作。 这确保了即使在工作负载较高的应用程序中也能高效执行PDF处理任务。
  9. 全面的文档和支持:IronPDF提供详细的文档和大量的代码示例,使开发人员可以轻松入门并实现其功能。 此外,它还提供技术支持,以帮助解决开发过程中可能出现的问题。

3. 创建新的Visual Studio项目

在我们深入代码示例之前,让我们创建一个新的Visual Studio项目。 这里有一个关于如何在Visual Studio中建立C#控制台应用的分步指南。

步骤1:安装Visual Studio(如果尚未安装)

Visual Studio是进行C#项目的最佳IDE。 如果你还没有下载并安装它,可以从这个Visual Studio下载页面下载。

步骤2:打开Visual Studio

安装Visual Studio后,打开它。 如果你有Visual Studio Community,你可以选择登录或不登录继续。

步骤3:创建新项目

  1. 点击“创建新项目”或导航到文件 > 新建 > 项目。

    Compdfkit与IronPDF的比较:图3 - IronPDF与DinkToPdf的比较:图1

  2. 在搜索栏中搜索控制台应用,并从搜索结果中选择控制台应用程序。

    Compdfkit与IronPDF的比较:图4 - IronPDF与DinkToPdf的比较:图2 - 在创建新项目对话框中选择C#控制台应用并点击下一步。

  3. 选择最符合你需求的项目模板。 对于基本控制台应用程序,你可以选择“控制台应用程序(.NET Framework)”。
  4. 提供项目的名称和保存位置。 你也可以设置解决方案名称。
  5. 选择合适的目标框架,并点击“创建”以生成你的项目。

4. 安装IronPDF

通过多种方法可以将IronPDF集成到你的项目中,每种方法都提供无缝的设置体验。

  1. 若要使用Visual Studio NuGet包管理器,首先右键单击解决方案中的“Dependencies”并选择“管理NuGet包”。在“浏览”选项卡中搜索“IronPDF”并为你的项目安装最新版本。

    Compdfkit与IronPDF的比较:图5 - 使用NuGet包管理器搜索IronPDF

  2. 或者,你可以使用NuGet包管理器控制台。 通过在Visual Studio中导航到工具 > NuGet包管理器 > 包管理器控制台打开控制台。 控制台打开后,执行命令:

    Install-Package IronPdf

    这种方式提供了一种通过简单命令行快速安装库的方式。

    Compdfkit与IronPDF的比较:图6 - 使用命令行输入上面的指令

  3. 对于那些喜欢直接从NuGet网站下载的人,请访问IronPDF NuGet包页面。 从那里,你可以下载包文件。下载后,双击该文件将其添加到你的项目中,然后重新加载解决方案以完成集成。
  4. 另一种方法是直接下载最新版本的IronPDF。 这确保你获取到最新的包。 按照网站上提供的说明手动将IronPDF集成到你的Visual Studio项目中。

通过这些方法中的任一种,你都可以有效地将IronPDF集成到.NET项目中。

5. 安装ComPDFKit C#

有两种主要方法将ComPDFKit添加到你的项目中:使用NuGet包管理器或本地包。

5.1 使用NuGet包管理器

  1. 打开NuGet包管理器:在解决方案资源管理器中,右键单击“引用”,选择“管理NuGet包”。
  2. 搜索并安装:在NuGet包管理器中搜索“ComPDFKit”。 选择合适的包(如ComPDFKit.NetFrameworkComPDFKit.Conversion.NetFramework)并点击“安装”。

Compdfkit与IronPDF的比较:图7 - 使用NuGet包管理器搜索ComPDFKit

  1. 验证安装:确保包出现在解决方案资源管理器的“引用”下。

5.2 使用本地包

  1. 下载包:从正式的ComPDFKit网站获取ComPDFKit.NetFramework.nupkg文件。
  2. 配置NuGet源:在你的项目目录中创建或编辑一个nuget.config文件以包含本地包的路径。

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <packageSources>
            <add key="ComPDFKitSource" value="path\to\directoryContainingNupkg" />
        </packageSources>
    </configuration>
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <packageSources>
            <add key="ComPDFKitSource" value="path\to\directoryContainingNupkg" />
        </packageSources>
    </configuration>
    XML
  3. 安装本地包:重新打开你的解决方案,在Visual Studio中转到“管理NuGet包”,选择你的本地包源。 从本地源安装ComPDFKit包。

5.3 应用许可证密钥

  1. 获取许可证:联系ComPDFKit团队,获取试用或完整许可证。
  2. 在代码中应用许可证

    bool LicenseVerify()
    {
        if (!CPDFSDKVerifier.LoadNativeLibrary())
            return false;
        LicenseErrorCode verifyResult = CPDFSDKVerifier.LicenseVerify("input your license here");
        return (verifyResult == LicenseErrorCode.E_LICENSE_SUCCESS);
    }
    bool LicenseVerify()
    {
        if (!CPDFSDKVerifier.LoadNativeLibrary())
            return false;
        LicenseErrorCode verifyResult = CPDFSDKVerifier.LicenseVerify("input your license here");
        return (verifyResult == LicenseErrorCode.E_LICENSE_SUCCESS);
    }
    IRON VB CONVERTER ERROR developers@ironsoftware.com
    $vbLabelText   $csharpLabel

    在你的主应用程序文件中添加此方法以验证许可证。

通过遵循这些步骤,你可以成功将ComPDFKit集成到你的C#项目中。

6. HTML到PDF

将HTML转换为PDF是许多应用程序中的常见需求,例如从网页内容动态生成报告、发票或文档。 IronPDF和ComPDFKit均为此任务提供了强大的解决方案,但其方法和能力显著不同。

此过程通常从捕获HTML内容开始,该内容可以是静态的或动态生成的。 然后处理捕获的HTML以应用任何相关的样式表(CSS)和脚本(JavaScript),这确保了最终的PDF镜像原始网页的外观和行为。

6.1 使用IronPDF转换HTML为PDF

IronPDF是一个在C#中将HTML转换为PDF的多功能库。 它使用基于Chrome的渲染引擎来确保高质量的输出。 此过程涉及将HTML、CSS和JavaScript内容准确地渲染为PDF格式。 以下是如何使用IronPDF将HTML字符串转换为PDF文件的基本示例:

using IronPdf;
using System;

class Program
{
    static void Main()
    {
        // Define your HTML string
        string htmlString = @"
            <h1>Hello, IronPDF!</h1>
            <p>This is a simple PDF created from an HTML string.</p>";

        var renderer = new ChromePdfRenderer();
        // Convert the HTML string to a PDF document
        PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlString);
        // Save the PDF document to a file
        string outputPath = "sample.pdf";
        pdf.SaveAs(outputPath);
        Console.WriteLine($"PDF created successfully and saved to {outputPath}");
    }
}
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        // Define your HTML string
        string htmlString = @"
            <h1>Hello, IronPDF!</h1>
            <p>This is a simple PDF created from an HTML string.</p>";

        var renderer = new ChromePdfRenderer();
        // Convert the HTML string to a PDF document
        PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlString);
        // Save the PDF document to a file
        string outputPath = "sample.pdf";
        pdf.SaveAs(outputPath);
        Console.WriteLine($"PDF created successfully and saved to {outputPath}");
    }
}
Imports IronPdf
Imports System

Friend Class Program
	Shared Sub Main()
		' Define your HTML string
		Dim htmlString As String = "
            <h1>Hello, IronPDF!</h1>
            <p>This is a simple PDF created from an HTML string.</p>"

		Dim renderer = New ChromePdfRenderer()
		' Convert the HTML string to a PDF document
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlString)
		' Save the PDF document to a file
		Dim outputPath As String = "sample.pdf"
		pdf.SaveAs(outputPath)
		Console.WriteLine($"PDF created successfully and saved to {outputPath}")
	End Sub
End Class
$vbLabelText   $csharpLabel

Compdfkit与IronPDF的比较:图8 - 上述代码的示例输出

同样,你也可以从HTML文件创建PDF。有时HTML字符串太大并且需要添加CSS,此功能非常有帮助。 IronPDF通过提供一种方法直接将HTML文件及其CSS和JS文件转换为PDF文档来帮助实现这一目标。

using IronPdf;
using System;

class Program
{
    static void Main()
    {
        var renderer = new ChromePdfRenderer();
        // Convert the HTML file to a PDF document
        PdfDocument pdf = renderer.RenderHtmlFileAsPdf("index.html");
        // Save the PDF document to a file
        string outputPath = "HTML File.pdf";
        pdf.SaveAs(outputPath);
        Console.WriteLine($"PDF created successfully and saved to {outputPath}");
    }
}
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        var renderer = new ChromePdfRenderer();
        // Convert the HTML file to a PDF document
        PdfDocument pdf = renderer.RenderHtmlFileAsPdf("index.html");
        // Save the PDF document to a file
        string outputPath = "HTML File.pdf";
        pdf.SaveAs(outputPath);
        Console.WriteLine($"PDF created successfully and saved to {outputPath}");
    }
}
Imports IronPdf
Imports System

Friend Class Program
	Shared Sub Main()
		Dim renderer = New ChromePdfRenderer()
		' Convert the HTML file to a PDF document
		Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("index.html")
		' Save the PDF document to a file
		Dim outputPath As String = "HTML File.pdf"
		pdf.SaveAs(outputPath)
		Console.WriteLine($"PDF created successfully and saved to {outputPath}")
	End Sub
End Class
$vbLabelText   $csharpLabel

Compdfkit与IronPDF的比较:图9 - 上述代码输出示例,利用IronPDF呈现HTML为PDF

IronPDF还支持将URL到PDF和HTML文件转换为PDF。 这些功能在需要文档管理的软件中非常有用。 IronPDF为PDF的创建和操作提供了广泛的功能,使其成为开发人员的强大工具。

6.2 使用ComPDFKit C#进行 HTML到PDF转换

ComPDFKit在其C# SDK中不直接支持HTML到PDF转换。 相反,它提供了一个专门用于此目的的单独API。 此API允许你通过向其服务发送HTTP请求进行HTML到PDF转换。

要使用ComPDFKit HTML到PDF API,你通常需要遵循以下步骤:

  1. 发送HTML内容:创建HTTP POST请求向ComPDFKit API端点发送你的HTML内容。
  2. 接收PDF输出:API处理HTML内容并返回生成的PDF文件。

以下是你可能在C#中构建这样一个请求的示例:

using System;
using System.Net.Http;
using System.Threading.Tasks;

public class HtmlToPdfExample
{
    public static async Task ConvertHtmlToPdfAsync()
    {
        using (var client = new HttpClient())
        {
            var content = new StringContent("<h1>Hello World</h1>");
            var response = await client.PostAsync("https://api.compdfkit.com/html-to-pdf", content);
            var pdfBytes = await response.Content.ReadAsByteArrayAsync();
            System.IO.File.WriteAllBytes("output.pdf", pdfBytes);
        }
    }
}
using System;
using System.Net.Http;
using System.Threading.Tasks;

public class HtmlToPdfExample
{
    public static async Task ConvertHtmlToPdfAsync()
    {
        using (var client = new HttpClient())
        {
            var content = new StringContent("<h1>Hello World</h1>");
            var response = await client.PostAsync("https://api.compdfkit.com/html-to-pdf", content);
            var pdfBytes = await response.Content.ReadAsByteArrayAsync();
            System.IO.File.WriteAllBytes("output.pdf", pdfBytes);
        }
    }
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks

Public Class HtmlToPdfExample
	Public Shared Async Function ConvertHtmlToPdfAsync() As Task
		Using client = New HttpClient()
			Dim content = New StringContent("<h1>Hello World</h1>")
			Dim response = Await client.PostAsync("https://api.compdfkit.com/html-to-pdf", content)
			Dim pdfBytes = Await response.Content.ReadAsByteArrayAsync()
			System.IO.File.WriteAllBytes("output.pdf", pdfBytes)
		End Using
	End Function
End Class
$vbLabelText   $csharpLabel

这只是一个演示,说明我们可以在C#程序中使用这样的API。 在ComPDFKit的文档中没有具体说明如何在C#中使用它。

PDF生成的Bootstrap CSS框架支持

现代电子商务和商业应用广泛使用Bootstrap进行一致的用户界面设计。 在生成PDF格式的发票、收据和报告时,保持Bootstrap样式对于品牌一致性至关重要。 IronPDF的Chromium引擎提供完整的Bootstrap支持,而ComPDFKit的基于API的方法在处理复杂CSS框架时存在局限性。

IronPDF:使用Chromium进行的原生Bootstrap渲染

IronPDF利用Chromium渲染引擎的全部威力,提供像素完美的Bootstrap支持,包括所有版本(Bootstrap 5、4和3)。 该库可以无缝处理Flexbox布局、CSS网格、响应式工具以及自定义组件。

using IronPdf;

// Set license
IronPdf.License.LicenseKey = "License-Key";

var renderer = new ChromePdfRenderer();

// Bootstrap 5 e-commerce invoice example
string bootstrapInvoice = @"
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
    <style>
        @page { margin: 20mm; }
        .invoice-header { border-bottom: 3px solid #0d6efd; }
        .product-row { border-bottom: 1px solid #dee2e6; }
        .total-section { background-color: #f8f9fa; }
    </style>
</head>
<body>
    <div class='container-fluid p-4'>
        <!-- Invoice Header -->
        <div class='row invoice-header pb-4 mb-4'>
            <div class='col-8'>
                <h1 class='display-4 text-primary'>INVOICE</h1>
                <p class='text-muted mb-0'>TechStore Inc.</p>
                <p class='text-muted mb-0'>123 Commerce Street, Tech City, TC 12345</p>
                <p class='text-muted'>Email: sales@techstore.com | Phone: (555) 123-4567</p>
            </div>
            <div class='col-4 text-end'>
                <p class='mb-1'><strong>Invoice #:</strong> INV-2024-1089</p>
                <p class='mb-1'><strong>Date:</strong> October 27, 2024</p>
                <p class='mb-1'><strong>Due Date:</strong> November 27, 2024</p>
                <span class='badge bg-success'>PAID</span>
            </div>
        </div>

        <!-- Bill To Section -->
        <div class='row mb-4'>
            <div class='col-6'>
                <h5 class='text-primary'>Bill To:</h5>
                <p class='mb-1'><strong>Acme Corporation</strong></p>
                <p class='mb-1'>456 Business Ave</p>
                <p class='mb-1'>Enterprise City, EC 67890</p>
                <p class='mb-0'>contact@acmecorp.com</p>
            </div>
            <div class='col-6 text-end'>
                <h5 class='text-primary'>Payment Method:</h5>
                <p class='mb-1'>Credit Card ending in 4242</p>
                <p class='mb-0'>Transaction ID: TXN-9876543210</p>
            </div>
        </div>

        <!-- Products Table -->
        <div class='row mb-4'>
            <div class='col-12'>
                <table class='table'>
                    <thead class='table-primary'>
                        <tr>
                            <th scope='col'>#</th>
                            <th scope='col'>Product</th>
                            <th scope='col'>Description</th>
                            <th scope='col' class='text-center'>Qty</th>
                            <th scope='col' class='text-end'>Unit Price</th>
                            <th scope='col' class='text-end'>Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class='product-row'>
                            <td>1</td>
                            <td><strong>IronPDF Pro License</strong></td>
                            <td>Professional developer license with 1 year support</td>
                            <td class='text-center'>1</td>
                            <td class='text-end'>$2,999.00</td>
                            <td class='text-end'><strong>$2,999.00</strong></td>
                        </tr>
                        <tr class='product-row'>
                            <td>2</td>
                            <td><strong>Priority Support</strong></td>
                            <td>24/7 priority technical support package</td>
                            <td class='text-center'>1</td>
                            <td class='text-end'>$999.00</td>
                            <td class='text-end'><strong>$999.00</strong></td>
                        </tr>
                        <tr class='product-row'>
                            <td>3</td>
                            <td><strong>Training Package</strong></td>
                            <td>On-site developer training (2 days)</td>
                            <td class='text-center'>1</td>
                            <td class='text-end'>$1,500.00</td>
                            <td class='text-end'><strong>$1,500.00</strong></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Totals Section -->
        <div class='row justify-content-end mb-4'>
            <div class='col-md-6'>
                <div class='card total-section'>
                    <div class='card-body'>
                        <div class='row mb-2'>
                            <div class='col-6'><strong>Subtotal:</strong></div>
                            <div class='col-6 text-end'>$5,498.00</div>
                        </div>
                        <div class='row mb-2'>
                            <div class='col-6'><strong>Tax (8.5%):</strong></div>
                            <div class='col-6 text-end'>$467.33</div>
                        </div>
                        <div class='row mb-2'>
                            <div class='col-6 text-success'><strong>Discount (10%):</strong></div>
                            <div class='col-6 text-end text-success'>-$549.80</div>
                        </div>
                        <hr>
                        <div class='row'>
                            <div class='col-6'><h4 class='text-primary'>Total:</h4></div>
                            <div class='col-6 text-end'><h4 class='text-primary'>$5,415.53</h4></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Payment Terms -->
        <div class='row mb-4'>
            <div class='col-12'>
                <div class='alert alert-info' role='alert'>
                    <h6 class='alert-heading'>Payment Terms</h6>
                    <p class='mb-0'>Payment is due within 30 days. Late payments may incur a 1.5% monthly interest charge. Thank you for your business!</p>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <div class='row border-top pt-3'>
            <div class='col-12 text-center text-muted'>
                <small>TechStore Inc. | Tax ID: 12-3456789 | All prices in USD</small>
            </div>
        </div>
    </div>
</body>
</html>";

// Render PDF with optimized settings
var pdf = renderer.RenderHtmlAsPdf(bootstrapInvoice);

// Add metadata for document management
pdf.MetaData.Title = "Invoice INV-2024-1089";
pdf.MetaData.Author = "TechStore Inc.";
pdf.MetaData.Subject = "Sales Invoice";
pdf.MetaData.Keywords = "invoice, payment, e-commerce";

// Save the invoice
pdf.SaveAs("invoice-with-bootstrap.pdf");
using IronPdf;

// Set license
IronPdf.License.LicenseKey = "License-Key";

var renderer = new ChromePdfRenderer();

// Bootstrap 5 e-commerce invoice example
string bootstrapInvoice = @"
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
    <style>
        @page { margin: 20mm; }
        .invoice-header { border-bottom: 3px solid #0d6efd; }
        .product-row { border-bottom: 1px solid #dee2e6; }
        .total-section { background-color: #f8f9fa; }
    </style>
</head>
<body>
    <div class='container-fluid p-4'>
        <!-- Invoice Header -->
        <div class='row invoice-header pb-4 mb-4'>
            <div class='col-8'>
                <h1 class='display-4 text-primary'>INVOICE</h1>
                <p class='text-muted mb-0'>TechStore Inc.</p>
                <p class='text-muted mb-0'>123 Commerce Street, Tech City, TC 12345</p>
                <p class='text-muted'>Email: sales@techstore.com | Phone: (555) 123-4567</p>
            </div>
            <div class='col-4 text-end'>
                <p class='mb-1'><strong>Invoice #:</strong> INV-2024-1089</p>
                <p class='mb-1'><strong>Date:</strong> October 27, 2024</p>
                <p class='mb-1'><strong>Due Date:</strong> November 27, 2024</p>
                <span class='badge bg-success'>PAID</span>
            </div>
        </div>

        <!-- Bill To Section -->
        <div class='row mb-4'>
            <div class='col-6'>
                <h5 class='text-primary'>Bill To:</h5>
                <p class='mb-1'><strong>Acme Corporation</strong></p>
                <p class='mb-1'>456 Business Ave</p>
                <p class='mb-1'>Enterprise City, EC 67890</p>
                <p class='mb-0'>contact@acmecorp.com</p>
            </div>
            <div class='col-6 text-end'>
                <h5 class='text-primary'>Payment Method:</h5>
                <p class='mb-1'>Credit Card ending in 4242</p>
                <p class='mb-0'>Transaction ID: TXN-9876543210</p>
            </div>
        </div>

        <!-- Products Table -->
        <div class='row mb-4'>
            <div class='col-12'>
                <table class='table'>
                    <thead class='table-primary'>
                        <tr>
                            <th scope='col'>#</th>
                            <th scope='col'>Product</th>
                            <th scope='col'>Description</th>
                            <th scope='col' class='text-center'>Qty</th>
                            <th scope='col' class='text-end'>Unit Price</th>
                            <th scope='col' class='text-end'>Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class='product-row'>
                            <td>1</td>
                            <td><strong>IronPDF Pro License</strong></td>
                            <td>Professional developer license with 1 year support</td>
                            <td class='text-center'>1</td>
                            <td class='text-end'>$2,999.00</td>
                            <td class='text-end'><strong>$2,999.00</strong></td>
                        </tr>
                        <tr class='product-row'>
                            <td>2</td>
                            <td><strong>Priority Support</strong></td>
                            <td>24/7 priority technical support package</td>
                            <td class='text-center'>1</td>
                            <td class='text-end'>$999.00</td>
                            <td class='text-end'><strong>$999.00</strong></td>
                        </tr>
                        <tr class='product-row'>
                            <td>3</td>
                            <td><strong>Training Package</strong></td>
                            <td>On-site developer training (2 days)</td>
                            <td class='text-center'>1</td>
                            <td class='text-end'>$1,500.00</td>
                            <td class='text-end'><strong>$1,500.00</strong></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Totals Section -->
        <div class='row justify-content-end mb-4'>
            <div class='col-md-6'>
                <div class='card total-section'>
                    <div class='card-body'>
                        <div class='row mb-2'>
                            <div class='col-6'><strong>Subtotal:</strong></div>
                            <div class='col-6 text-end'>$5,498.00</div>
                        </div>
                        <div class='row mb-2'>
                            <div class='col-6'><strong>Tax (8.5%):</strong></div>
                            <div class='col-6 text-end'>$467.33</div>
                        </div>
                        <div class='row mb-2'>
                            <div class='col-6 text-success'><strong>Discount (10%):</strong></div>
                            <div class='col-6 text-end text-success'>-$549.80</div>
                        </div>
                        <hr>
                        <div class='row'>
                            <div class='col-6'><h4 class='text-primary'>Total:</h4></div>
                            <div class='col-6 text-end'><h4 class='text-primary'>$5,415.53</h4></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Payment Terms -->
        <div class='row mb-4'>
            <div class='col-12'>
                <div class='alert alert-info' role='alert'>
                    <h6 class='alert-heading'>Payment Terms</h6>
                    <p class='mb-0'>Payment is due within 30 days. Late payments may incur a 1.5% monthly interest charge. Thank you for your business!</p>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <div class='row border-top pt-3'>
            <div class='col-12 text-center text-muted'>
                <small>TechStore Inc. | Tax ID: 12-3456789 | All prices in USD</small>
            </div>
        </div>
    </div>
</body>
</html>";

// Render PDF with optimized settings
var pdf = renderer.RenderHtmlAsPdf(bootstrapInvoice);

// Add metadata for document management
pdf.MetaData.Title = "Invoice INV-2024-1089";
pdf.MetaData.Author = "TechStore Inc.";
pdf.MetaData.Subject = "Sales Invoice";
pdf.MetaData.Keywords = "invoice, payment, e-commerce";

// Save the invoice
pdf.SaveAs("invoice-with-bootstrap.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

展示的关键Bootstrap功能:

  • 网格系统rowcol-*类用于响应式布局结构
  • 排版display-4text-mutedh5用于层级文本样式
  • 表格tabletable-primarytable-hover用于结构化数据展示
  • 卡片cardcard-body用于总计部分的背景样式
  • 徽章badge bg-success用于付款状态指示
  • 警告框alert alert-info用于付款条款通知
  • 工具类text-endtext-centermb-*pb-*间距工具
  • 自定义样式:结合Bootstrap类用于特定发票设计

IronPDF的Chromium引擎确保了Bootstrap组件的完美渲染,保持了网络和PDF文档之间的品牌一致性。

有关PDF生成中Bootstrap布局的全面故障排除,包括Flexbox和响应式设计问题,请参阅:排除Bootstrap Flex和CSS问题

ComPDFKit:基于API的HTML处理局限性

ComPDFKit的HTML到PDF转换依赖于外部API调用而非嵌入式渲染。 虽然这种方法可以处理基本的Bootstrap样式,但它引入了一些限制:

  • 网络依赖:需要向外部服务的HTTP请求
  • CSS框架支持:可能无法完全支持复杂的Flexbox或CSS网格布局
  • 渲染一致性:结果可能因API服务实现不同而不同
  • 自定义样式:对Bootstrap组件渲染的控制有限
  • 性能:网络延迟给文档生成增加开销

对于需要可靠Bootstrap渲染且完全控制样式和布局的应用,原生Chromium渲染提供了更优的结果。

7. PDF上的水印

对PDF进行水印处理在许多方面是必要的。 它有助于保护文档的完整性,确认所有权并增加一层安全保护。 水印可以是文本、徽标或图像,可以出现在文档的背景或前景。 它们能够阻止内容未经授权的使用、复制和分发。 此外,水印可以传达重要信息,如文档的状态(例如,“机密”、“草稿”、“已批准”)或创作者的身份。

7.1 使用IronPDF的水印

IronPDF提供了一种简单的方法通过编程方式向PDF文档添加水印。 此功能已集成到库中,允许开发人员使用C#代码应用水印。

using IronPdf;
using IronPdf.Editing;

class Program
{
    static void Main()
    {
        License.LicenseKey = "License-Code";

        string watermarkHtml = @"
            <img style='width: 500px;' src='C:\Users\Tayyab Ali\Desktop\watermark.png'>
            <h1>IronPDF Watermark</h1>";

        ChromePdfRenderer renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>It's a PDF with a watermark</h1>");
        // Apply watermark with 30 degrees rotation and 50% opacity
        pdf.ApplyWatermark(watermarkHtml, rotation: 30, opacity: 50);
        pdf.SaveAs("Confidential.pdf");
    }
}
using IronPdf;
using IronPdf.Editing;

class Program
{
    static void Main()
    {
        License.LicenseKey = "License-Code";

        string watermarkHtml = @"
            <img style='width: 500px;' src='C:\Users\Tayyab Ali\Desktop\watermark.png'>
            <h1>IronPDF Watermark</h1>";

        ChromePdfRenderer renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>It's a PDF with a watermark</h1>");
        // Apply watermark with 30 degrees rotation and 50% opacity
        pdf.ApplyWatermark(watermarkHtml, rotation: 30, opacity: 50);
        pdf.SaveAs("Confidential.pdf");
    }
}
Imports IronPdf
Imports IronPdf.Editing

Friend Class Program
	Shared Sub Main()
		License.LicenseKey = "License-Code"

		Dim watermarkHtml As String = "
            <img style='width: 500px;' src='C:\Users\Tayyab Ali\Desktop\watermark.png'>
            <h1>IronPDF Watermark</h1>"

		Dim renderer As New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>It's a PDF with a watermark</h1>")
		' Apply watermark with 30 degrees rotation and 50% opacity
		pdf.ApplyWatermark(watermarkHtml, rotation:= 30, opacity:= 50)
		pdf.SaveAs("Confidential.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Compdfkit与IronPDF的比较:图10 - 使用IronPDF添加水印的代码输出示例输出

在此示例中,使用ChromePdfRenderer类从HTML字符串创建PDF。 然后使用ApplyWatermark方法应用水印。 水印由图像和标题组成,均在watermarkHtml字符串中定义。 rotation参数设置为30度,opacity设置为50%,确保水印可见但不压倒主要内容。 最终的PDF保存到指定路径。

7.2 使用ComPDFKit的水印

ComPDFKit提供了直接在C#中向PDF文档添加水印的综合功能。 可以通过利用ComPDFKit库的方法以编程方式完成这一操作。 以下是如何使用ComPDFKit添加文本水印的示例:

static private bool AddTextWatermark(CPDFDocument document)
{
    CPDFWatermark watermark = document.InitWatermark(C_Watermark_Type.WATERMARK_TYPE_TEXT);
    watermark.SetText("test");
    watermark.SetFontName("Helvetica"); 
    watermark.SetPages("0-3");
    byte[] color = { 255, 0, 0 };
    watermark.SetTextRGBColor(color);
    watermark.SetScale(2);
    watermark.SetRotation(0);
    watermark.SetOpacity(120);
    watermark.SetVertalign(C_Watermark_Vertalign.WATERMARK_VERTALIGN_CENTER);
    watermark.SetHorizalign(C_Watermark_Horizalign.WATERMARK_HORIZALIGN_CENTER);
    watermark.SetVertOffset(0);
    watermark.SetHorizOffset(0);
    watermark.SetFront(true);
    watermark.SetFullScreen(true);
    watermark.SetVerticalSpacing(10);
    watermark.SetHorizontalSpacing(10);
    watermark.CreateWatermark();
    string path = "AddTextWatermarkTest.pdf";
    if (!document.WriteToFilePath(path))
    {
        return false;
    }
    Console.WriteLine("Browse the changed file in " + path);
    return true;
}

CPDFDocument document = CPDFDocument.InitWithFilePath("SamplePDF.pdf");
if (AddTextWatermark(document))
{
    Console.WriteLine("Add text watermark done.");
}
else
{
    Console.WriteLine("Add text watermark failed.");
}
static private bool AddTextWatermark(CPDFDocument document)
{
    CPDFWatermark watermark = document.InitWatermark(C_Watermark_Type.WATERMARK_TYPE_TEXT);
    watermark.SetText("test");
    watermark.SetFontName("Helvetica"); 
    watermark.SetPages("0-3");
    byte[] color = { 255, 0, 0 };
    watermark.SetTextRGBColor(color);
    watermark.SetScale(2);
    watermark.SetRotation(0);
    watermark.SetOpacity(120);
    watermark.SetVertalign(C_Watermark_Vertalign.WATERMARK_VERTALIGN_CENTER);
    watermark.SetHorizalign(C_Watermark_Horizalign.WATERMARK_HORIZALIGN_CENTER);
    watermark.SetVertOffset(0);
    watermark.SetHorizOffset(0);
    watermark.SetFront(true);
    watermark.SetFullScreen(true);
    watermark.SetVerticalSpacing(10);
    watermark.SetHorizontalSpacing(10);
    watermark.CreateWatermark();
    string path = "AddTextWatermarkTest.pdf";
    if (!document.WriteToFilePath(path))
    {
        return false;
    }
    Console.WriteLine("Browse the changed file in " + path);
    return true;
}

CPDFDocument document = CPDFDocument.InitWithFilePath("SamplePDF.pdf");
if (AddTextWatermark(document))
{
    Console.WriteLine("Add text watermark done.");
}
else
{
    Console.WriteLine("Add text watermark failed.");
}
Private Shared Function AddTextWatermark(ByVal document As CPDFDocument) As Boolean
	Dim watermark As CPDFWatermark = document.InitWatermark(C_Watermark_Type.WATERMARK_TYPE_TEXT)
	watermark.SetText("test")
	watermark.SetFontName("Helvetica")
	watermark.SetPages("0-3")
	Dim color() As Byte = { 255, 0, 0 }
	watermark.SetTextRGBColor(color)
	watermark.SetScale(2)
	watermark.SetRotation(0)
	watermark.SetOpacity(120)
	watermark.SetVertalign(C_Watermark_Vertalign.WATERMARK_VERTALIGN_CENTER)
	watermark.SetHorizalign(C_Watermark_Horizalign.WATERMARK_HORIZALIGN_CENTER)
	watermark.SetVertOffset(0)
	watermark.SetHorizOffset(0)
	watermark.SetFront(True)
	watermark.SetFullScreen(True)
	watermark.SetVerticalSpacing(10)
	watermark.SetHorizontalSpacing(10)
	watermark.CreateWatermark()
	Dim path As String = "AddTextWatermarkTest.pdf"
	If Not document.WriteToFilePath(path) Then
		Return False
	End If
	Console.WriteLine("Browse the changed file in " & path)
	Return True
End Function

Private document As CPDFDocument = CPDFDocument.InitWithFilePath("SamplePDF.pdf")
If AddTextWatermark(document) Then
	Console.WriteLine("Add text watermark done.")
Else
	Console.WriteLine("Add text watermark failed.")
End If
$vbLabelText   $csharpLabel

Compdfkit与IronPDF的比较:图11 - 使用ComPDFKit添加水印的代码输出示例输出

在此示例中,使用CPDFDocument类打开一个现有的PDF文档。 AddTextWatermark方法使用InitWatermark方法初始化文本水印。 设置水印的各种属性,如文本内容、字体、颜色、缩放、旋转、不透明度、对齐和间距。 然后创建水印并应用于PDF文档的指定页面。 最后,将修改后的PDF保存到指定路径。 集成图像水印需要使用不同的方法。

8. PDFA

PDF/A是PDF的一种标准化版本,专为电子文档的长期数字保存而设计。 确保文档符合PDF/A,确保它们可以在未来可靠地查看和再现。 本节探讨如何使用两个流行的库创建PDF/A兼容文档:IronPDF和ComPDFKit。

8.1 使用IronPDF的PDFA

IronPDF简化了将标准PDF文档转换为PDF/A兼容文档的过程。 使用IronPDF,你可以轻松加载现有的PDF并将其以PDF/A兼容格式存储。

using IronPdf;
using System;

class Program
{
    static void Main()
    {
        License.LicenseKey = "License-Key";
        PdfDocument pdf = PdfDocument.FromFile("Source.pdf");
        pdf.SaveAsPdfA("pdfa-compliant.pdf", PdfAVersions.PdfA3);
    }
}
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        License.LicenseKey = "License-Key";
        PdfDocument pdf = PdfDocument.FromFile("Source.pdf");
        pdf.SaveAsPdfA("pdfa-compliant.pdf", PdfAVersions.PdfA3);
    }
}
Imports IronPdf
Imports System

Friend Class Program
	Shared Sub Main()
		License.LicenseKey = "License-Key"
		Dim pdf As PdfDocument = PdfDocument.FromFile("Source.pdf")
		pdf.SaveAsPdfA("pdfa-compliant.pdf", PdfAVersions.PdfA3)
	End Sub
End Class
$vbLabelText   $csharpLabel

以下是此过程的简要概述:

  1. 初始化IronPDF:首先导入IronPDF库并设置你的许可证密钥。
  2. 加载PDF:使用PdfDocument.FromFile加载你的源PDF文件。
  3. 转换并保存:通过指定所需的PDF/A版本将已加载的PDF转换为PDF/A并保存生成的文档。

这种简单的方法使IronPDF成为处理PDF/A转换的便捷选择。

8.2 使用ComPDFKit的PDFA

ComPDFKit提供了一个将PDF转换为PDF/A格式的强大解决方案。 该过程涉及初始化PDF文档、定义输出路径以及调用转换方法。

static public bool CovertToPDFA1a(CPDFDocument document)
{
    string convertToPDFA1aPath = "ConvertToPDFA1aTest.pdf";
    if (!document.WritePDFAToFilePath(CPDFType.CPDFTypePDFA1a, convertToPDFA1aPath))
    {
        return false;
    }
    Console.WriteLine("Browse the changed file in " + convertToPDFA1aPath);
    return true;
}

CPDFDocument document = CPDFDocument.InitWithFilePath("CommonFivePage.pdf");
if (CovertToPDFA1a(document))
{
    Console.WriteLine("Convert to PDF/A-1a done.");
}
else
{
    Console.WriteLine("Convert to PDF/A-1a failed.");
}
static public bool CovertToPDFA1a(CPDFDocument document)
{
    string convertToPDFA1aPath = "ConvertToPDFA1aTest.pdf";
    if (!document.WritePDFAToFilePath(CPDFType.CPDFTypePDFA1a, convertToPDFA1aPath))
    {
        return false;
    }
    Console.WriteLine("Browse the changed file in " + convertToPDFA1aPath);
    return true;
}

CPDFDocument document = CPDFDocument.InitWithFilePath("CommonFivePage.pdf");
if (CovertToPDFA1a(document))
{
    Console.WriteLine("Convert to PDF/A-1a done.");
}
else
{
    Console.WriteLine("Convert to PDF/A-1a failed.");
}
Public Shared Function CovertToPDFA1a(ByVal document As CPDFDocument) As Boolean
	Dim convertToPDFA1aPath As String = "ConvertToPDFA1aTest.pdf"
	If Not document.WritePDFAToFilePath(CPDFType.CPDFTypePDFA1a, convertToPDFA1aPath) Then
		Return False
	End If
	Console.WriteLine("Browse the changed file in " & convertToPDFA1aPath)
	Return True
End Function

Private document As CPDFDocument = CPDFDocument.InitWithFilePath("CommonFivePage.pdf")
If CovertToPDFA1a(document) Then
	Console.WriteLine("Convert to PDF/A-1a done.")
Else
	Console.WriteLine("Convert to PDF/A-1a failed.")
End If
$vbLabelText   $csharpLabel

以下是步骤的概要:

  1. 初始化文档:使用CPDFDocument.InitWithFilePath加载PDF文档。
  2. 设置输出目录:确保输出目录存在或必要时进行创建。
  3. 转换为PDF/A:使用根据指定的PDF/A类型的WritePDFAToFilePath执行转换并保存文件。

9. 数字签名

数字签名对于验证文件的真实性和完整性至关重要。 本节展示了如何使用IronPDF和ComPDFKit向PDF添加数字签名。

9.1 由IronPDF进行数字签名

IronPDF提供了一种简单有效的方法向PDF文档应用数字签名。

using IronPdf;
using IronPdf.Signing;

class Program
{
    static void Main(string[] args)
    {
        var simpleSignature = new PdfSignature("MyCert.p12", "newpassword");
        simpleSignature.SignPdfFile("sample.pdf");
    }
}
using IronPdf;
using IronPdf.Signing;

class Program
{
    static void Main(string[] args)
    {
        var simpleSignature = new PdfSignature("MyCert.p12", "newpassword");
        simpleSignature.SignPdfFile("sample.pdf");
    }
}
Imports IronPdf
Imports IronPdf.Signing

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim simpleSignature = New PdfSignature("MyCert.p12", "newpassword")
		simpleSignature.SignPdfFile("sample.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

该过程包括:

  1. 初始化IronPDF:导入必要的IronPDF库。
  2. 创建签名:初始化使用证书文件和密码的PdfSignature对象。
  3. 签署PDF:使用SignPdfFile将签名应用于PDF。

这种方法确保你的PDF文件被安全签署,提高其信誉和安全性。

9.2 由CompDFKit进行数字签名

ComPDFKit为创建具有广泛定制选项的数字签名提供了全面的解决方案。

private static void CreateDigitalSignature(CPDFDocument document, string certificatePath, string password)
{
    Console.WriteLine("--------------------");
    Console.WriteLine("Create digital signature.");
    CPDFSignatureCertificate certificate = CPDFPKCS12CertHelper.GetCertificateWithPKCS12Path("Certificate.pfx", "ComPDFKit");
    CPDFPage page = document.PageAtIndex(0);
    CPDFSignatureWidget signatureField = page.CreateWidget(C_WIDGET_TYPE.WIDGET_SIGNATUREFIELDS) as CPDFSignatureWidget;
    signatureField.SetRect(new CRect(28, 420, 150, 370));
    signatureField.SetWidgetBorderRGBColor(new byte[] { 0, 0, 0 });
    signatureField.SetWidgetBgRGBColor(new byte[] { 150, 180, 210 });
    signatureField.UpdateAp();
    string name = GetGrantorFromDictionary(certificate.SubjectDict) + "\n";
    string date = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss");
    string reason = "I am the owner of the document.";
    string location = certificate.SubjectDict["C"];
    string DN = certificate.Subject;

    CPDFSignatureConfig signatureConfig = new CPDFSignatureConfig
    {
        Text = GetGrantorFromDictionary(certificate.SubjectDict),
        Content =
            "Name: " + name + "\n" +
            "Date: " + date + "\n" +
            "Reason: " + reason + " \n" +
            "Location: " + location + "\n" +
            "DN: " + DN + "\n",
        IsContentAlignLeft = false,
        IsDrawLogo = true,
        LogoBitmap = new Bitmap("Logo.png"),
        TextColor = new float[] { 0, 0, 0 },
        ContentColor = new float[] { 0, 0, 0 }
    };
    string filePath = document.FileName + "_Signed.pdf";
    signatureField.UpdataApWithSignature(signatureConfig);
    if (document.WriteSignatureToFilePath(signatureField,
        filePath,
        certificatePath, password,
        location,
        reason, CPDFSignaturePermissions.CPDFSignaturePermissionsNone))
    {
        Console.WriteLine("File saved in " + filePath);
        Console.WriteLine("Create digital signature done.");
    }
    else
    {
        Console.WriteLine("Create digital signature failed.");
    }
    Console.WriteLine("--------------------");
}
private static void CreateDigitalSignature(CPDFDocument document, string certificatePath, string password)
{
    Console.WriteLine("--------------------");
    Console.WriteLine("Create digital signature.");
    CPDFSignatureCertificate certificate = CPDFPKCS12CertHelper.GetCertificateWithPKCS12Path("Certificate.pfx", "ComPDFKit");
    CPDFPage page = document.PageAtIndex(0);
    CPDFSignatureWidget signatureField = page.CreateWidget(C_WIDGET_TYPE.WIDGET_SIGNATUREFIELDS) as CPDFSignatureWidget;
    signatureField.SetRect(new CRect(28, 420, 150, 370));
    signatureField.SetWidgetBorderRGBColor(new byte[] { 0, 0, 0 });
    signatureField.SetWidgetBgRGBColor(new byte[] { 150, 180, 210 });
    signatureField.UpdateAp();
    string name = GetGrantorFromDictionary(certificate.SubjectDict) + "\n";
    string date = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss");
    string reason = "I am the owner of the document.";
    string location = certificate.SubjectDict["C"];
    string DN = certificate.Subject;

    CPDFSignatureConfig signatureConfig = new CPDFSignatureConfig
    {
        Text = GetGrantorFromDictionary(certificate.SubjectDict),
        Content =
            "Name: " + name + "\n" +
            "Date: " + date + "\n" +
            "Reason: " + reason + " \n" +
            "Location: " + location + "\n" +
            "DN: " + DN + "\n",
        IsContentAlignLeft = false,
        IsDrawLogo = true,
        LogoBitmap = new Bitmap("Logo.png"),
        TextColor = new float[] { 0, 0, 0 },
        ContentColor = new float[] { 0, 0, 0 }
    };
    string filePath = document.FileName + "_Signed.pdf";
    signatureField.UpdataApWithSignature(signatureConfig);
    if (document.WriteSignatureToFilePath(signatureField,
        filePath,
        certificatePath, password,
        location,
        reason, CPDFSignaturePermissions.CPDFSignaturePermissionsNone))
    {
        Console.WriteLine("File saved in " + filePath);
        Console.WriteLine("Create digital signature done.");
    }
    else
    {
        Console.WriteLine("Create digital signature failed.");
    }
    Console.WriteLine("--------------------");
}
Imports Microsoft.VisualBasic

Private Shared Sub CreateDigitalSignature(ByVal document As CPDFDocument, ByVal certificatePath As String, ByVal password As String)
	Console.WriteLine("--------------------")
	Console.WriteLine("Create digital signature.")
	Dim certificate As CPDFSignatureCertificate = CPDFPKCS12CertHelper.GetCertificateWithPKCS12Path("Certificate.pfx", "ComPDFKit")
	Dim page As CPDFPage = document.PageAtIndex(0)
	Dim signatureField As CPDFSignatureWidget = TryCast(page.CreateWidget(C_WIDGET_TYPE.WIDGET_SIGNATUREFIELDS), CPDFSignatureWidget)
	signatureField.SetRect(New CRect(28, 420, 150, 370))
	signatureField.SetWidgetBorderRGBColor(New Byte() { 0, 0, 0 })
	signatureField.SetWidgetBgRGBColor(New Byte() { 150, 180, 210 })
	signatureField.UpdateAp()
	Dim name As String = GetGrantorFromDictionary(certificate.SubjectDict) & vbLf
	Dim [date] As String = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss")
	Dim reason As String = "I am the owner of the document."
	Dim location As String = certificate.SubjectDict("C")
	Dim DN As String = certificate.Subject

	Dim signatureConfig As New CPDFSignatureConfig With {
		.Text = GetGrantorFromDictionary(certificate.SubjectDict),
		.Content = "Name: " & name & vbLf & "Date: " & [date] & vbLf & "Reason: " & reason & " " & vbLf & "Location: " & location & vbLf & "DN: " & DN & vbLf,
		.IsContentAlignLeft = False,
		.IsDrawLogo = True,
		.LogoBitmap = New Bitmap("Logo.png"),
		.TextColor = New Single() { 0, 0, 0 },
		.ContentColor = New Single() { 0, 0, 0 }
	}
	Dim filePath As String = document.FileName & "_Signed.pdf"
	signatureField.UpdataApWithSignature(signatureConfig)
	If document.WriteSignatureToFilePath(signatureField, filePath, certificatePath, password, location, reason, CPDFSignaturePermissions.CPDFSignaturePermissionsNone) Then
		Console.WriteLine("File saved in " & filePath)
		Console.WriteLine("Create digital signature done.")
	Else
		Console.WriteLine("Create digital signature failed.")
	End If
	Console.WriteLine("--------------------")
End Sub
$vbLabelText   $csharpLabel

步骤包括:

  1. 初始化文档和证书:使用CPDFPKCS12CertHelper加载PDF文档和检索证书。
  2. 创建和配置签名字段:向PDF添加签名字段,设置其属性,并配置签名详细信息。
  3. 应用签名:使用WriteSignatureToFilePath应用签名并保存签名的PDF。

10. 提取文本

从PDF文档中提取文本对于各种数据处理和分析任务至关重要。 本节说明了如何使用IronPDF和ComPDFKit从PDF提取文本。

10.1 使用IronPDF提取文本

IronPDF提供了一种直接的方法从PDF文档中提取文本。

using IronPdf;
using System.IO;

PdfDocument pdf = PdfDocument.FromFile("PDF File With Text.pdf");
string text = pdf.ExtractAllText();
File.WriteAllText("PDF Text.txt", text);
using IronPdf;
using System.IO;

PdfDocument pdf = PdfDocument.FromFile("PDF File With Text.pdf");
string text = pdf.ExtractAllText();
File.WriteAllText("PDF Text.txt", text);
Imports IronPdf
Imports System.IO

Private pdf As PdfDocument = PdfDocument.FromFile("PDF File With Text.pdf")
Private text As String = pdf.ExtractAllText()
File.WriteAllText("PDF Text.txt", text)
$vbLabelText   $csharpLabel

该过程包括:

  1. 初始化IronPDF:导入IronPDF库。
  2. 加载PDF:使用PdfDocument.FromFile加载PDF文件。
  3. 提取文本:调用ExtractAllText以从PDF中检索所有文本内容。
  4. 将文本保存到文件:使用标准文件I/O操作将提取的文本写入文件。

此方法为从PDF文件中提取和保存文本提供了简单而高效的途径。

10.2 使用ComPDFKit提取文本

ComPDFKit提供了一种灵活的PDF文档文本提取解决方案。

static private bool PDFToText(CPDFDocument document)
{
    string path = "//PDFToText.txt";
    if (!document.PdfToText("1-" + document.PageCount.ToString(), path))//Page ranges are counted from 1
    {
        return false;
    }
    Console.WriteLine("Browse the generated file in " + path);
    return true;
}

static void Main(string[] args)
{
    Console.WriteLine("Running PDFPage test sample…\r\n");
    SDKLicenseHelper.LicenseVerify();
    CPDFDocument document = CPDFDocument.InitWithFilePath("CommonFivePage.pdf");

    if (PDFToText(document))
    {
        Console.WriteLine("PDF to text done.");
    }
    else
    {
        Console.WriteLine("PDF to text failed.");
    }
    Console.WriteLine("--------------------");
    Console.WriteLine("Done!");
    Console.WriteLine("--------------------");
    Console.ReadLine();
}
static private bool PDFToText(CPDFDocument document)
{
    string path = "//PDFToText.txt";
    if (!document.PdfToText("1-" + document.PageCount.ToString(), path))//Page ranges are counted from 1
    {
        return false;
    }
    Console.WriteLine("Browse the generated file in " + path);
    return true;
}

static void Main(string[] args)
{
    Console.WriteLine("Running PDFPage test sample…\r\n");
    SDKLicenseHelper.LicenseVerify();
    CPDFDocument document = CPDFDocument.InitWithFilePath("CommonFivePage.pdf");

    if (PDFToText(document))
    {
        Console.WriteLine("PDF to text done.");
    }
    else
    {
        Console.WriteLine("PDF to text failed.");
    }
    Console.WriteLine("--------------------");
    Console.WriteLine("Done!");
    Console.WriteLine("--------------------");
    Console.ReadLine();
}
Imports Microsoft.VisualBasic

Private Shared Function PDFToText(ByVal document As CPDFDocument) As Boolean
	Dim path As String = "//PDFToText.txt"
	If Not document.PdfToText("1-" & document.PageCount.ToString(), path) Then 'Page ranges are counted from 1
		Return False
	End If
	Console.WriteLine("Browse the generated file in " & path)
	Return True
End Function

Shared Sub Main(ByVal args() As String)
	Console.WriteLine("Running PDFPage test sample…" & vbCrLf)
	SDKLicenseHelper.LicenseVerify()
	Dim document As CPDFDocument = CPDFDocument.InitWithFilePath("CommonFivePage.pdf")

	If PDFToText(document) Then
		Console.WriteLine("PDF to text done.")
	Else
		Console.WriteLine("PDF to text failed.")
	End If
	Console.WriteLine("--------------------")
	Console.WriteLine("Done!")
	Console.WriteLine("--------------------")
	Console.ReadLine()
End Sub
$vbLabelText   $csharpLabel

步驟是:

  1. 初始化文档:使用CPDFDocument.InitWithFilePath加载PDF文档。
  2. 提取并保存文本:使用PdfToText从指定的页面范围内提取文本并将其保存到文件中。

11. 许可

IronPDF和ComPDFKit的许可模式在其方法和使用条款上存在差异。 了解这些差异可以帮助你为项目的需求和预算选择合适的工具。

11.1 IronPDF许可

Compdfkit与IronPDF的比较:图12 - IronPDF许可页面

IronPDF在商业许可模式下运行,这意味着对于商业或与业务相关的应用程序,通常需要购买许可证。 该模式提供灵活性,包括免版税发行选项。 这使开发人员可以将库集成到他们的项目中,而不会在运行时面临额外费用。

IronPDF提供永久许可证。 永久许可证需要一次性付款即可终身使用,针对初始期间外的更新和技术支持提供可选费用。 这种商业模式确保企业获得专业PDF生成和操作所需的专用支持、全面的文档以及对高级功能的访问。

11.2 ComPDFKit许可

ComPDFKit采用灵活的许可模式,满足不同业务需求。 它提供永久和订阅许可证。 永久许可证涉及一次性付款,授予对SDK的终身访问权,并且可选择性支付更新和扩展支持的费用。 订阅许可证需要定期付款(月度或年度)并包括持续的更新和支持访问。

在IronPDF和ComPDFKit之间进行选择时,考虑项目的具体需求,例如对专用支持的需要、预算限制和部署规模。 IronPDF的商业模型更适合于寻找强大支持和高级功能的企业。

12. 文档和支持

12.1. IronPDF文档和支持

IronPDF为其用户提供全面的文档和强大的支持选项。 文档内容丰富而详细,提供了有关安装、基本使用、高级功能和故障排除的明确指导。 在Read the Docs上提供官方文档,包括快速入门指南、详细API参考和大量代码示例,帮助开发者初学者轻松掌握并有效使用IronPDF功能。

IronPDF还维护一个活跃的故障排除指南和技术支持网站,通过其博客和示例部分,用户可以找到常见问题的解决方案,例如渲染延迟和部署挑战。 支持站点包含一系列文章,处理常见问题和特定技术问题。

对于直接支持,IronPDF提供一个响应迅速的客户服务团队,可以就更复杂的问题或个性化帮助与其联系。 大量的文檔和強大的支持基礎設施使IronPDF成為希望在應用程式中整合PDF功能的開發人員的可靠選擇。

12.2. ComPDFKit 文檔和支持

ComPDFKit還為其用戶提供了完整的文檔和支持資源。 它涵蓋了使用SDK的各個方面,從基本設置到高級功能,如水印和數字簽名。 在支持方面,ComPDFKit通過其客戶服務渠道提供技術幫助。 支持團隊隨時幫助解決技術問題,回答問題,並提供有效使用SDK的指導。

雖然IronPDF和ComPDFKit都提供強大的文檔和支持,但IronPDF在其更廣泛的故障排除指南和高度響應的支持團隊方面具有優勢。 這對於可能遇到複雜技術挑戰並需要可靠幫助的開發人員來說特別有利。

13. 結論

IronPDF和ComPDFKit之間的比較突出了開發人員在尋找用于PDF生成和操作的強大C#庫時的優點和考慮因素。

ComPDFKit是一個綜合的PDF SDK,支持程序性處理PDF文檔所需的廣泛功能。 它在PDF註釋方面表現出色,且具有廣泛的編輯功能。 其功能,如格式轉換和安全選項,為開發人員增加了顯著的價值。

另一方面,IronPDF以其強大且易於使用的API而聞名。 它通過從HTML、CSS和JavaScript渲染PDF來簡化PDF生成。 IronPDF在HTML到PDF轉換方面表現出色,提供了與.NET應用程式的無縫整合。 該庫提供了廣泛的編輯功能,包括添加標題、頁腳、水印和數字簽名。

IronPDF的安全功能確保PDF文檔中的敏感信息得到良好保護。 其對多個.NET平台的支持和針對高負荷工作的優化性能使其成為企業級應用的理想選擇。 IronPDF的商業許可模式確保了專業支持、全面的文檔和高級功能的訪問,使其尤其適合於專業級項目。

IronPDF相比ComPDFKit是開發人員尋找全面且功能豐富的PDF庫的強選擇。 其高級功能、用戶友好的API和強大的支持基礎設施使其成為企業和對PDF需求多樣且苛刻的項目的首選解決方案。 IronPDF的豐富能力和專業支持提供了顯著的優勢,確保專業應用中的PDF生成和操作可靠高效。

總而言之,IronPDF和ComPDFKit都是用於C#中的PDF處理的強大工具。 然而,IronPDF的廣泛功能集、優化性能和卓越支持使其成為開發人員針對專業和企業級應用的首選。

IronPDF提供免費試用許可,供用戶試用該庫及其功能。 IronPDF的許可起始價格為$799。 Additionally, Iron Software bundles nine libraries for the cost of two, which includes IronXL and IronOCR along with IronPDF.

請注意ComPDFKit是其各自所有者的註冊商標。 本網站與ComPDFKit無關、未經其認可或贊助。 所有產品名稱、徽標和品牌均為其各自所有者的財產。 比較僅供信息參考,並反映撰寫時公開可用的信息。

常見問題解答

怎樣在 C# 中將 HTML 轉換為 PDF?

您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字串轉換為 PDF。此方法適合將 HTML、CSS 和 JavaScript 轉換為高品質 PDF 文件。

使用 C# PDF 庫有何好處?

像 IronPDF 和 ComPDFKit 這樣的 C# PDF 庫能夠創建、修改和提取文本/圖像。他們支持表單處理、數位簽名和安全性等功能,提供跨平台的靈活性。

我可以在 C# 中為我的 PDF 增加安全性嗎?

可以,使用 IronPDF,您可以通過設置密碼、加密文件和添加數字簽名來增強 PDF 的安全性,以保護敏感信息。

ComPDFKit 如何處理 PDF 編輯和轉換?

ComPDFKit 提供強大的 PDF 編輯功能和轉換到各種格式,包括用於長期數字保存的 PDF/A,使其適合跨平台專案。

C# PDF 庫有哪些授權選項?

IronPDF 提供商業授權模式,具有永久授權,而 ComPDFKit 提供永久和訂閱授權,根據業務需求提供靈活性。

對於使用這些庫的開發者有哪些支持和資源?

IronPDF 提供全面的文檔和快速的客戶支持,使其適合企業級應用。ComPDFKit 也提供詳盡的文檔和技術支持。

IronPDF 和 ComPDFKit 在 HTML 轉 PDF 轉換方面如何比較?

IronPDF 在 HTML 轉 PDF 轉換方面表現出色,支持 HTML 字串、網址、ASPX 網頁表單和 MVC 視圖,而 ComPDFKit 提供更廣泛的 PDF 編輯和轉換功能。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。