namespace Utilities { public static class PDFHelper { /// <summary> /// Html转Pdf /// </summary> /// <param name="strHtmlData">HTML内容</param> /// <param name="filePath">文件路径</param> /// <param name="fileName">文件名</param> public static bool HtmlToPdfByInfo(string strHtmlData, string filePath, string fileName) { FileStream fs = null; try { if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } //获得字节数组 byte[] bPDF = ConvertHtmlTextToPDF(strHtmlData); if (bPDF == null) { return false; } fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create); //开始写入 fs.Write(bPDF, 0, bPDF.Length); return true; } catch (Exception) { throw; } finally { //清空缓冲区、关闭流 if (fs != null) { fs.Flush(); fs.Close(); } } } public static bool DownLoadFile(string url, string filePath, string fileName) { try { WebClient wc = new WebClient(); wc.Encoding = System.Text.Encoding.UTF8; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } wc.DownloadFile(url, Path.Combine(filePath, fileName)); return true; } catch (Exception ex) { string strLog = string.Format("下载文件名:{0};文件下载地址:{1};错误信息:{2}。", fileName, url, ex.StackTrace); LogHelper.Info(strLog); throw ex; } } #region HTML模板方式转PDF(格式问题) /// <summary> /// Html转Pdf /// </summary> /// <param name="url">页面地址,要完整地址</param> /// <param name="filePath">文件路径</param> /// <param name="fileName">文件名</param> public static bool HtmlToPdf(string url, string filePath, string fileName) { FileStream fs = null; try { WebClient wc = new WebClient(); wc.Encoding = System.Text.Encoding.UTF8; //从网址下载Html字串 string htmlText = wc.DownloadString(url); //StreamWriter TxtWriter = new StreamWriter(@"D:logfile.txt", true); //TxtWriter.Write("0" + Environment.NewLine); //TxtWriter.Write(htmlText + Environment.NewLine); //TxtWriter.Close(); //获得字节数组 byte[] bPDF = ConvertHtmlTextToPDF(htmlText); if (bPDF == null) { return false; } if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create); //开始写入 fs.Write(bPDF, 0, bPDF.Length); return true; } catch (Exception ex) { string strLog = string.Format("HTML模板方式转PDF 文件名:{0};文件下载地址:{1};错误信息:{2}。", fileName, url, ex.StackTrace); LogHelper.Info(strLog); throw ex; } finally { //清空缓冲区、关闭流 if (fs != null) { fs.Flush(); fs.Close(); } } } #endregion private static byte[] ConvertHtmlTextToPDF(string htmlText) { if (string.IsNullOrEmpty(htmlText)) { return null; } //避免当htmlText无任何html tag标签的纯文字时,转PDF时会挂掉,所以一律加上<p>标签 //htmlText = "<p>" + htmlText + "</p>"; MemoryStream outputStream = new MemoryStream();//要把PDF写到哪个串流 byte[] data = Encoding.UTF8.GetBytes(htmlText);//字串转成byte[] MemoryStream msInput = new MemoryStream(data); Document doc = new Document();//要写PDF的文件,建构子没填的话预设直式A4 PdfWriter writer = PdfWriter.GetInstance(doc, outputStream); //PageEventHelper pageEventHelper = new PageEventHelper(); //writer.PageEvent = pageEventHelper; //指定文件预设开档时的缩放为100% PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); //开启Document文件 doc.Open(); //使用XMLWorkerHelper把Html parse到PDF档里 //XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8); XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory()); //XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory()); //将pdfDest设定的资料写到PDF档 PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); ////手工加内容 //doc.NewPage(); ////要先定义中文字体 //BaseFont BF_Light = BaseFont.CreateFont(@"C:WindowsFontssimsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); ////要设置字体和大小 //var p = new Paragraph("合同信息", new Font(BF_Light, 13)); //PdfPTable table = new PdfPTable(1); //PdfPCell cell = new PdfPCell(p); ////设置cell属性 //cell.HorizontalAlignment = Element.ALIGN_CENTER; ////添加单元格 //table.AddCell(cell); //doc.Add(table); doc.Close(); msInput.Close(); outputStream.Close(); //回传PDF档案 return outputStream.ToArray(); } #region 创建PDF文档 /// <summary> /// 生成PDF /// </summary> /// <param name="strHtmlData">HTML内容</param> /// <param name="filePath">文件路径</param> /// <param name="fileName">文件名</param> public static bool CreatePdf(string filePath, string fileName, PdfPTable dt) { FileStream fs = null; try { if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } //获得字节数组 byte[] bPDF = CreatePdf(dt); if (bPDF == null) { return false; } fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create); //开始写入 fs.Write(bPDF, 0, bPDF.Length); return true; } catch (Exception) { throw; } finally { //清空缓冲区、关闭流 if (fs != null) { fs.Flush(); fs.Close(); } } } /// <summary> /// 创建PDF /// </summary> /// <param name="htmlText"></param> /// <returns></returns> private static byte[] CreatePdf(PdfPTable pdfTable) { MemoryStream outputStream = new MemoryStream();//要把PDF写到哪个串流 Document doc = new Document();//要写PDF的文件,建构子没填的话预设直式A4 PdfWriter writer = PdfWriter.GetInstance(doc, outputStream); //指定文件预设开档时的缩放为100% PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); //开启Document文件 doc.Open(); //将pdfDest设定的资料写到PDF档 PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); //手工加内容 doc.NewPage(); doc.Add(pdfTable); var row = pdfTable.Rows[pdfTable.Rows.Count]; //iTextSharp.text.Image splitline = iTextSharp.text.Image.GetInstance(@"E:WorkCodesYeWuYCloud.MFBP.WebImagesyaoshi.png"); //splitline.ScalePercent(12f); //图片比例 //splitline.SetAbsolutePosition(doc.PageSize.Width- doc.PageSize.Width/3*2, doc.PageSize.Height - doc.PageSize.Height/5*4); doc.Close(); outputStream.Close(); //回传PDF档案 return outputStream.ToArray(); } #endregion } public class UnicodeFontFactory : FontFactoryImp { static string fontPath = Environment.GetFolderPath(Environment.SpecialFolder.Fonts); //arial unicode MS是完整的unicode字型。 //private static readonly string arialFontPath = Path.Combine(fontPath, "arialuni.ttf"); //宋体。 private static readonly string stFontPath = Path.Combine(fontPath, "simsun.ttc,0"); public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached) { BaseFont baseFont = BaseFont.CreateFont(stFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); return new Font(baseFont, size, style, color); } } public class PageEventHelper : PdfPageEventHelper { PdfContentByte cb; PdfTemplate template; public override void OnOpenDocument(PdfWriter writer, Document document) { cb = writer.DirectContent; template = cb.CreateTemplate(100, 50); } public override void OnStartPage(PdfWriter writer, Document document) { base.OnStartPage(writer, document); } public override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); String text = "第" + writer.PageNumber.ToString() + "页"; UnicodeFontFactory info = new UnicodeFontFactory(); float len = 10; iTextSharp.text.Rectangle pageSize = document.PageSize; cb.SetRGBColorFill(100, 100, 100); string fontPath = Environment.GetFolderPath(Environment.SpecialFolder.Fonts); string stFontPath = Path.Combine(fontPath, "simsun.ttc,0"); BaseFont baseFont = BaseFont.CreateFont(stFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); cb.BeginText(); cb.SetFontAndSize(baseFont, 10); cb.SetTextMatrix(document.LeftMargin, pageSize.GetBottom(document.BottomMargin)); cb.ShowText(text); cb.EndText(); cb.AddTemplate(template, document.LeftMargin + len, pageSize.GetBottom(document.BottomMargin)); } public override void OnCloseDocument(PdfWriter writer, Document document) { base.OnCloseDocument(writer, document); string fontPath = Environment.GetFolderPath(Environment.SpecialFolder.Fonts); string stFontPath = Path.Combine(fontPath, "simsun.ttc,0"); BaseFont baseFont = BaseFont.CreateFont(stFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); template.BeginText(); template.SetFontAndSize(baseFont, 10); template.SetTextMatrix(12, 0); template.ShowText("共" + writer.PageNumber + "页"); template.EndText(); } } }