C# 使用 iTextSharp(4.1.2) 生成 PDF 文档

在 Java 里操作 PDF 文档的组件首当其充就是 iText,几乎是不二之选,惯性思维到 C# 里应该有一个相应的实现吧,对了,那就是 iTextSharp,这里来看看 iTextSharp 怎么生成一个 PDF 文档的。此篇所选版本是 iTextSharp 4.1.2,因与 iTextSharp 5 有较大的差别,所以分两篇来说明。

这两个版本的主要区别有,iTextSharp 5 里不再有 iTextSharp.text.Table、HeaderFooter 类的,且实现了自己的 Font, Color,不再依赖于 System.Drawing 了;在设置页眉页脚实现也不一样。

下面例子,用 OLDDB 从一个 Excel 里读取第一个 sheet,然后在 PDF 文档里生成张表格:
  1using System;
  2using System.Data;
  3using System.IO;
  4using iTextSharp.text.pdf;
  5using iTextSharp.text;
  6using System.Data.OleDb;
  7
  8namespace Unmi
  9{
 10    class PdfTest
 11    {
 12        public static void Main(string[] args)
 13        {
 14
 15            //查询 Excel 的 sheet1 获得 DataTable 对象
 16            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\test.xls;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
 17            DataTable dt = new DataTable();
 18            using (OleDbConnection conn = new OleDbConnection(strConn))
 19            {
 20                conn.Open();
 21                //OleDbCommand cmd = new OleDbCommand();
 22                OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [sheet1$]", conn);
 23                da.Fill(dt);
 24            }
 25
 26            //为将要被创建的Pdf文档指定大小和颜色
 27            Rectangle rec = new Rectangle(PageSize.A4.Rotate());//A4纸横向
 28
 29            //rec.BackgroundColor = new Color(System.Drawing.Color.Plum); //设置背景色
 30
 31            //创建Pdf文档
 32            Document doc = new Document(rec);
 33
 34            //定义字体
 35            Font fixedsysFont = FontFactory.GetFont("Fixedsys", 9);
 36
 37            //为Document创建多个PdfWriter对象
 38            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("c:\\test.pdf", FileMode.Create));
 39
 40            //例如创建 HtmlWriter 还能生成一个相应的 html 文件
 41            //iTextSharp.text.html.HtmlWriter.GetInstance(doc, new FileStream("c:\\test.html", FileMode.Create));
 42
 43            //设置文档的边距,依次是 left, right, top, bottom
 44            doc.SetMargins(17.2f, 18.8f, 15.8f, 15f);
 45
 46            //定义页眉
 47            HeaderFooter header = new HeaderFooter(new Phrase(6f,"http://unmi.blogjava.net   ", fixedsysFont),new Phrase(6f,"  "));
 48            header.Border = Rectangle.NO_BORDER;
 49            header.Alignment = Element.ALIGN_RIGHT;
 50            doc.Header = header;
 51
 52            //可以在Open()方法调用前为doc添加摘要信息
 53            doc.AddCreationDate();
 54            doc.AddCreator("Unmi");
 55            doc.AddAuthor("Unmi");
 56            doc.AddTitle("iTextSharp 4 生成 PDF 文档示例");
 57
 58            doc.Open(); //打开文档
 59
 60            //向 PDF 文档添加一个 Table,其他的内容对象有 phrase、Paragraph、Graphic
 61            Table pdfTable = new Table(dt.Columns.Count);
 62
 63            /*
 64             * 要理解 Table 中的单元格怎么显示,先设定列数,然后逐个放 Cell,当前行的 Cell
 65             * 数量到达列数时另起新行,可用单元格的 Rowspan,Colspan 设定跨行或跨列的数量
 66            **/
 67
 68            pdfTable.Padding = 2;
 69            pdfTable.Spacing = 2;
 70            pdfTable.TableFitsPage = true;
 71            pdfTable.Width = 98f;
 72
 73            //每一列的宽度比率,这里要求你的 Excel 第一张表有 6 列
 74            pdfTable.Widths = new float[]{ 0.8f, 1f, 0.6f,0.6f,0.9f, 7f };
 75
 76            //让单元格内容能跨页显示
 77            pdfTable.CellsFitPage = false;
 78
 79            //输出表头
 80            foreach(DataColumn dc in dt.Columns)
 81            {
 82                Font headerFont = FontFactory.GetFont("Fixedsys", 10, Font.BOLD, Color.WHITE);
 83                Cell cellHeader = new Cell(new Paragraph(dc.ColumnName, headerFont));
 84                cellHeader.HorizontalAlignment = Element.ALIGN_CENTER;
 85                cellHeader.Header = true;
 86                cellHeader.BackgroundColor = Color.RED;
 87                pdfTable.AddCell(cellHeader);
 88            }
 89
 90            //pdfTable.EndHeaders();// 表头是否显示在每一页
 91
 92            //显示数据
 93            foreach (DataRow dr in dt.Rows)
 94            {
 95                foreach (DataColumn dc in dt.Columns)
 96                {
 97                    Cell cellData = new Cell(new Paragraph(dr[dc].ToString(), fixedsysFont));
 98                    pdfTable.AddCell(cellData);
 99                }
100            }
101
102            doc.Add(pdfTable);
103            doc.Close();
104        }
105    }
106}
参考:1. iText 简介
        2. 使用iTextSharp创建pdf文件
        3. iText 5.0.2 发布,PDF操作Java类库
        4. 第18章. iText PDF 生成
  • Create PDFs in ASP.NET - getting started with iTextSharp
  • Working with Fonts
  • Adding Text with Chunks, Phrases and Paragraphs
  • Lists with iTextSharp
  • Links and Bookmarks
  • Introducing Tables
  • Working with images
  • Drawing shapes and Graphics
  • Page Layout with Columns
  • 永久链接 https://yanbin.blog/csharp-itextsharp4-1-2-pdf/, 来自 隔叶黄莺 Yanbin's Blog
    [版权声明] 本文采用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 进行许可。