产品比较

SpirePDF C# HTML转PDF教程及库对比

发布 2024年十一月11日
分享:

介绍

您是否希望寻找一个PDF库来完成所有与PDF相关的任务,而无需安装Adobe Acrobat,但不知道在目前众多的PDF库中选择哪一个? 今天,我们将深入了解两个主要的PDF库,IronPDF和Spire.PDF,在.NET环境中。

在整个对比指南中,我们将查看这些库提供的功能、它们如何帮助您、库的现有文档以及使用这些库的许可定价。

IronPDF和Spire.PDF简要概述

IronPDF 是一个多功能的 .NET PDF 库,旨在处理广泛的 PDF 相关任务,包括 PDF 文件转换、PDF 编辑、PDF 创建、读取 PDF 文件等。 它因易于集成到现有的.NET应用程序中、高性能以及支持HTML5、CSS3和JavaScript等现代Web标准而闻名。 IronPDF的API直观,使其成为在项目中添加强大PDF功能的绝佳选择。

Spire.PDF for .NET 是另一个功能强大的 .NET PDF 库,它提供了全面的功能集用于 PDF 创建和操作。 它支持多种PDF功能,如文本和图像提取、PDF表单填写和数字签名。 Spire.PDF 旨在易于使用,并可无缝集成到 .NET 应用程序中,使其成为您的 PDF 项目的另一潜在选择。

有关IronPDF的更多详细信息,请访问IronPDF.com.

跨平台兼容性

IronPDF

IronPDF因其广泛的跨平台兼容性而脱颖而出。 它支持 .NET 框架内的广泛环境,确保在不同平台上的无缝运行。 以下是IronPDF平台兼容性的总结:

  • .NET 版本:

    • 完全用C#、VB.NET和F#编写和支持

    • .NET Core(8、7、6、5 和 3.1+)

    • .NET标准(2.0+)
  • .NET 框架(4.6.2+)
  • 应用环境: IronPDF 可以在各种应用环境中运行,如 Windows、Linux、Mac、Docker、Azure 和 AWS。
  • IDEs(集成开发环境): 适用于Microsoft Visual Studio和JetBrains Rider & ReSharper等IDEs。
  • 操作系统和处理器: 支持多种不同的操作系统和处理器,包括Windows、Mac、Linux、x64、x86、ARM。

    有关 IronPDF 兼容性的更多详细信息,请访问IronPDF兼容性.

Spire.PDF

Spire.PDF在.NET环境中具有全面支持,但虽然它可以在Windows操作系统中工作,但缺乏IronPDF在Linux和macOS上的原生支持。

  • .NET 支持:
  • .NET Framework 2.0+
  • .NET Core 2.0+
  • 用C#编写,支持VB.NET
  • 应用环境: Spire.PDF 可以在各种应用环境中运行,例如 Windows 和 ASP.NET 应用程序,并且也可以支持 Windows Forms。

功能比较:IronPDF与Spire.PDF的PDF功能

IronPDF和Spire.PDF都提供一系列针对不同PDF功能量身定制的功能。 以下是每个库提供的关键功能比较:

IronPDF 功能

  • PDF 转换: IronPDF 可以将 HTML 转换为 PDF,通过完全支持现代网络标准,您可以放心,IronPDF 会始终从您的 HTML 内容中生成像素完美的 PDF。 IronPDF 还能将其他格式的文件转换为PDF,如DOCX、图片、RTF等。
  • PDF生成:使用IronPDF,您可以从URL、ASPX文件或HTML字符串生成PDF。
  • 安全功能: 使用IronPDF,您可以放心,任何敏感的PDF文件都得到了安全保护,多亏了它的安全功能。 使用 IronPDF 加密您的 PDF 文件,设置密码,并为您的 PDF 文件设置权限。
  • PDF编辑功能: 使用IronPDF,您可以处理现有的PDF文档,编辑它们,并轻松读取PDF文件。 IronPDF 提供的编辑功能包括添加页眉和页脚,将文本和图像盖章到PDF页面上,为PDF添加自定义水印,处理PDF表单,以及拆分或合并PDF文件。
  • 集成:无缝集成到ASP.NET和MVC应用程序。
  • PDF版本支持: 可以支持PDF版本1.2-1.7

    要查看 IronPDF 功能的完整列表,请访问IronPDF 功能.

Spire.PDF 功能

  • PDF 创建:从头创建 PDF 或从现有文件创建 PDF。
  • 文本和图像提取:使用Spire.PDF提取PDF页面和内容。
  • PDF表单处理:填写和管理PDF表单。
  • PDF转换:将PDF转换为其他格式,如HTML、RTF和图像。
  • 页面操作:插入、删除和重新排序PDF中的页面。

IronPDF与Spire.PDF for .NET的顶级亮点功能比较及代码示例

为了展示IronPDF和Spire.PDF for .NET的功能,我们将通过代码示例比较它们在几个关键PDF功能上的实现,让您了解这些功能如何帮助您的PDF项目。

将HTML转换为PDF

IronPDF

using IronPdf;

// Disable local disk access or cross-origin requests
Installation.EnableWebSecurity = true;

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

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

// Advanced Example with HTML Assets
// Load external html assets: images, CSS and JavaScript.
// An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
using IronPdf;

// Disable local disk access or cross-origin requests
Installation.EnableWebSecurity = true;

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

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

// Advanced Example with HTML Assets
// Load external html assets: images, CSS and JavaScript.
// An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
Imports IronPdf

' Disable local disk access or cross-origin requests
Installation.EnableWebSecurity = True

' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()

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

' Advanced Example with HTML Assets
' Load external html assets: images, CSS and JavaScript.
' An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
Dim myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\site\assets\")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
VB   C#

Spire.PDF 示例:

using Spire.Pdf;
using Spire.Pdf.HtmlConverter;
using System.IO;
using System.Threading;
using System.Drawing;

namespace ConvertHtmlStringToPdfWithoutPlugin
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Create a PdfPageSettings object
            PdfPageSettings setting = new PdfPageSettings();

            //Save page size and margins through the object
            setting.Size = new SizeF(1000, 1000);
            setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);

            //Create a PdfHtmlLayoutFormat object
            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            //Set IsWaiting property to true
            htmlLayoutFormat.IsWaiting = true;

            //Read html string from a .html file
            string htmlString = File.ReadAllText(@"C:\Users\Administrator\Desktop\Document\Html\Sample.html");
            //Load HTML from html string using LoadFromHTML method
            Thread thread = new Thread(() =>
            { doc.LoadFromHTML(htmlString, true, setting, htmlLayoutFormat); });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            //Save to a PDF file
            doc.SaveToFile("HtmlStringToPdf.pdf");
        }
    }
}
using Spire.Pdf;
using Spire.Pdf.HtmlConverter;
using System.IO;
using System.Threading;
using System.Drawing;

namespace ConvertHtmlStringToPdfWithoutPlugin
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Create a PdfPageSettings object
            PdfPageSettings setting = new PdfPageSettings();

            //Save page size and margins through the object
            setting.Size = new SizeF(1000, 1000);
            setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);

            //Create a PdfHtmlLayoutFormat object
            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            //Set IsWaiting property to true
            htmlLayoutFormat.IsWaiting = true;

            //Read html string from a .html file
            string htmlString = File.ReadAllText(@"C:\Users\Administrator\Desktop\Document\Html\Sample.html");
            //Load HTML from html string using LoadFromHTML method
            Thread thread = new Thread(() =>
            { doc.LoadFromHTML(htmlString, true, setting, htmlLayoutFormat); });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            //Save to a PDF file
            doc.SaveToFile("HtmlStringToPdf.pdf");
        }
    }
}
Imports Spire.Pdf
Imports Spire.Pdf.HtmlConverter
Imports System.IO
Imports System.Threading
Imports System.Drawing

Namespace ConvertHtmlStringToPdfWithoutPlugin
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			'Create a PdfDocument object
			Dim doc As New PdfDocument()

			'Create a PdfPageSettings object
			Dim setting As New PdfPageSettings()

			'Save page size and margins through the object
			setting.Size = New SizeF(1000, 1000)
			setting.Margins = New Spire.Pdf.Graphics.PdfMargins(20)

			'Create a PdfHtmlLayoutFormat object
			Dim htmlLayoutFormat As New PdfHtmlLayoutFormat()

			'Set IsWaiting property to true
			htmlLayoutFormat.IsWaiting = True

			'Read html string from a .html file
			Dim htmlString As String = File.ReadAllText("C:\Users\Administrator\Desktop\Document\Html\Sample.html")
			'Load HTML from html string using LoadFromHTML method
			Dim thread As New Thread(Sub()
				doc.LoadFromHTML(htmlString, True, setting, htmlLayoutFormat)
			End Sub)
			thread.SetApartmentState(ApartmentState.STA)
			thread.Start()
			thread.Join()

			'Save to a PDF file
			doc.SaveToFile("HtmlStringToPdf.pdf")
		End Sub
	End Class
End Namespace
VB   C#

IronPDF使用Chrome的渲染引擎进行高保真HTML到PDF转换,凭借对现代网络标准的支持,确保准确呈现网页内容。 Spire.PDF 也提供强大的 HTML 转 PDF 转换,但其渲染精度可能不如 IronPDF,同时这种转换方法更为费时且需要手动处理。

因此,如果您正在寻找一种简便的方法来自动化您的HTML到PDF任务,同时保持PDF的高质量,那么IronPDF将是您的理想工具。

加密PDF文档

IronPDF

using IronPdf;
using System;

// Open an Encrypted File, alternatively create a new PDF from Html
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");

// Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = DateTime.Now;

// Edit file security settings
pdf.SecuritySettings.RemovePasswordsAndEncryption();
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key");
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;

// Change or set the document encryption password
pdf.Password = "my-password";
pdf.SaveAs("secured.pdf");
using IronPdf;
using System;

// Open an Encrypted File, alternatively create a new PDF from Html
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");

// Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = DateTime.Now;

// Edit file security settings
pdf.SecuritySettings.RemovePasswordsAndEncryption();
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key");
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;

// Change or set the document encryption password
pdf.Password = "my-password";
pdf.SaveAs("secured.pdf");
Imports IronPdf
Imports System

' Open an Encrypted File, alternatively create a new PDF from Html
Private pdf = PdfDocument.FromFile("encrypted.pdf", "password")

' Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = DateTime.Now

' Edit file security settings
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key")
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights

' Change or set the document encryption password
pdf.Password = "my-password"
pdf.SaveAs("secured.pdf")
VB   C#

Spire.PDF:

using Spire.Pdf;
using Spire.Pdf.Security;

//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();

//Load a sample PDF file
pdf.LoadFromFile(@"E:\Files\sample.pdf");

//Encrypt the PDF file with password
pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print 
 PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit);

//Save the result file
pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF);
using Spire.Pdf;
using Spire.Pdf.Security;

//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();

//Load a sample PDF file
pdf.LoadFromFile(@"E:\Files\sample.pdf");

//Encrypt the PDF file with password
pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print 
 PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit);

//Save the result file
pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF);
Imports Spire.Pdf
Imports Spire.Pdf.Security

'Create a PdfDocument object
Private pdf As New PdfDocument()

'Load a sample PDF file
pdf.LoadFromFile("E:\Files\sample.pdf")

'Encrypt the PDF file with password
pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit)

'Save the result file
pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF)
VB   C#

这两个库都提供了易于使用的方法来加密PDF,并设置加密PDF文档的可读性。 IronPDF 提供了一种简单的方法,同时仍然让您完全掌控 PDF 的安全设置。 Spire.PDF 的流程稍短,但仍包括设置权限的附加选项。

PDF内容编辑

IronPDF

using IronPdf;

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

// Redact 'are' phrase from all pages
pdf.RedactTextOnAllPages("are");

pdf.SaveAs("redacted.pdf");
using IronPdf;

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

// Redact 'are' phrase from all pages
pdf.RedactTextOnAllPages("are");

pdf.SaveAs("redacted.pdf");
Imports IronPdf

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

' Redact 'are' phrase from all pages
pdf.RedactTextOnAllPages("are")

pdf.SaveAs("redacted.pdf")
VB   C#

Spire.PDF:

Spire.PDF没有内置专门的修订工具。 然而,您仍然可以通过在您希望编辑的内容上绘制矩形来编辑内容。(如下所示)或通过提取并删除您想要编辑的文本。

using Spire.Pdf;
using Spire.Pdf.Graphics;

// Specify the input PDF file path
        string inputPdfFilePath = "path/to/your/input.pdf";

        // Specify the output redacted PDF file path
        string outputPdfFilePath = "path/to/your/redacted_output.pdf";

        // Create a new PdfDocument object
        PdfDocument pdfDocument = new PdfDocument();

        // Load the existing PDF document
        pdfDocument.LoadFromFile(inputPdfFilePath);

        // Redact content on each page
        foreach (PdfPageBase page in pdfDocument.Pages)
        {
            // Define the area to redact (e.g., coordinates and size of the rectangle)
            RectangleF redactArea = new RectangleF(100, 100, 200, 50); // Example coordinates and size

            // Apply redaction
            page.Canvas.DrawRectangle(new PdfSolidBrush(Color.Black), redactArea);
        }      
        // Save the redacted PDF document
        pdfDocument.SaveToFile(outputPdfFilePath);
using Spire.Pdf;
using Spire.Pdf.Graphics;

// Specify the input PDF file path
        string inputPdfFilePath = "path/to/your/input.pdf";

        // Specify the output redacted PDF file path
        string outputPdfFilePath = "path/to/your/redacted_output.pdf";

        // Create a new PdfDocument object
        PdfDocument pdfDocument = new PdfDocument();

        // Load the existing PDF document
        pdfDocument.LoadFromFile(inputPdfFilePath);

        // Redact content on each page
        foreach (PdfPageBase page in pdfDocument.Pages)
        {
            // Define the area to redact (e.g., coordinates and size of the rectangle)
            RectangleF redactArea = new RectangleF(100, 100, 200, 50); // Example coordinates and size

            // Apply redaction
            page.Canvas.DrawRectangle(new PdfSolidBrush(Color.Black), redactArea);
        }      
        // Save the redacted PDF document
        pdfDocument.SaveToFile(outputPdfFilePath);
Imports Spire.Pdf
Imports Spire.Pdf.Graphics

' Specify the input PDF file path
		Private inputPdfFilePath As String = "path/to/your/input.pdf"

		' Specify the output redacted PDF file path
		Private outputPdfFilePath As String = "path/to/your/redacted_output.pdf"

		' Create a new PdfDocument object
		Private pdfDocument As New PdfDocument()

		' Load the existing PDF document
		pdfDocument.LoadFromFile(inputPdfFilePath)

		' Redact content on each page
		For Each page As PdfPageBase In pdfDocument.Pages
			' Define the area to redact (e.g., coordinates and size of the rectangle)
			Dim redactArea As New RectangleF(100, 100, 200, 50) ' Example coordinates and size

			' Apply redaction
			page.Canvas.DrawRectangle(New PdfSolidBrush(Color.Black), redactArea)
		Next page
		' Save the redacted PDF document
		pdfDocument.SaveToFile(outputPdfFilePath)
VB   C#

IronPDF通过其强大而简单的修订工具简化了修订过程。 由于缺少内置的修订工具,Spire.PDF需要手动进行修订操作,这会降低效率。

签署 PDF

IronPDF

using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>foo</h1>");

// Create X509Certificate2 object with X509KeyStorageFlags set to Exportable
X509Certificate2 cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);

// Create PDF digital signature with the PdfSignature object
var sig = new PdfSignature(cert);

// Sign PDF document
pdf.Sign(sig);
pdf.SaveAs("signed.pdf");
using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>foo</h1>");

// Create X509Certificate2 object with X509KeyStorageFlags set to Exportable
X509Certificate2 cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);

// Create PDF digital signature with the PdfSignature object
var sig = new PdfSignature(cert);

// Sign PDF document
pdf.Sign(sig);
pdf.SaveAs("signed.pdf");
Imports IronPdf
Imports IronPdf.Signing
Imports System.Security.Cryptography.X509Certificates

Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>foo</h1>")

' Create X509Certificate2 object with X509KeyStorageFlags set to Exportable
Private cert As New X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable)

' Create PDF digital signature with the PdfSignature object
Private sig = New PdfSignature(cert)

' Sign PDF document
pdf.Sign(sig)
pdf.SaveAs("signed.pdf")
VB   C#

Spire.PDF 示例:

using system;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Security;
using Spire.Pdf.Graphics;

//Create a PdfDocument object
PdfDocument doc = new PdfDocument();

//Load a sample PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

//Load the certificate
PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");

//Create a PdfSignature object and specify its position and size
PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
24
RectangleF rectangleF = new RectangleF(doc.Pages[0].ActualSize.Width - 260 - 54 , 200, 260, 110);
signature.Bounds = rectangleF;
signature.Certificated = true;

//Set the graphics mode to ImageAndSignDetail
signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;

//Set the signature content
signature.NameLabel = "Signer:";
signature.Name = "Gary";
signature.ContactInfoLabel = "Phone:";
signature.ContactInfo = "0123456";
signature.DateLabel = "Date:";
signature.Date = DateTime.Now;
signature.LocationInfoLabel = "Location:";
signature.LocationInfo = "USA";
signature.ReasonLabel = "Reason:";
signature.Reason = "I am the author";
signature.DistinguishedNameLabel = "DN:";
signature.DistinguishedName = signature.Certificate.IssuerName.Name;

//Set the signature image source
signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\handwrittingSignature.png");

//Set the signature font
signature.SignDetailsFont = new PdfTrueTypeFont(new Font("Arial Unicode MS", 12f, FontStyle.Regular));

//Set the document permission to forbid changes but allow form fill
signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges 
 PdfCertificationFlags.AllowFormFill;

//Save to file
doc.SaveToFile("VisiableSignature.pdf");
doc.Close();
using system;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Security;
using Spire.Pdf.Graphics;

//Create a PdfDocument object
PdfDocument doc = new PdfDocument();

//Load a sample PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

//Load the certificate
PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");

//Create a PdfSignature object and specify its position and size
PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
24
RectangleF rectangleF = new RectangleF(doc.Pages[0].ActualSize.Width - 260 - 54 , 200, 260, 110);
signature.Bounds = rectangleF;
signature.Certificated = true;

//Set the graphics mode to ImageAndSignDetail
signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;

//Set the signature content
signature.NameLabel = "Signer:";
signature.Name = "Gary";
signature.ContactInfoLabel = "Phone:";
signature.ContactInfo = "0123456";
signature.DateLabel = "Date:";
signature.Date = DateTime.Now;
signature.LocationInfoLabel = "Location:";
signature.LocationInfo = "USA";
signature.ReasonLabel = "Reason:";
signature.Reason = "I am the author";
signature.DistinguishedNameLabel = "DN:";
signature.DistinguishedName = signature.Certificate.IssuerName.Name;

//Set the signature image source
signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\handwrittingSignature.png");

//Set the signature font
signature.SignDetailsFont = new PdfTrueTypeFont(new Font("Arial Unicode MS", 12f, FontStyle.Regular));

//Set the document permission to forbid changes but allow form fill
signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges 
 PdfCertificationFlags.AllowFormFill;

//Save to file
doc.SaveToFile("VisiableSignature.pdf");
doc.Close();
Imports system
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Security
Imports Spire.Pdf.Graphics

'Create a PdfDocument object
Private doc As New PdfDocument()

'Load a sample PDF file
doc.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf")

'Load the certificate
Dim cert As New PdfCertificate("C:\Users\Administrator\Desktop\MyCertificate.pfx", "e-iceblue")

'Create a PdfSignature object and specify its position and size
Dim signature As New PdfSignature(doc, doc.Pages(doc.Pages.Count - 1), cert, "MySignature")
24 RectangleF rectangleF = New RectangleF(doc.Pages(0).ActualSize.Width - 260 - 54, 200, 260, 110)
signature.Bounds = rectangleF
signature.Certificated = True

'Set the graphics mode to ImageAndSignDetail
signature.GraphicsMode = GraphicMode.SignImageAndSignDetail

'Set the signature content
signature.NameLabel = "Signer:"
signature.Name = "Gary"
signature.ContactInfoLabel = "Phone:"
signature.ContactInfo = "0123456"
signature.DateLabel = "Date:"
signature.Date = DateTime.Now
signature.LocationInfoLabel = "Location:"
signature.LocationInfo = "USA"
signature.ReasonLabel = "Reason:"
signature.Reason = "I am the author"
signature.DistinguishedNameLabel = "DN:"
signature.DistinguishedName = signature.Certificate.IssuerName.Name

'Set the signature image source
signature.SignImageSource = PdfImage.FromFile("C:\Users\Administrator\Desktop\handwrittingSignature.png")

'Set the signature font
signature.SignDetailsFont = New PdfTrueTypeFont(New Font("Arial Unicode MS", 12F, FontStyle.Regular))

'Set the document permission to forbid changes but allow form fill
signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges PdfCertificationFlags.AllowFormFill

'Save to file
doc.SaveToFile("VisiableSignature.pdf")
doc.Close()
VB   C#

数字签名PDF在各种场合中都很有用,比如用来验证PDF文档,或者仅仅是在新项目上签名。 IronPDF 提供了一种简单的方法来添加数字签名,使用 IronPDF 您可以轻松自动化数字签名过程。 Spire.PDF也支持PDF的数字签名,不过这个过程可能更加手动,需要更多的工作来实现。

水印 PDF

IronPDF

using IronPdf;

// Stamps a Watermark onto a new or existing PDF
var renderer = new ChromePdfRenderer();

var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs(@"C:\Path\To\Watermarked.pdf");
using IronPdf;

// Stamps a Watermark onto a new or existing PDF
var renderer = new ChromePdfRenderer();

var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs(@"C:\Path\To\Watermarked.pdf");
Imports IronPdf

' Stamps a Watermark onto a new or existing PDF
Private renderer = New ChromePdfRenderer()

Private pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center)
pdf.SaveAs("C:\Path\To\Watermarked.pdf")
VB   C#

Spire.PDF 示例:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();

//Load a sample PDF document
pdf.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");

//Create a PdfTrueTypeFont object
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 50f), true);

//Set the watermark text
string text = "CONFIDENTIAL";

//Measure the text size
SizeF textSize = font.MeasureString(text);

            //Calculate the values of two offset variables,
            //which will be used to calculate the translation amount of the coordinate system
float offset1 = (float)(textSize.Width * System.Math.Sqrt(2) / 4);
float offset2 = (float)(textSize.Height * System.Math.Sqrt(2) / 4);

        //Traverse all the pages in the document
    foreach (PdfPageBase page in pdf.Pages)
        {
    //Set the page transparency
    page.Canvas.SetTransparency(0.8f);

    //Translate the coordinate system by specified coordinates
    page.Canvas.TranslateTransform(page.Canvas.Size.Width / 2 - offset1 - offset2, page.Canvas.Size.Height / 2 + offset1 - offset2);

        //Rotate the coordinate system 45 degrees counterclockwise
        page.Canvas.RotateTransform(-45);

        //Draw watermark text on the page
        page.Canvas.DrawString(text, font, PdfBrushes.DarkGray, 0, 0);
            }

//Save the changes to another file
pdf.SaveToFile("TextWatermark.pdf");
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();

//Load a sample PDF document
pdf.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");

//Create a PdfTrueTypeFont object
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 50f), true);

//Set the watermark text
string text = "CONFIDENTIAL";

//Measure the text size
SizeF textSize = font.MeasureString(text);

            //Calculate the values of two offset variables,
            //which will be used to calculate the translation amount of the coordinate system
float offset1 = (float)(textSize.Width * System.Math.Sqrt(2) / 4);
float offset2 = (float)(textSize.Height * System.Math.Sqrt(2) / 4);

        //Traverse all the pages in the document
    foreach (PdfPageBase page in pdf.Pages)
        {
    //Set the page transparency
    page.Canvas.SetTransparency(0.8f);

    //Translate the coordinate system by specified coordinates
    page.Canvas.TranslateTransform(page.Canvas.Size.Width / 2 - offset1 - offset2, page.Canvas.Size.Height / 2 + offset1 - offset2);

        //Rotate the coordinate system 45 degrees counterclockwise
        page.Canvas.RotateTransform(-45);

        //Draw watermark text on the page
        page.Canvas.DrawString(text, font, PdfBrushes.DarkGray, 0, 0);
            }

//Save the changes to another file
pdf.SaveToFile("TextWatermark.pdf");
Imports System
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing

'Create a PdfDocument object
Private pdf As New PdfDocument()

'Load a sample PDF document
pdf.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf")

'Create a PdfTrueTypeFont object
Dim font As New PdfTrueTypeFont(New Font("Arial", 50F), True)

'Set the watermark text
Dim text As String = "CONFIDENTIAL"

'Measure the text size
Dim textSize As SizeF = font.MeasureString(text)

			'Calculate the values of two offset variables,
			'which will be used to calculate the translation amount of the coordinate system
Dim offset1 As Single = CSng(textSize.Width * Math.Sqrt(2) / 4)
Dim offset2 As Single = CSng(textSize.Height * Math.Sqrt(2) / 4)

		'Traverse all the pages in the document
	For Each page As PdfPageBase In pdf.Pages
	'Set the page transparency
	page.Canvas.SetTransparency(0.8F)

	'Translate the coordinate system by specified coordinates
	page.Canvas.TranslateTransform(page.Canvas.Size.Width \ 2 - offset1 - offset2, page.Canvas.Size.Height \ 2 + offset1 - offset2)

		'Rotate the coordinate system 45 degrees counterclockwise
		page.Canvas.RotateTransform(-45)

		'Draw watermark text on the page
		page.Canvas.DrawString(text, font, PdfBrushes.DarkGray, 0, 0)
	Next page

'Save the changes to another file
pdf.SaveToFile("TextWatermark.pdf")
VB   C#

IronPDF 提供了一种简单的方法来添加文本水印,同时让您完全控制水印的位置和设计。 IronPDF 使用 HTML 和 CSS 意味着如果您对这些语言有经验,过程会更简单。 Spire.PDF的方法较为耗时,采用更多手动处理,但仍提供了一个强大的水印工具,允许完全控制设计和位置。

标记图像 HTML 文本

IronPDF

using IronPdf;
using IronPdf.Editing;

// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>");

// Create text stamper
TextStamper textStamper = new TextStamper()
{
    Text = "Text Stamper!",
    FontFamily = "Bungee Spice",
    UseGoogleFont = true,
    FontSize = 30,
    IsBold = true,
    IsItalic = true,
    VerticalAlignment = VerticalAlignment.Top,
};

// Stamp the text stamper
pdf.ApplyStamp(textStamper);
pdf.SaveAs("stampText.pdf");

// Create image stamper
ImageStamper imageStamper = new ImageStamper(new Uri("https://ironpdf.com/img/svgs/iron-pdf-logo.svg"))
{
    VerticalAlignment = VerticalAlignment.Top,
};

// Stamp the image stamper
pdf.ApplyStamp(imageStamper, 0);
pdf.SaveAs("stampImage.pdf");
using IronPdf;
using IronPdf.Editing;

// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>");

// Create text stamper
TextStamper textStamper = new TextStamper()
{
    Text = "Text Stamper!",
    FontFamily = "Bungee Spice",
    UseGoogleFont = true,
    FontSize = 30,
    IsBold = true,
    IsItalic = true,
    VerticalAlignment = VerticalAlignment.Top,
};

// Stamp the text stamper
pdf.ApplyStamp(textStamper);
pdf.SaveAs("stampText.pdf");

// Create image stamper
ImageStamper imageStamper = new ImageStamper(new Uri("https://ironpdf.com/img/svgs/iron-pdf-logo.svg"))
{
    VerticalAlignment = VerticalAlignment.Top,
};

// Stamp the image stamper
pdf.ApplyStamp(imageStamper, 0);
pdf.SaveAs("stampImage.pdf");
Imports IronPdf
Imports IronPdf.Editing

' Instantiate Renderer
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>")

' Create text stamper
Private textStamper As New TextStamper() With {
	.Text = "Text Stamper!",
	.FontFamily = "Bungee Spice",
	.UseGoogleFont = True,
	.FontSize = 30,
	.IsBold = True,
	.IsItalic = True,
	.VerticalAlignment = VerticalAlignment.Top
}

' Stamp the text stamper
pdf.ApplyStamp(textStamper)
pdf.SaveAs("stampText.pdf")

' Create image stamper
Dim imageStamper As New ImageStamper(New Uri("https://ironpdf.com/img/svgs/iron-pdf-logo.svg")) With {.VerticalAlignment = VerticalAlignment.Top}

' Stamp the image stamper
pdf.ApplyStamp(imageStamper, 0)
pdf.SaveAs("stampImage.pdf")
VB   C#

Spire.PDF:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

//save graphics state
PdfGraphicsState state = page.Canvas.Save();

//Draw the text - transform          
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 18f);
PdfSolidBrush brush1 = new PdfSolidBrush(Color.DeepSkyBlue);
PdfSolidBrush brush2 = new PdfSolidBrush(Color.CadetBlue);
page.Canvas.TranslateTransform(20, 200);
page.Canvas.ScaleTransform(1f, 0.6f);
page.Canvas.SkewTransform(-10, 0);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush1, 0, 0);
page.Canvas.SkewTransform(10, 0);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, 0);
page.Canvas.ScaleTransform(1f, -1f);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, -2 * 18);

//restore graphics
page.Canvas.Restore(state);
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

//save graphics state
PdfGraphicsState state = page.Canvas.Save();

//Draw the text - transform          
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 18f);
PdfSolidBrush brush1 = new PdfSolidBrush(Color.DeepSkyBlue);
PdfSolidBrush brush2 = new PdfSolidBrush(Color.CadetBlue);
page.Canvas.TranslateTransform(20, 200);
page.Canvas.ScaleTransform(1f, 0.6f);
page.Canvas.SkewTransform(-10, 0);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush1, 0, 0);
page.Canvas.SkewTransform(10, 0);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, 0);
page.Canvas.ScaleTransform(1f, -1f);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, -2 * 18);

//restore graphics
page.Canvas.Restore(state);
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing

'save graphics state
Private state As PdfGraphicsState = page.Canvas.Save()

'Draw the text - transform          
Private font As New PdfFont(PdfFontFamily.Helvetica, 18F)
Private brush1 As New PdfSolidBrush(Color.DeepSkyBlue)
Private brush2 As New PdfSolidBrush(Color.CadetBlue)
page.Canvas.TranslateTransform(20, 200)
page.Canvas.ScaleTransform(1F, 0.6F)
page.Canvas.SkewTransform(-10, 0)
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush1, 0, 0)
page.Canvas.SkewTransform(10, 0)
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, 0)
page.Canvas.ScaleTransform(1F, -1F)
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, -2 * 18)

'restore graphics
page.Canvas.Restore(state)
VB   C#

IronPDF 的文本和图像盖章工具是一款强大且易于使用的盖章工具,当您应用盖章内容时,它采用类似于 HTML 和 CSS 的方法。 虽然Spire.PDF也提供了一个基本的文本盖章工具,但将盖章文本应用于PDF文件需要更多的工作。

DOCX 转 PDF

IronPDF

using IronPdf;

// Instantiate Renderer
DocxToPdfRenderer renderer = new DocxToPdfRenderer();

// Render from DOCX file
PdfDocument pdf = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx");

// Save the PDF
pdf.SaveAs("pdfFromDocx.pdf");
using IronPdf;

// Instantiate Renderer
DocxToPdfRenderer renderer = new DocxToPdfRenderer();

// Render from DOCX file
PdfDocument pdf = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx");

// Save the PDF
pdf.SaveAs("pdfFromDocx.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer As New DocxToPdfRenderer()

' Render from DOCX file
Private pdf As PdfDocument = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx")

' Save the PDF
pdf.SaveAs("pdfFromDocx.pdf")
VB   C#

Spire.PDF:

Spire.PDF本身无法将DOCX转换为PDF,但可以使用Spire.Doc库进行此转换,然后您可以继续使用Spire.PDF处理生成的PDF。

using Spire.Doc;

// Create a Document object
Document doc = new Document();

// Load a Word document
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

// Save the document to PDF
doc.SaveToFile("ToPDF.pdf", FileFormat.PDF);

// Dispose resources
doc.Dispose();
using Spire.Doc;

// Create a Document object
Document doc = new Document();

// Load a Word document
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

// Save the document to PDF
doc.SaveToFile("ToPDF.pdf", FileFormat.PDF);

// Dispose resources
doc.Dispose();
Imports Spire.Doc

' Create a Document object
Private doc As New Document()

' Load a Word document
doc.LoadFromFile("C:\Users\Administrator\Desktop\Sample.docx")

' Save the document to PDF
doc.SaveToFile("ToPDF.pdf", FileFormat.PDF)

' Dispose resources
doc.Dispose()
VB   C#

IronPDF 提供对直接将 DOCX 转换为 PDF 的内置支持,这意味着您无需安装额外的库来处理此任务,从而节省时间。 另一方面,Spire.PDF 无法直接将 DOCX 转换为 PDF,因此您需要安装 Spire.Doc 库将 DOCX 文件转换为 PDF。

代码示例比较摘要

以下是总结IronPDF与Spire.PDF for .NET在代码实现方面关键差异的对比表:

Spire Pdf Html To Pdf 1 related to 代码示例比较摘要

价格和许可:IronPDF与Spire.PDF for .NET库的对比

IronPDF 定价和许可

IronPDF拥有不同级别和购买许可证的附加功能。 开发者也可以购买Iron Suite它使您可以仅以两个产品的价格访问IronSoftware的所有产品。 如果您尚未准备购买许可证,IronPDF提供了一种免费试用持续30天。

  • 永久许可证: 根据您团队的规模、项目需求和地点数量提供一系列永久许可证。 每种许可类型都包括电子邮件支持。
  • Lite License:此许可证价格为749美元,支持一个开发者、一个地点和一个项目。
  • Plus License(加强许可): 支持三名开发者、三个地点和三个项目,这是从轻量版许可升级的下一步,费用为$1,499。Plus许可还提供聊天支持和电话支持,除了基本的电子邮件支持。
  • 专业许可证: 此许可证适用于较大的团队,支持10名开发者、10个位置和10个项目,价格为2999美元。它提供与之前等级相同的联系支持渠道,但也提供屏幕共享支持。
  • 免版税重新分发: IronPDF 的许可还提供额外 $1,999 的免版税重新分发覆盖。
  • 持续不断的产品支持: IronPDF为用户提供持续的产品更新、安全功能升级以及他们工程团队的支持,费用为每年999美元或一次性支付1999美元,享受5年的服务。
  • IronSuite:花费 $1,498,您将获得所有Iron Software产品的访问权,包括IronPDF、IronOCR、IronWord、IronXL、IronBarcode、IronQR、IronZIP、IronPrint和IronWebScraper。

    Spire Pdf Html To Pdf 2 related to IronPDF 定价和许可

Spire.PDF

Spire.PDF根据您的需求提供多种许可证。

  • 免费版本: Spire.PDF 确实提供免费版本,这个完全免费的 PDF API 限制在 10 页 PDF,超过此限制需要购买付费许可证。
  • 开发者订阅:价格为每年 $999 或 $1,199,具体取决于您需要的支持类型。此选项适用于需要构建 PDF 相关功能但不需要 OEM 分发权限的开发者。
  • 开发者 OEM 订阅:根据所需支持的多少,费用大约为每年 $2,549 - $4,248,包括免费升级、高级支持,以及将应用程序分发给最终用户的能力。
  • Site Small Business: 根据您需要的支持,该许可级别的价格为 $4,599 或 $7,598,支持最多 10 个位置的 10 位开发人员,一年更新,以及免费的在线技术资源。
  • 网站 OEM 订阅:费用为每年 $13,088 - $16,687,具体取决于您所需的支持类型,旨在针对需要将应用程序部署到多个地点的大型企业。

文档和支持:IronPDF vs. Spire.PDF for .NET

IronPDF

IronPDF在提供广泛文档和支持方面表现出色:

  • 全面的文档:涵盖所有功能的广泛且用户友好的文档。
  • 24/5 支持:提供活跃的工程师支持。
  • 视频教程:详细的视频指南可在YouTube上找到。
  • 社区论坛:为了提供额外支持而设立的活跃社区。
  • 定期更新:每月产品更新,确保具备最新功能和安全补丁。
  • PDF API 参考: 提供 API 参考,让您充分利用我们的工具所提供的功能。

    documentation on our website.文献资料,并访问IronSoftware YouTube频道.

Spire.PDF for .NET 文档和支持

  • 论坛: Spire.PDF 有一个论坛,用户可以在其中互相交流,分享使用技巧、用途以及在 Spire.PDF 中遇到的问题。
  • 代码示例: Spire.PDF 在其网站上提供代码示例,展示如何在各种使用场景中使用该产品。
  • 新闻通讯: Spire.PDF 提供开发者新闻通讯,用于更新公告和其他重要信息。
  • 支持: Spire.PDF 提供多种支持级别和响应时间,具体取决于您持有的许可版本。

结论

总之,IronPDF 和 Spire.PDF for .NET 是在 .NET 应用程序中处理 PDF 文档的强大工具。 IronPDF在易用性、跨平台兼容性和对现代网页标准的支持方面表现出色,是您在处理PDF文档时提升水平的优选。 Spire.PDF 提供了全面的功能集,但对于复杂任务可能需要更多的努力,并且可能缺乏 IronPDF 所能提供的丰富、广泛的功能集。

您可以尝试 0 天免费试用 查看他们的可用功能。

< 前一页
ActivePDF DocConverter 教程和对比 IronPDF
下一步 >
PDFSharp HTML 到 PDF 示例和教程比较

准备开始了吗? 版本: 2024.12 刚刚发布

免费NuGet下载 总下载量: 11,622,374 查看许可证 >