用 C# 或 VB 在 ASP.NET 中生成 PDF 报告

This article was translated from English: Does it need improvement?
Translated
View the article in English

从结构化数据(如 SQL)生成管理或数据库报告是一项常见的 .NET 开发任务。IronPDF 可用作 C# PDF 阅读器,帮助在 ASP.NET C# 中将 ssrs 报告可视化并导出为 PDF。

IronPDF 可用于将数据快照渲染为 PDF 文件格式的 "报告"。它还可用作 PDF C# 解析器。


步骤 1

1.安装 IronPDF

使用 NuGet: https://www.nuget.org/packages/IronPdf

Install-Package IronPdf

您还可以 下载 手动运行 IronPDF DLL。


教程

2.创建 PDF 报告的方法

基本方法是首先将报告生成 HTML 文档,然后使用 IronPDF 将 HTML 呈现为 PDF。本教程将向您展示如何在 ASP.NET C# 中创建 PDF 报告。

:path=/static-assets/pdf/content-code-examples/how-to/csharp-pdf-reports-render-html-file.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf")
VB   C#

3.用 .NET 将 Crystal Reports 转换为 PDF

在 Crystal Reports 应用程序中,您可以使用以下方法将报表导出为 HTML:

文件 -> 导出并选择 HTML 4.0

然后,就可以使用上述 "方法 "部分的 C# 示例代码将生成的报告导出为 PDF 格式。

下面是一个示例:

:path=/static-assets/pdf/content-code-examples/how-to/csharp-pdf-reports-render-header-footer.cs
using IronPdf;
using IronSoftware.Drawing;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Add a header to very page easily
renderer.RenderingOptions.FirstPageNumber = 1;
renderer.RenderingOptions.TextHeader.DrawDividerLine = true;
renderer.RenderingOptions.TextHeader.CenterText = "{url}";
renderer.RenderingOptions.TextHeader.Font = FontTypes.Arial;
renderer.RenderingOptions.TextHeader.FontSize = 12;

// Add a footer too
renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
renderer.RenderingOptions.TextFooter.Font = FontTypes.Arial;
renderer.RenderingOptions.TextFooter.FontSize = 10;
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}";

renderer.RenderHtmlFileAsPdf(@"c:\my\exported\report.html").SaveAs("report.pdf");
Imports IronPdf
Imports IronSoftware.Drawing

Private renderer As New ChromePdfRenderer()

' Add a header to very page easily
renderer.RenderingOptions.FirstPageNumber = 1
renderer.RenderingOptions.TextHeader.DrawDividerLine = True
renderer.RenderingOptions.TextHeader.CenterText = "{url}"
renderer.RenderingOptions.TextHeader.Font = FontTypes.Arial
renderer.RenderingOptions.TextHeader.FontSize = 12

' Add a footer too
renderer.RenderingOptions.TextFooter.DrawDividerLine = True
renderer.RenderingOptions.TextFooter.Font = FontTypes.Arial
renderer.RenderingOptions.TextFooter.FontSize = 10
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}"
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"

renderer.RenderHtmlFileAsPdf("c:\my\exported\report.html").SaveAs("report.pdf")
VB   C#

3.1 使用 C Sharp 以编程方式将 Crystal Reports 转换为 PDF

如果您希望通过编程从 Crystal Reports(RPT) 这也是可以实现的,而且能让您控制得更多。

CrystalDecisions.Shared.DiskFileDestinationOptions diskOpts = CrystalDecisions.Shared.ExportOptions.CreateDiskFileDestinationOptions();

CrystalDecisions.Shared.ExportOptions exportOpts = new CrystalDecisions.Shared.ExportOptions();

CrystalDecisions.Shared.CharacterSeparatedValuesFormatOptions csvExpOpts = new CrystalDecisions.Shared.CharacterSeparatedValuesFormatOptions();

CrystalDecisions.Shared.HTMLFormatOptions HTMLExpOpts = new CrystalDecisions.Shared.HTMLFormatOptions();

rpt.Load(@"c:\my\report.rpt");

//diskOpts.DiskFileName = "c:\\ReportName.csv";

diskOpts.DiskFileName = @"c:\tmp\html\b.html";

exportOpts.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile;
exportOpts.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.HTML40;
exportOpts.ExportDestinationOptions = diskOpts;

HTMLExpOpts = new HTMLFormatOptions();
HTMLExpOpts.HTMLBaseFolderName = @"c:\tmp\html\b.html";
HTMLExpOpts.HTMLEnableSeparatedPages = false;
HTMLExpOpts.UsePageRange = false;
HTMLExpOpts.HTMLHasPageNavigator = false;

System.IO.Stream htmlStream;

byte[] htmlByteArray = null;

htmlStream = rpt.ExportThtmlStream(CrystalDecisions.Shared.ExportFormatType.HTML40);

htmlByteArray = new byte[htmlStream.Length];

htmlStream.Read(htmlByteArray, 0, Convert.ToInt32(htmlStream.Length - 1));

System.IO.File.Create(diskOpts.DiskFileName, Convert.ToInt32(htmlStream.Length - 1)).Close();

System.IO.File.OpenWrite(diskOpts.DiskFileName).Write(htmlByteArray, 0, Convert.ToInt32(htmlStream.Length - 1));

System.IO.File.SetAttributes(diskOpts.DiskFileName, System.IO.FileAttributes.Directory);

htmlStream.Close();

IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();

// Add a header to very page easily
renderer.RenderingOptions.FirstPageNumber = 1;
renderer.RenderingOptions.TextHeader.DrawDividerLine = true;
renderer.RenderingOptions.TextHeader.CenterText = "{url}";
renderer.RenderingOptions.TextHeader.Font = IronSoftware.Drawing.FontTypes.Arial;
renderer.RenderingOptions.TextHeader.FontSize = 12;

// Add a footer too
renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial;
renderer.RenderingOptions.TextFooter.FontSize = 10;
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}";

Renderer.RenderFileAsPdf(diskOpts.DiskFileName).SaveAs("Report.pdf");

Cosole.WriteLine("Report Weitten To {0}", Path.GetFullPath(diskOpts.DiskFileName));
CrystalDecisions.Shared.DiskFileDestinationOptions diskOpts = CrystalDecisions.Shared.ExportOptions.CreateDiskFileDestinationOptions();

CrystalDecisions.Shared.ExportOptions exportOpts = new CrystalDecisions.Shared.ExportOptions();

CrystalDecisions.Shared.CharacterSeparatedValuesFormatOptions csvExpOpts = new CrystalDecisions.Shared.CharacterSeparatedValuesFormatOptions();

CrystalDecisions.Shared.HTMLFormatOptions HTMLExpOpts = new CrystalDecisions.Shared.HTMLFormatOptions();

rpt.Load(@"c:\my\report.rpt");

//diskOpts.DiskFileName = "c:\\ReportName.csv";

diskOpts.DiskFileName = @"c:\tmp\html\b.html";

exportOpts.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile;
exportOpts.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.HTML40;
exportOpts.ExportDestinationOptions = diskOpts;

HTMLExpOpts = new HTMLFormatOptions();
HTMLExpOpts.HTMLBaseFolderName = @"c:\tmp\html\b.html";
HTMLExpOpts.HTMLEnableSeparatedPages = false;
HTMLExpOpts.UsePageRange = false;
HTMLExpOpts.HTMLHasPageNavigator = false;

System.IO.Stream htmlStream;

byte[] htmlByteArray = null;

htmlStream = rpt.ExportThtmlStream(CrystalDecisions.Shared.ExportFormatType.HTML40);

htmlByteArray = new byte[htmlStream.Length];

htmlStream.Read(htmlByteArray, 0, Convert.ToInt32(htmlStream.Length - 1));

System.IO.File.Create(diskOpts.DiskFileName, Convert.ToInt32(htmlStream.Length - 1)).Close();

System.IO.File.OpenWrite(diskOpts.DiskFileName).Write(htmlByteArray, 0, Convert.ToInt32(htmlStream.Length - 1));

System.IO.File.SetAttributes(diskOpts.DiskFileName, System.IO.FileAttributes.Directory);

htmlStream.Close();

IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();

// Add a header to very page easily
renderer.RenderingOptions.FirstPageNumber = 1;
renderer.RenderingOptions.TextHeader.DrawDividerLine = true;
renderer.RenderingOptions.TextHeader.CenterText = "{url}";
renderer.RenderingOptions.TextHeader.Font = IronSoftware.Drawing.FontTypes.Arial;
renderer.RenderingOptions.TextHeader.FontSize = 12;

// Add a footer too
renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial;
renderer.RenderingOptions.TextFooter.FontSize = 10;
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}";

Renderer.RenderFileAsPdf(diskOpts.DiskFileName).SaveAs("Report.pdf");

Cosole.WriteLine("Report Weitten To {0}", Path.GetFullPath(diskOpts.DiskFileName));
Dim diskOpts As CrystalDecisions.Shared.DiskFileDestinationOptions = CrystalDecisions.Shared.ExportOptions.CreateDiskFileDestinationOptions()

Dim exportOpts As New CrystalDecisions.Shared.ExportOptions()

Dim csvExpOpts As New CrystalDecisions.Shared.CharacterSeparatedValuesFormatOptions()

Dim HTMLExpOpts As New CrystalDecisions.Shared.HTMLFormatOptions()

rpt.Load("c:\my\report.rpt")

'diskOpts.DiskFileName = "c:\\ReportName.csv";

diskOpts.DiskFileName = "c:\tmp\html\b.html"

exportOpts.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile
exportOpts.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.HTML40
exportOpts.ExportDestinationOptions = diskOpts

HTMLExpOpts = New HTMLFormatOptions()
HTMLExpOpts.HTMLBaseFolderName = "c:\tmp\html\b.html"
HTMLExpOpts.HTMLEnableSeparatedPages = False
HTMLExpOpts.UsePageRange = False
HTMLExpOpts.HTMLHasPageNavigator = False

Dim htmlStream As System.IO.Stream

Dim htmlByteArray() As Byte = Nothing

htmlStream = rpt.ExportThtmlStream(CrystalDecisions.Shared.ExportFormatType.HTML40)

htmlByteArray = New Byte(htmlStream.Length - 1){}

htmlStream.Read(htmlByteArray, 0, Convert.ToInt32(htmlStream.Length - 1))

System.IO.File.Create(diskOpts.DiskFileName, Convert.ToInt32(htmlStream.Length - 1)).Close()

System.IO.File.OpenWrite(diskOpts.DiskFileName).Write(htmlByteArray, 0, Convert.ToInt32(htmlStream.Length - 1))

System.IO.File.SetAttributes(diskOpts.DiskFileName, System.IO.FileAttributes.Directory)

htmlStream.Close()

Dim Renderer As New IronPdf.ChromePdfRenderer()

' Add a header to very page easily
renderer.RenderingOptions.FirstPageNumber = 1
renderer.RenderingOptions.TextHeader.DrawDividerLine = True
renderer.RenderingOptions.TextHeader.CenterText = "{url}"
renderer.RenderingOptions.TextHeader.Font = IronSoftware.Drawing.FontTypes.Arial
renderer.RenderingOptions.TextHeader.FontSize = 12

' Add a footer too
renderer.RenderingOptions.TextFooter.DrawDividerLine = True
renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial
renderer.RenderingOptions.TextFooter.FontSize = 10
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}"
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"

Renderer.RenderFileAsPdf(diskOpts.DiskFileName).SaveAs("Report.pdf")

Cosole.WriteLine("Report Weitten To {0}", Path.GetFullPath(diskOpts.DiskFileName))
VB   C#

4.XML 报告

尽管 JSON 等更容易编码的格式已经非常普及,但以 XML 格式导出报告数据仍然很常见。

要为 XML 报告设计样式,可以先解析 XML,然后用数据生成 HTML。

一个更优雅的解决方案是使用 XSLT,使用 XslCompiledTransform 类直接将 XML 转换为 HTML,如以下文章''中记录的那样。使用 XslCompiledTransform 类.'

然后就可以使用 IronPDF 将生成的 HTML 字符串或文件渲染为 PDF:

XslCompiledTransform transform = new XslCompiledTransform();

using (XmlReader reader = XmlReader.Create(new StringReader(xslt)))
{
    transform.Load(reader);
}
StringWriter results = new StringWriter();
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
    transform.Transform(reader, null, results);
}

IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();

// options, headers and footers may be set there
// Render our report as a PDF
renderer.RenderHtmlFileAsPdf(results.ToString()).SaveAs("Report.pdf");
XslCompiledTransform transform = new XslCompiledTransform();

using (XmlReader reader = XmlReader.Create(new StringReader(xslt)))
{
    transform.Load(reader);
}
StringWriter results = new StringWriter();
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
    transform.Transform(reader, null, results);
}

IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();

// options, headers and footers may be set there
// Render our report as a PDF
renderer.RenderHtmlFileAsPdf(results.ToString()).SaveAs("Report.pdf");
Dim transform As New XslCompiledTransform()

Using reader As XmlReader = XmlReader.Create(New StringReader(xslt))
	transform.Load(reader)
End Using
Dim results As New StringWriter()
Using reader As XmlReader = XmlReader.Create(New StringReader(xml))
	transform.Transform(reader, Nothing, results)
End Using

Dim renderer As New IronPdf.ChromePdfRenderer()

' options, headers and footers may be set there
' Render our report as a PDF
renderer.RenderHtmlFileAsPdf(results.ToString()).SaveAs("Report.pdf")
VB   C#

请访问用 C# 和 VB.NET 将 XML 转换为 PDF'一文了解更多信息。

5.微软 SQL 服务器报告

微软的 SQL Server 和免费的 SQL Server Express 包含报表工具。在 ASP.NET 中将 SSRS 报表导出为 PDF 文件是 IronPDF 的一项实用功能。

教程:如何定位和启动报告服务工具 (SSRS)

这些报告可以生成 HTML 格式,然后使用 IronPDF 进行定制并转换为 PDF 格式。

渲染为 HTML(报告生成器)

6.安全报告

为确保 PDF 报告未被修改或篡改,可对其进行数字签名。这在 PDF 报告文件渲染并保存到磁盘后最容易实现。

:path=/static-assets/pdf/content-code-examples/how-to/csharp-pdf-reports-sign-pdf.cs
using IronPdf.Signing;

// Sign our PDF Report using a p12 or pix digital certificate file
new PdfSignature("IronSoftware.pfx", "123456").SignPdfFile("signed.pdf");
Imports IronPdf.Signing

' Sign our PDF Report using a p12 or pix digital certificate file
Call (New PdfSignature("IronSoftware.pfx", "123456")).SignPdfFile("signed.pdf")
VB   C#

如果没有数字签名,可以在 macOS 和 Windows 上使用免费的 Adobe Acrobat Reader 创建新的数字签名文件。

7.用 ASP.NET Webforms 将 ASPX 转换为 PDF

在 ASP.NET 中提供 HTML 内容的最简单方法是在 ASP.NET WebForms 的 Form_Load 事件中使用 IronPdf.AspxToPdf 类。

var AspxToPdfOptions = new IronPdf.ChromePdfRenderOptions()
{
  EnableJavaScript = false,
  //.. many more options available
};

IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.Attachment, "Report.pdf", AspxToPdfOptions);
var AspxToPdfOptions = new IronPdf.ChromePdfRenderOptions()
{
  EnableJavaScript = false,
  //.. many more options available
};

IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.Attachment, "Report.pdf", AspxToPdfOptions);
Dim AspxToPdfOptions = New IronPdf.ChromePdfRenderOptions() With {.EnableJavaScript = False}

IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.Attachment, "Report.pdf", AspxToPdfOptions)
VB   C#

希望本文对您学习如何在 ASP.NET C# 或 VB.NET 中生成 PDF 报告有所帮助。您还可以查看我们的 ASP.NET ASPX 转 PDF 教程 了解更多信息。