在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
C# 生成 PDF 的功能对于许多现代应用程序(从创建报告到发票系统)都至关重要。 在本文中,我们将探讨六种常用的方法来生成PDF译文必须使用 C# 编写文件,突出基于代码的库,如:.NET、Java、Python 或 Node js。IronPDF翻译的内容包括:.NET、Java、Python 或 Node js。 无论您是需要在网络应用程序中动态生成 PDF 文件,还是只需从现有文档创建 PDF 文件,这些工具都能满足您的需求。
破损图片 添加自 Pixabay,请从您的文件中选择或将图片拖放到此处。
IronPDF是一款优质的 .NET PDF 库,专为需要将 HTML 转换为 PDF 文件的开发人员设计。 IronPDF 使用基于 Chromium 的渲染引擎来确保精确的转换,使其成为想要用 C# 将 HTML 页面或基于 Web 的报告转换为 PDF 文件的 Web 应用程序的最佳选择。 该工具以其对现有 PDF 文档的强大处理能力而著称,并提供编辑、合并或拆分 PDF 的功能。
IronPDF 可通过 NuGet 包管理器轻松集成到 C# 项目中,只需几行代码,您就可以开始生成 PDF 文档。 这是一款多功能工具,既可用于动态 HTML 内容,也可用于服务器生成的 PDF 文件输出。
using IronPdf;
class Program
{
static void Main()
{
string html = "<h1>Hello, World!</h1><p>This PDF is generated from HTML.</p>";
ChromePdfRenderer renderer = new ChromePdfRenderer(); // Create an instance of ChromePdfRenderer
PdfDocument pdf = renderer.RenderHtmlAsPdf(html); // Render the HTML as a PDF document
pdf.SaveAs("Generated.pdf"); // Save the PDF to a specified file
}
}
using IronPdf;
class Program
{
static void Main()
{
string html = "<h1>Hello, World!</h1><p>This PDF is generated from HTML.</p>";
ChromePdfRenderer renderer = new ChromePdfRenderer(); // Create an instance of ChromePdfRenderer
PdfDocument pdf = renderer.RenderHtmlAsPdf(html); // Render the HTML as a PDF document
pdf.SaveAs("Generated.pdf"); // Save the PDF to a specified file
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main()
Dim html As String = "<h1>Hello, World!</h1><p>This PDF is generated from HTML.</p>"
Dim renderer As New ChromePdfRenderer() ' Create an instance of ChromePdfRenderer
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html) ' Render the HTML as a PDF document
pdf.SaveAs("Generated.pdf") ' Save the PDF to a specified file
End Sub
End Class
名称空间导入: 使用 IronPdf;导入 IronPDF 库以访问其类和方法。
HTML 字符串:变量 HTML 包含您要转换为 PDF 的 HTML 内容。
渲染器实例: new ChromePdfRenderer(); 创建 HtmlToPdf 类的实例,该类提供将 HTML 内容渲染为 PDF 格式的方法。
渲染 PDF: PdfDocument PDF = renderer.RenderHtmlAsPdf(html); 将 HTML 字符串转换为 PDF 文档。
iTextSharp 是一个成熟的 .NET PDF 库,为创建和编辑 PDF 文件提供了广泛的功能。 它广泛应用于金融和法律等行业,在这些行业中,文件必须是定制的、安全的。 iTextSharp 允许您从头开始创建 PDF 文件、填写表格和修改 PDF 文件,并提供对文档内容的广泛控制。 对于需要生成具有精确布局和动态数据的 PDF 文件(如发票或合同)的企业应用程序来说,它尤其有用。
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Mapping;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using Voodoo;
namespace Helpers
{
public class PdfGenerator
{
public static Byte[] GeneratePdfFromFragment(string htmlFragment)
{
var html = string.Format(@"
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
<head>
<style type='text/css'>
table,td {{border: 1px solid black;}}
div {{ white-space: nowrap; padding: 2px;}}
table{{ border-collapse: collapse; width: 100%; empty-cells: show;}}
body table {{font-size: 50%;}}
th {{width:500px; height: 28px;}}
td {{width:300px; height: 28px;}}
</style>
</head><body>{0}</body></html>", htmlFragment);
return generate(html);
}
public static Byte[] GeneratePdfFromPage(string htmlPage)
{
return generate(htmlPage);
}
private static Byte[] generate (string html)
{
using (var memoryStream = new MemoryStream())
{
var pdfDocument = new Document(PageSize.LETTER);
var pdfWriter = PdfWriter.GetInstance(pdfDocument, memoryStream);
pdfDocument.Open();
using (var fw = new StringReader(html))
{
XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, fw);
pdfDocument.Close();
fw.Close();
}
return memoryStream.ToArray();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Mapping;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using Voodoo;
namespace Helpers
{
public class PdfGenerator
{
public static Byte[] GeneratePdfFromFragment(string htmlFragment)
{
var html = string.Format(@"
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
<head>
<style type='text/css'>
table,td {{border: 1px solid black;}}
div {{ white-space: nowrap; padding: 2px;}}
table{{ border-collapse: collapse; width: 100%; empty-cells: show;}}
body table {{font-size: 50%;}}
th {{width:500px; height: 28px;}}
td {{width:300px; height: 28px;}}
</style>
</head><body>{0}</body></html>", htmlFragment);
return generate(html);
}
public static Byte[] GeneratePdfFromPage(string htmlPage)
{
return generate(htmlPage);
}
private static Byte[] generate (string html)
{
using (var memoryStream = new MemoryStream())
{
var pdfDocument = new Document(PageSize.LETTER);
var pdfWriter = PdfWriter.GetInstance(pdfDocument, memoryStream);
pdfDocument.Open();
using (var fw = new StringReader(html))
{
XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, fw);
pdfDocument.Close();
fw.Close();
}
return memoryStream.ToArray();
}
}
}
}
Imports System
Imports System.Collections.Generic
Imports System.Data.Entity.Core.Mapping
Imports System.IO
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml
Imports Voodoo
Namespace Helpers
Public Class PdfGenerator
Public Shared Function GeneratePdfFromFragment(ByVal htmlFragment As String) As Byte()
Dim html = String.Format("
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
<head>
<style type='text/css'>
table,td {{border: 1px solid black;}}
div {{ white-space: nowrap; padding: 2px;}}
table{{ border-collapse: collapse; width: 100%; empty-cells: show;}}
body table {{font-size: 50%;}}
th {{width:500px; height: 28px;}}
td {{width:300px; height: 28px;}}
</style>
</head><body>{0}</body></html>", htmlFragment)
Return generate(html)
End Function
Public Shared Function GeneratePdfFromPage(ByVal htmlPage As String) As Byte()
Return generate(htmlPage)
End Function
Private Shared Function generate(ByVal html As String) As Byte()
Using memoryStream As New MemoryStream()
Dim pdfDocument = New Document(PageSize.LETTER)
Dim pdfWriter = PdfWriter.GetInstance(pdfDocument, memoryStream)
pdfDocument.Open()
Using fw = New StringReader(html)
XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, fw)
pdfDocument.Close()
fw.Close()
End Using
Return memoryStream.ToArray()
End Using
End Function
End Class
End Namespace
GeneratePdfFromFragment:获取 HTML 片段(如部分 HTML 文档) 并将其转换为完整的 HTML 结构,将其封装在一个基本的
和模板。 然后调用内部生成方法。GeneratePdfFromPage:接受完整的 HTML 页面并直接调用生成方法。
生成:该方法处理 HTML 到 PDF 的转换。
它将初始化一个 MemoryStream,以便在内存中保存生成的 PDF。
4.
PDFSharp是一个轻量级、开源的.NET PDF库,是基本PDF创建任务的理想选择。 如果您的应用程序只需要添加文本、图像或表格等简单操作,那么 PdfSharp 是用 C# 生成 PDF 文档的一个易用选项。 它缺乏 HTML 到 PDF 转换等高级功能,但在用 C# 生成中小型 PDF 文件的简易性方面却大放异彩。
using PdfSharp.Pdf;
using PdfSharp.Drawing;
class Program
{
static void Main()
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PdfSharp";
// Add a page to the document
PdfPage page = document.AddPage();
// Create an XGraphics object to draw on the page
XGraphics gfx = XGraphics.FromPdfPage(page);
// Set a font to use for drawing text
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
// Draw the text on the PDF page
gfx.DrawString("Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
// Save the document to disk
document.Save("Generated.pdf");
}
}
using PdfSharp.Pdf;
using PdfSharp.Drawing;
class Program
{
static void Main()
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PdfSharp";
// Add a page to the document
PdfPage page = document.AddPage();
// Create an XGraphics object to draw on the page
XGraphics gfx = XGraphics.FromPdfPage(page);
// Set a font to use for drawing text
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
// Draw the text on the PDF page
gfx.DrawString("Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
// Save the document to disk
document.Save("Generated.pdf");
}
}
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Friend Class Program
Shared Sub Main()
' Create a new PDF document
Dim document As New PdfDocument()
document.Info.Title = "Created with PdfSharp"
' Add a page to the document
Dim page As PdfPage = document.AddPage()
' Create an XGraphics object to draw on the page
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
' Set a font to use for drawing text
Dim font As New XFont("Verdana", 20, XFontStyle.Bold)
' Draw the text on the PDF page
gfx.DrawString("Hello, World!", font, XBrushes.Black, New XRect(0, 0, page.Width, page.Height), XStringFormats.Center)
' Save the document to disk
document.Save("Generated.pdf")
End Sub
End Class
Syncfusion PDF Library 是一款高性能的综合工具,专为需要在各种应用程序中处理 PDF 的企业而设计。 这是 Syncfusion 套件的一部分,该套件提供适用于各种格式和平台的库。 PDF 库之所以脱颖而出,是因为它具有广泛的功能集,不仅可以创建简单的文档,还可以进行详细的操作,包括填写表格、数字签名和文档安全。
using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
class Program
{
static void Main()
{
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a page to the document.
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;
//Set the standard font.
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
//Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));
//Save the document.
document.Save("Output.pdf");
//Close the document.
document.Close(true);
}
}
using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
class Program
{
static void Main()
{
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a page to the document.
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;
//Set the standard font.
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
//Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));
//Save the document.
document.Save("Output.pdf");
//Close the document.
document.Close(true);
}
}
Imports Syncfusion.Pdf
Imports Syncfusion.Pdf.Parsing
Imports Syncfusion.Pdf.Graphics
Imports Syncfusion.Pdf.Grid
Friend Class Program
Shared Sub Main()
'Create a new PDF document.
Dim document As New PdfDocument()
'Add a page to the document.
Dim page As PdfPage = document.Pages.Add()
'Create PDF graphics for the page.
Dim graphics As PdfGraphics = page.Graphics
'Set the standard font.
Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 20)
'Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, New PointF(0, 0))
'Save the document.
document.Save("Output.pdf")
'Close the document.
document.Close(True)
End Sub
End Class
PDFShift 是一项基于云的服务,旨在将 HTML 转换为 PDF 文件。 它可通过其 API 与 C# 应用程序顺利集成,让您可以将动态生成的 HTML 网页转换为专业品质的 PDF。 PDFShift 尤其适用于希望根据 HTML 内容(如发票或报告)按需生成 PDF 文档的网络开发人员。 由于 PDFShift 完全通过其 REST API 运行,因此您只需向服务发送几行 HTML 代码,即可收到可下载的 PDF 文件。 这是一个基于网络生成 PDF 文件的简单、可扩展的解决方案。
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
string htmlContent = "<h1>Hello, World!</h1><p>This is generated using PDFShift API.</p>";
var content = new StringContent(htmlContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("https://api.pdfshift.io/v3/convert", content);
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
}
}
}
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
string htmlContent = "<h1>Hello, World!</h1><p>This is generated using PDFShift API.</p>";
var content = new StringContent(htmlContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("https://api.pdfshift.io/v3/convert", content);
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
}
}
}
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
Using client As New HttpClient()
Dim htmlContent As String = "<h1>Hello, World!</h1><p>This is generated using PDFShift API.</p>"
Dim content = New StringContent(htmlContent, Encoding.UTF8, "application/json")
Dim response As HttpResponseMessage = Await client.PostAsync("https://api.pdfshift.io/v3/convert", content)
Dim pdfBytes() As Byte = Await response.Content.ReadAsByteArrayAsync()
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes)
End Using
End Function
End Class
DocRaptor 是另一款功能强大的基于 API 的 PDF 生成服务,可将 HTML 和 CSS 转换成高质量的 PDF。 它以出色的 HTML 文档渲染能力而闻名,尤其是在处理复杂的 CSS 样式、媒体查询和网络字体方面。 这使得 DocRaptor 成为直接从 HTML 模板生成报告、发票和电子书等专业外观文档的最佳选择。
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
string apiKey = "YOUR_API_KEY";
string htmlContent = "<h1>Professional Report</h1><p>Generated using DocRaptor API.</p>";
string jsonData = $"{{\"test\": true, \"document_content\": \"{htmlContent}\", \"name\": \"Generated.pdf\", \"document_type\": \"pdf\"}}";
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync($"https://docraptor.com/docs?user_key={apiKey}", content);
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
}
}
}
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
string apiKey = "YOUR_API_KEY";
string htmlContent = "<h1>Professional Report</h1><p>Generated using DocRaptor API.</p>";
string jsonData = $"{{\"test\": true, \"document_content\": \"{htmlContent}\", \"name\": \"Generated.pdf\", \"document_type\": \"pdf\"}}";
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync($"https://docraptor.com/docs?user_key={apiKey}", content);
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
}
}
}
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
Using client As New HttpClient()
Dim apiKey As String = "YOUR_API_KEY"
Dim htmlContent As String = "<h1>Professional Report</h1><p>Generated using DocRaptor API.</p>"
Dim jsonData As String = $"{{""test"": true, ""document_content"": ""{htmlContent}"", ""name"": ""Generated.pdf"", ""document_type"": ""pdf""}}"
Dim content = New StringContent(jsonData, Encoding.UTF8, "application/json")
Dim response As HttpResponseMessage = Await client.PostAsync($"https://docraptor.com/docs?user_key={apiKey}", content)
Dim pdfBytes() As Byte = Await response.Content.ReadAsByteArrayAsync()
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes)
End Using
End Function
End Class
如果您不想编写代码或需要快速生成 PDF 的解决方案,有几款在线工具可以让您快速轻松地创建 PDF。 以下是几个值得注意的选项:
Smallpdf 是一个在线平台,提供各种 PDF 相关工具,包括从各种文件格式创建 PDF 的功能。 它专为那些希望使用简单的拖放界面而无需编写代码的用户而设计。 Smallpdf 广泛用于快速文件转换,如将 Word 文档、Excel 表或图像转换为 PDF。 它还提供了合并、压缩和拆分 PDF 的工具,使其成为执行基本 PDF 任务的多功能工具。
PDFescape 是一款易于使用的基于网络的 PDF 编辑器,用户无需安装任何软件即可创建、编辑和查看 PDF。 对于那些需要对 PDF 进行快速编辑(如填写表格、添加文本注释或插入图片)的人来说,这是一个很好的工具。 PDFescape 还提供了从零开始创建新 PDF 的工具,使其成为基本文档创建的灵活选择。
PDF Candy 是一套免费的在线 PDF 工具,涵盖从文件转换到编辑等各种 PDF 相关任务。 对于需要在无需注册账户或安装软件的情况下快速执行 PDF 操作的用户来说,这是一个极佳的选择。 PDF Candy 支持将 Word 文档、图像和文本文件等各种文件类型转换为 PDF。 它还提供了合并、拆分和压缩 PDF 的工具。
选择合适的工具用 C# 生成 PDF 文件取决于您的需求。 如果您需要从 HTML 内容生成 PDF 文档,IronPDF 和 PDFShift 是极佳的选择。 iTextSharp 和 Syncfusion 可为更复杂的项目提供广泛的自定义选项和文档结构控制。 对于更简单的开源解决方案,PDFsharp 是修改 PDF 文件或创建基本 PDF 的可靠选择。 最后,对于非开发人员,Smallpdf、PDFescape 和 PDF Candy 提供了处理 PDF 文件的简单、无代码选项。
对于有兴趣尝试IronPDF因此,对于开发人员来说,在购买付费许可证之前,测试 HTML 到 PDF 的转换和 PDF 操作功能是一个极好的选择。 试用版允许您探索其高级功能,如生成高质量 PDF 文件、安全选项和修改现有 PDF 文档,让您亲身体验该工具的功能。 如果您的项目需要频繁进行 HTML 到 PDF 的转换或复杂的 PDF 编辑,IronPDF 的免费试用版是了解它是否符合您需求的好方法。
通过评估每种工具的具体功能和您的项目范围,您可以选择最佳解决方案,用 C# 高效生成 PDF 文件。