介绍
本文是关于使用 C#、.NET 和 iText 库生成 PDF 文档的。我需要为我从事的一个项目生成 PDF 格式的发票。在我的研究中,我开始了解 iText。iText 是一个用于在 .NET 和 Java 中创建和操作 PDF 文件的库。如果您在 C# 方面遇到困难,请考虑查看TechRepublic Academy。
先决条件
- Visual Studio 2017 及更高版本
- .NET Framework,版本 4.0 及更高版本
- 使用 NuGet 包管理器安装 iText 7 库
设置项目
步骤 1:使用 Visual Studio 创建控制台应用程序
在 Visual Studio 中,转到File -> New -> Project。
在“新建项目窗口”中,选择Console App(.NET Framework)并为项目命名,如图 1 所示。
图 1:选择控制台应用程序(.NET Framework)
第 2 步:使用“管理 NuGet 包...”安装 iText 7
右键单击项目名称并选择“管理 NuGet 包...”。您可以在图 2 中看到这一点。
图 2:选择 NuGet 包
选择“浏览”,然后在搜索框中键入 itext7,然后从搜索结果中选择 itext7 并安装(参见图 3)。
图 3:选择 itext7
以下是生成 PDF 文档的有用类和方法:
- PdfWriter:传递文件名并将内容写入文档。
- PdfDocument:PDF 文档的内存表示。它将以书写模式打开 PDF 文档。
- Document:从内存中的 PdfDocument 创建一个文档。
- 段落:创建一个段落,用一些文本初始化。
- SetFontSize:设置文本的字体大小。
- SetTextAlignment:设置文本对齐方式,如左、右、居中等。
我将在 PDF 文档中添加页眉、子页眉、行分隔符、图像、表格、超链接,最后是页码。
A. 添加标题
向 PDF 文档添加页眉。标题内容与文档居中对齐,我将字体大小设置为 20。我们可以通过创建段落对象来实现这一点。以下是创建段落对象并将其添加到文档对象的代码片段。最后,我们需要通过调用 Close() 方法来关闭文档对象。
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
namespace GeneratePdfDemo
{
class Program
{
static void Main(string[] args)
{
// Must have write permissions to the path folder
PdfWriter writer = new PdfWriter("C:\\demo.pdf");
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
Paragraph header = new Paragraph("HEADER")
.SetTextAlignment(TextAlignment.CENTER)
.SetFontSize(20);
document.Add(header);
document.Close();
}
}
}
运行程序并转到 PdfWriter 中指定的路径并打开 PDF 文档。图 4 是带有标题文本的 PDF 文档的图像。
图 4:显示标题文本
B. 创建子标题
创建一个文本居中对齐的 Sub Header,并将字体大小设置为 15。将此 Sub Header 添加到文档对象,如图 5 所示。
Paragraph subheader = new Paragraph("SUB HEADER")
.SetTextAlignment(TextAlignment.CENTER)
.SetFontSize(15);
document.Add(subheader);
图 5:创建子标题
C. 添加水平分隔线
使用 Line Separator 添加一条水平线。如图 6 所示。
// Line separator
LineSeparator ls = new LineSeparator(new SolidLine());
document.Add(ls);
图 6:创建分隔线
D. 添加图像
使用 Image 实例将 Image 添加到 PDF 文档(参见图 7)。
// Add image
Image img = new Image(ImageDataFactory
.Create(@"..\..\image.jpg"))
.SetTextAlignment(TextAlignment.CENTER);
document.Add(img);
图 7:添加图像
E. 创建表
创建一个表并将其添加到文档中,如图 8 所示。
// Table
Table table = new Table(2, false);
Cell cell11 = new Cell(1, 1)
.SetBackgroundColor(ColorConstants.GRAY)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("State"));
Cell cell12 = new Cell(1, 1)
.SetBackgroundColor(ColorConstants.GRAY)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("Capital"));
Cell cell21 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("New York"));
Cell cell22 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("Albany"));
Cell cell31 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("New Jersey"));
Cell cell32 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("Trenton"));
Cell cell41 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("California"));
Cell cell42 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("Sacramento"));
table.AddCell(cell11);
table.AddCell(cell12);
table.AddCell(cell21);
table.AddCell(cell22);
table.AddCell(cell31);
table.AddCell(cell32);
table.AddCell(cell41);
table.AddCell(cell42);
document.Add(table);
图 8:添加表格
F. 创建超链接
创建一个超链接并将其添加到文档中(参见图 9)。
// Hyper link
Link link = new Link("click here",
PdfAction.CreateURI("https://www.google.com"));
Paragraph hyperLink = new Paragraph("Please ")
.Add(link.SetBold().SetUnderline()
.SetItalic().SetFontColor(ColorConstants.BLUE))
.Add(" to go www.google.com.");
document.Add(newline);
document.Add(hyperLink);
图 9:添加超链接
G. 添加页码
在页面右上角添加页码,如图10所示。
// Page numbers
int n = pdf.GetNumberOfPages();
for (int i = 1; i <= n; i++)
{
document.ShowTextAligned(new Paragraph(String
.Format("page" + i + " of " + n)),
559, 806, i, TextAlignment.RIGHT,
VerticalAlignment.TOP, 0);
}
图 10:添加页码
以下是完整的代码清单。
using iText.IO.Image;
using iText.Kernel.Colors;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Action;
using iText.Kernel.Pdf.Canvas.Draw;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using System;
namespace GeneratePdfDemo
{
class Program
{
static void Main(string[] args)
{
// Must have write permissions to the path folder
PdfWriter writer = new PdfWriter("C:\\test\\demo.pdf");
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
// Header
Paragraph header = new Paragraph("HEADER")
.SetTextAlignment(TextAlignment.CENTER)
.SetFontSize(20);
// New line
Paragraph newline = new Paragraph(new Text("\n"));
document.Add(newline);
document.Add(header);
// Add sub-header
Paragraph subheader = new Paragraph("SUB HEADER")
.SetTextAlignment(TextAlignment.CENTER)
.SetFontSize(15);
document.Add(subheader);
// Line separator
LineSeparator ls = new LineSeparator(new SolidLine());
document.Add(ls);
// Add paragraph1
Paragraph paragraph1 = new Paragraph("Lorem ipsum " +
"dolor sit amet, consectetur adipiscing elit, " +
"sed do eiusmod tempor incididunt ut labore " +
"et dolore magna aliqua.");
document.Add(paragraph1);
// Add image
Image img = new Image(ImageDataFactory
.Create(@"..\..\image.jpg"))
.SetTextAlignment(TextAlignment.CENTER);
document.Add(img);
// Table
Table table = new Table(2, false);
Cell cell11 = new Cell(1, 1)
.SetBackgroundColor(ColorConstants.GRAY)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("State"));
Cell cell12 = new Cell(1, 1)
.SetBackgroundColor(ColorConstants.GRAY)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("Capital"));
Cell cell21 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("New York"));
Cell cell22 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("Albany"));
Cell cell31 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("New Jersey"));
Cell cell32 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("Trenton"));
Cell cell41 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("California"));
Cell cell42 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("Sacramento"));
table.AddCell(cell11);
table.AddCell(cell12);
table.AddCell(cell21);
table.AddCell(cell22);
table.AddCell(cell31);
table.AddCell(cell32);
table.AddCell(cell41);
table.AddCell(cell42);
document.Add(newline);
document.Add(table);
// Hyper link
Link link = new Link("click here",
PdfAction.CreateURI("https://www.google.com"));
Paragraph hyperLink = new Paragraph("Please ")
.Add(link.SetBold().SetUnderline()
.SetItalic().SetFontColor(ColorConstants.BLUE))
.Add(" to go www.google.com.");
document.Add(newline);
document.Add(hyperLink);
// Page numbers
int n = pdf.GetNumberOfPages();
for (int i = 1; i <= n; i++)
{
document.ShowTextAligned(new Paragraph(String
.Format("page" + i + " of " + n)),
559, 806, i, TextAlignment.RIGHT,
VerticalAlignment.TOP, 0);
}
// Close document
document.Close();
}
}
}
添加中文支持
using iText.IO.Image;
using iText.Kernel.Colors;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Action;
using iText.Kernel.Pdf.Canvas.Draw;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using System;
namespace GeneratePdfDemo
{
class Program
{
static void Main(string[] args)
{
// Must have write permissions to the path folder
PdfWriter writer = new PdfWriter("C:\\test\\demo.pdf");
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
PdfFont sysFont = PdfFontFactory.CreateFont("C:/Windows/Fonts/simsun.ttc,1", iText.IO.Font.PdfEncodings.IDENTITY_H);
document.Add(new Paragraph("好 的!").SetFont(sysFont));
// Header
Paragraph header = new Paragraph("HEADER")
.SetTextAlignment(TextAlignment.CENTER)
.SetFontSize(20);
// New line
Paragraph newline = new Paragraph(new Text("\n"));
document.Add(newline);
document.Add(header);
// Add sub-header
Paragraph subheader = new Paragraph("SUB HEADER")
.SetTextAlignment(TextAlignment.CENTER)
.SetFontSize(15);
document.Add(subheader);
// Line separator
LineSeparator ls = new LineSeparator(new SolidLine());
document.Add(ls);
// Add paragraph1
Paragraph paragraph1 = new Paragraph("Lorem ipsum " +
"dolor sit amet, consectetur adipiscing elit, " +
"sed do eiusmod tempor incididunt ut labore " +
"et dolore magna aliqua.");
document.Add(paragraph1);
// Add image
Image img = new Image(ImageDataFactory
.Create(@"c:\\DesktopOK.png"))
.SetTextAlignment(TextAlignment.CENTER);
document.Add(img);
// Table
Table table = new Table(2, false);
Cell cell11 = new Cell(1, 1)
.SetBackgroundColor(ColorConstants.GRAY)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("State"));
Cell cell12 = new Cell(1, 1)
.SetBackgroundColor(ColorConstants.GRAY)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("Capital"));
Cell cell21 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("New York"));
Cell cell22 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("Albany"));
Cell cell31 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("New Jersey"));
Cell cell32 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("Trenton"));
Cell cell41 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("California"));
Cell cell42 = new Cell(1, 1)
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Paragraph("Sacramento"));
table.AddCell(cell11);
table.AddCell(cell12);
table.AddCell(cell21);
table.AddCell(cell22);
table.AddCell(cell31);
table.AddCell(cell32);
table.AddCell(cell41);
table.AddCell(cell42);
document.Add(newline);
document.Add(table);
// Hyper link
Link link = new Link("click here",
PdfAction.CreateURI("https://www.google.com"));
Paragraph hyperLink = new Paragraph("Please ")
.Add(link.SetBold().SetUnderline()
.SetItalic().SetFontColor(ColorConstants.BLUE))
.Add(" to go www.google.com.");
document.Add(newline);
document.Add(hyperLink);
// Page numbers
int n = pdf.GetNumberOfPages();
for (int i = 1; i <= n; i++)
{
document.ShowTextAligned(new Paragraph(String
.Format("page" + i + " of " + n)),
559, 806, i, TextAlignment.RIGHT,
VerticalAlignment.TOP, 0);
}
// Close document
document.Close();
}
}
}
结论
您已经了解了如何使用 C#、.NET 和 iText 库生成 PDF 文档。iText 允许对 PDF 文档进行大量自定义。我希望这篇文章对想要生成 PDF 文档的人有所帮助。