跳至页脚内容
产品比较

Compdfkit和IronPDF之间的比较

PDF,是便携文档格式的缩写,由Adobe创建,以确保文件共享中的统一性。 这种格式确保布局、文本和图像在不同设备和操作系统之间保持一致。 PDF以其安全性、交互功能和紧凑的尺寸而闻名,使其非常适合在不改变源内容下分发文档。

对于使用C#的开发人员,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功能。 它通过从HTML, CSS, JavaScript及各种图像格式生成PDF来简化PDF的生成。 这使其成为寻求在.NET应用程序中集成强大PDF功能的开发人员的理想工具。

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社区版,可以选择登录或不登录而继续。

步骤3:创建一个新项目

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

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

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

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

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

4. 安装 IronPDF

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

  1. 要使用 Visual Studio 的 NuGet 包管理器,请右键单击您的解决方案中的“依赖项”并选择“管理 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 和 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内容:创建一个带有您的HTML内容的HTTP POST请求到ComPDFKit API端点。
  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进行一致的UI设计。 在以PDF生成发票、收据和报告时,保持Bootstrap样式对于品牌一致性至关重要。 IronPDF的 Chromium 引擎提供全面的 Bootstrap 支持,而 ComPDFKit 的基于API的方法在处理复杂的 CSS 框架时有一些限制。

IronPDF:使用 Chromium 的 Native 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 字符串中定义。 旋转 参数设置为30度,不透明度 设置为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. PDF/A

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

8.1 使用 IronPDF 的 PDF/A

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 的 PDF/A

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之间的比较突显了那些寻求强大C#库以进行PDF生成和操作的开发人员的优点和考虑。

ComPDFKit是一个全面的PDF SDK,支持编程处理PDF文档所需的广泛功能。 它擅长于PDF注释并具有广泛的编辑能力。 其功能如格式转换和安全选项为开发人员增加了重大价值。

另一方面,IronPDF以其强大且用户友好的API而闻名。 它通过从HTML、CSS和JavaScript渲染PDF来简化PDF生成过程。 IronPDF在HTML到PDF转换中表现出色,为.NET应用程序提供了无缝的集成。 该库提供了广泛的编辑功能,包括添加页眉、页脚、水印和数字签名。

IronPDF的安全功能可确保PDF文档中的敏感信息得到良好的保护。 其对多个.NET平台的支持和为高工作负载优化的性能使其成为企业级应用程序的理想选择。 IronPDF的商业许可模式确保了专门的支持、全面的文档和高级功能的访问,使其特别适合专业级项目。

与ComPDFKit相比,IronPDF作为一个综合功能丰富的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.

[{i:(ComPDFKit是其各自所有者的注册商标。 本站与ComPDFKit没有任何关系、认可或赞助。 所有产品名称、徽标和品牌均为其各自所有者的财产。 比较仅供参考,反映的是撰写时的公开信息。]

常见问题解答

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

您可以使用 IronPDF 的RenderHtmlAsPdf方法将 HTML 字符串转换为 PDF。此方法适用于将 HTML、CSS 和 JavaScript 转换为高质量的 PDF 文档。

使用 C# PDF 库的好处是什么?

像 IronPDF 和 ComPDFKit 这样的 C# PDF 库支持 PDF 创建、修改和文本/图像提取。它们支持如表单处理、数字签名和安全性等功能,提供不同平台上的灵活性。

我可以在 C# 中为PDF 添加安全性吗?

是的,使用 IronPDF,您可以通过设置密码、加密文档和添加数字签名来增强 PDF 的安全性,以保护敏感信息。

ComPDFKit 如何处理 PDF 编辑和转换?

ComPDFKit 提供强大的 PDF 编辑功能和转换为各种格式的功能,包括用于长期数字保存的 PDF/A,使其在跨平台项目中具有很强的适应性。

C# PDF 库有哪些授权选项可用?

IronPDF 提供永续授权的商业授权模式,而 ComPDFKit 提供永续和订阅两种授权选项,使其能够根据业务需求灵活选择。

使用这些库的开发者有哪些支持和资源可用?

IronPDF 提供全面的文档和响应迅速的客户支持,使其适用于企业级应用。ComPDFKit 同样提供详细的文档和技术支持。

在 HTML 到 PDF 转换方面,IronPDF 和 ComPDFKit 如何比较?

IronPDF 在 HTML 到 PDF 转换方面表现优秀,支持 HTML 字符串、URL、ASPX Web 表单和 MVC 视图,而 ComPDFKit 提供更广泛的 PDF 编辑和转换功能。

Curtis Chau
技术作家

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

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