using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using iTextSharp; using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; /// <summary> /// TableToPDF 的摘要说明 /// </summary> /// /// 将DataTable转化为PDF文件的方法 /// public class TableToPDF { public TableToPDF() { } /// /// 转换数据表为PDF文档 /// /// 数据表数据 /// 目标PDF文件全路径 /// 字体所在路径 /// 字体大小 /// 返回调用是否成功 public static bool ConvertDataTableToPDF(DataTable datatable, string PDFFilePath, string FontPath, float FontSize) { //初始化一个目标文档类 Document document = new Document(); //调用PDF的写入方法流 //注意FileMode-Create表示如果目标文件不存在,则创建,如果已存在,则覆盖。 PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(PDFFilePath, FileMode.Create)); //打开目标文档对象 document.Open(); // 添加页眉 HeaderFooter header = new HeaderFooter(new Phrase("header"), false); document.Header = header; //创建PDF文档中的字体 BaseFont baseFont = BaseFont.CreateFont( FontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //根据字体路径和字体大小属性创建字体 Font font = new Font(baseFont, FontSize); //根据数据表内容创建一个PDF格式的表 PdfPTable table = new PdfPTable(datatable.Columns.Count); table.WidthPercentage = 500F; //打印列名 for (int j = 0; j < datatable.Columns.Count; j++) { table.AddCell(datatable.Columns[j].ColumnName.ToString()); }
//遍历原table的内容 for (int i = 0; i < datatable.Rows.Count; i++) { for (int j = 0; j < datatable.Columns.Count; j++) { table.AddCell(new Phrase(datatable.Rows[i][j].ToString(), font)); } } //在目标文档中添加转化后的表数据 document.Add(table); //关闭目标文件 document.Close(); //关闭写入流 writer.Close(); return true; } //然后,在要调用转换的按钮的事件代码中调用就可以了 // /将目标文件保存在此项目下 //字体使用simsun //字号选择14 //mytb是数据datatable的名 // TableToPDF.ConvertDataTableToPDF(mytb, Server.MapPath(".") + @"\Table.pdf", "c:\\winnt\\FONTS\\simsun.ttc,1", 14); //2 给出文本内容,生成PDF //比如用户输入文本内容及要输出PDF的保存路径的话,也可以输出PDF ///:要输出文本的内容
public static void CreateTxt(string txt, string filepath) { //创建文档对象 Document document = new Document(); //实例化生成的文档 PdfWriter.GetInstance(document, new FileStream(filepath, FileMode.Create)); //打开文档 document.Open(); //在文档中添加文本内容 document.Add(new Paragraph(txt)); //关闭文档对象 document.Close(); } // 3 加页眉页脚 public static void CreatePDFheader(string filepath, string headertxt, string footertxt) { //创建文档对象 Document document = new Document(); // 创建文档写入实例 PdfWriter.GetInstance(document, new FileStream(filepath, FileMode.Create)); // 添加页脚 HeaderFooter footer = new HeaderFooter(new Phrase(footertxt), true); footer.Border = Rectangle.NO_BORDER; document.Footer = footer; //打开文档内容对象 document.Open(); // 添加页眉 HeaderFooter header = new HeaderFooter(new Phrase(headertxt), false); document.Header = header; //设计各页的内容 document.Add(new Paragraph("This is First Page")); //新添加一个页 document.NewPage(); //第2页中添加文本 document.Add(new Paragraph("This is Second Page")); // 重置页面数量 document.ResetPageCount(); //关闭文档对象 document.Close(); }
} |
|