1using System; 2using System.Collections.Generic; 3using System.Text; 4using System.Data; 5using iTextSharp; 6using iTextSharp.text; 7using iTextSharp.text.pdf; 8using System.IO; 9 10namespace CNINSURE.WEB.COMMON 11{ 12 /**//// 13 /// 将DataTable转化为PDF文件的方法 14 /// 15 public class TableToPDF 16 { 17 public TableToPDF() 18 { 19 } 20 /**//// 21 /// 转换数据表为PDF文档 22 /// 23 /// 数据表数据 24 /// 目标PDF文件全路径 25 /// 字体所在路径 26 /// 字体大小 27 /// 返回调用是否成功 28 public static bool ConvertDataTableToPDF(DataTable datatable, string PDFFilePath, string FontPath, float FontSize) 29 { 30 //初始化一个目标文档类 31 Document document = new Document(); 32 //调用PDF的写入方法流 33 //注重FileMode-Create表示假如目标文件不存在,则创建,假如已存在,则覆盖。 34 PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(PDFFilePath, FileMode.Create)); 35 //打开目标文档对象 36 document.Open(); 37 //创建PDF文档中的字体 38 BaseFont baseFont = BaseFont.CreateFont( 39 FontPath, 40 BaseFont.IDENTITY_H, 41 BaseFont.NOT_EMBEDDED); 42 //根据字体路径和字体大小属性创建字体 43 Font font = new Font(baseFont, FontSize); 44 //根据数据表内容创建一个PDF格式的表 45 PdfPTable table = new PdfPTable(datatable.Columns.Count); 46 //遍历原table的内容 47 for (int i = 0; i < datatable.Rows.Count; i++) 48 { 49 for (int j = 0; j < datatable.Columns.Count; j++) 50 { 51 table.AddCell(new Phrase(datatable.Rows[i][j].ToString(), font)); 52 } 53 } 54 //在目标文档中添加转化后的表数据 55 document.Add(table); 56 //关闭目标文件 57 document.Close(); 58 //关闭写入流 59 writer.Close(); 60 return true; 61 } 62 /**//// 63 /// 给出文本内容,生成PDF 比如用户输入文本内容及要输出PDF的保存路径的话,也可以输出PDF 64 /// 65 /// 文本内容 66 /// 要输出文本的内容 67 private void CreateTxt(string txt, string filepath) 68 { 69 //创建文档对象 70 Document document = new Document(); 71 //实例化生成的文档 72 PdfWriter.GetInstance(document, new FileStream(filepath, FileMode.Create)); 73 //打开文档 74 document.Open(); 75 //在文档中添加文本内容 76 document.Add(new Paragraph(txt)); 77 //关闭文档对象 78 document.Close(); 79 } 80 81 /**//// 82 /// 加页眉页脚 83 /// 84 /// 文件路径 85 /// 头文本 86 /// 脚文本 87 public void CreatePDFheader(string filepath, string headertxt, string footertxt) 88 { 89 //创建文档对象 90 Document document = new Document(); 91 // 创建文档写入实例
92 PdfWriter.GetInstance(document, new FileStream(filepath, FileMode.Create)); 93 94 // 添加页脚 95 HeaderFooter footer = new HeaderFooter(new Phrase(footertxt), true); 96 footer.Border = Rectangle.NO_BORDER; 97 document.Footer = footer; 98 99 //打开文档内容对象 100 document.Open(); 101 102 // 添加页眉 103 HeaderFooter header = new HeaderFooter(new Phrase(headertxt), false); 104 document.Header = header; 105 //设计各页的内容 106 document.Add(new Paragraph("This is First Page")); 107 //新添加一个页 108 document.NewPage(); 109 //第2页中添加文本 110 document.Add(new Paragraph("This is Second Page")); 111 // 重置页面数量 112 document.ResetPageCount(); 113 //关闭文档对象 114 document.Close(); 115 } 116 117 118 119 } 120 121 122 123} 124
|