首先导入itextsharp.dll(及其依赖)到Plugins文件夹。
其次,看下面代码。
一个写入表格的例子,供学习参考使用:
using System.Collections.Generic;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public static class WritePDFHelper
{
/// <summary>
/// 写入PDF
/// </summary>
/// <param name="filePath">写入路径(包含文件名称及后缀)</param>
/// <param name="titleFrontPath">标题字体路径</param>
/// <param name="textFrontPath">正文</param>
/// <param name="title">标题内容</param>
/// <param name="tableContent">表格内容,每一个List元素为一个表格,以每个string[][]二位数组的第一行为限,若超出则不会显示,若不足,应该会报索引超出异常</param>
/// Demo:
/// WritePDF(@"C:\\xxxx\xxx/生成pdf.pdf",
/// @"c:\windows\fonts\simhei.ttf",
/// @"c:\windows\fonts\simsun.ttc,1", "xxxxx", new List<string[][]>()
/// {
/// new[] {new[] {"1", "2", "3"}, new[] {"2", "3", "4"}, new[] {"1", "2", "3"}},
/// new[] {new[] {"1", "2", "3"}, new[] {"2", "3", "4"}, new[] {"3", "2", "2"}}
/// });
public static void WritePDF(string filePath, string titleFrontPath, string textFrontPath, string title, List<string[][]> tableContent)
{
Document document = new Document();
try
{
PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create));
document.Open();
//标题字体
BaseFont bf_Title = BaseFont.CreateFont(titleFrontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font font_Title = new iTextSharp.text.Font(bf_Title, 20);
BaseFont bf_Txt = BaseFont.CreateFont(textFrontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font font_Txt = new iTextSharp.text.Font(bf_Txt, 12);
//写标题
Paragraph paragraph_title = new Paragraph(title, font_Title);
//标题居中
paragraph_title.Alignment = Rectangle.ALIGN_CENTER;
document.Add(paragraph_title);
//输入一个空行,以分开标题与表格
Paragraph nullp = new Paragraph(" ", font_Title);
nullp.Leading = 10;
//写入内容
for (int i = 0; i < tableContent.Count; i++)
{
document.Add(nullp);
string[][] piece = tableContent[i];
PdfPTable piece_Table = new PdfPTable(piece[0].Length);
for (int j = 0; j < piece.Length; j++)
{
for (int k = 0; k < piece[j].Length; k++)
{
piece_Table.AddCell(new PdfPCell(new Phrase(piece[j][k], font_Txt)));
}
}
document.Add(piece_Table);
}
document.Close();
}
catch (DocumentException de)
{
throw de;
}
catch (IOException io)
{
throw io;
}
}
}