using System; using System.Collections.Generic; using System.Linq; using System.Text; using iTextSharp.text.pdf; using iTextSharp.text; using System.IO; using System.Threading; using System.Windows.Forms; using System.Drawing; using System.Web; using iTextSharp.text.html.simpleparser; namespace Woo.Utility { /// <summary> /// html转Pdf /// </summary> public class HTML2PDF { private const int WIDTH = 800, HEIGHT = 1147; private string url; private Bitmap bitmap; private void GetBitmap() { using (WebBrowser wb = new WebBrowser()) { wb.Width = WIDTH; wb.Height = HEIGHT; wb.ScrollBarsEnabled = false; wb.Navigate(url); //确保页面被解析完全 while (wb.ReadyState != WebBrowserReadyState.Complete) { System.Windows.Forms.Application.DoEvents(); } bitmap = new System.Drawing.Bitmap(WIDTH, HEIGHT); wb.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, WIDTH, HEIGHT)); wb.Dispose(); } } /// <summary> /// 创建PDF /// </summary> /// <param name="HtmlUrl"></param> /// <param name="SavePath"></param> public void CreatPdf(string HtmlUrl, string SavePath) { HtmlUrl = IOUtility.TransUrl(HtmlUrl); SavePath = IOUtility.TransFilePath(SavePath); Document doc = new Document(new iTextSharp.text.Rectangle(550, 1140), 10, 10, 0, 0); MemoryStream ms = new MemoryStream(); try { PdfWriter writer = PdfWriter.GetInstance(doc, ms); writer.CloseStream = false; doc.Open(); this.url = HtmlUrl; Thread thread = new Thread(new ThreadStart(GetBitmap)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); while (thread.IsAlive) Thread.Sleep(100); bitmap.Save(@"E:\a.jpg"); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Bmp); //img.ScalePercent(75);//560 630 //595,842 //int percent = (int)PageSize.A4.Width * 100 / 1024; //58 //int percent = 50; img.ScalePercent(65); doc.Add(img); } catch (Exception ex) { LogUtility.WriteErrorLog(ex); throw; } finally { doc.Close(); if (File.Exists(SavePath)) { File.Delete(SavePath); } using (FileStream fs = new FileStream(SavePath, FileMode.Create)) { ms.Position = 0; byte[] bit = new byte[ms.Length]; ms.Read(bit, 0, (int)ms.Length); fs.Write(bit, 0, bit.Length); } } } /// <summary> /// 创建PDF /// </summary> /// <param name="FileName"></param> /// <param name="SavePath">保存文件路径</param> /// <param name="Data"></param> /// <param name="Title">标题</param> /// <param name="SubTitle">副标题</param> /// <param name="Aligns">对其方式列表</param> public static void CreatePdf(List<List<string>> Data, string FileName = "report.pdf", string SavePath = "", string Title = null, string SubTitle = null, List<Woo.Model.WooReport.ColumnAlignEnum> Aligns = null) { HttpResponse response = HttpContext.Current.Response; response.Clear(); response.Buffer = true; response.Charset = "utf-8"; response.ContentType = "application/ms-excel"; response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName); if (SavePath == "") { SavePath = string.Format("~/Upload/Report/{0:yyyyMMddhhmmssfff}.pdf", DateTime.Now); } CreatePdfInner(Data, SavePath, Title, SubTitle, Aligns: Aligns); response.WriteFile(SavePath); } private static void CreatePdfInner(List<List<string>> Data, string Path, string Title = null, string SubTitle = null, List<Woo.Model.WooReport.ColumnAlignEnum> Aligns = null) { Path = IOUtility.TransFilePath(Path); var width = 550; //Document document = new Document(PageSize.A4, 50, 50, 50, 50); //Document doc = new Document(new iTextSharp.text.Rectangle(550, 1140), 10, 10, 0, 0); var doc = new Document(PageSize.A4, 10, 10, 10, 10); var stm = new FileStream(Path, FileMode.Create); var fontPath = @"~/Content/simsun.ttc"; fontPath = IOUtility.TransFilePath(fontPath); var fontPath1 = @"~/Content/msyhbd.ttc"; fontPath1 = IOUtility.TransFilePath(fontPath1); PdfWriter.GetInstance(doc, stm); doc.Open(); //var fontbase = BaseFont.CreateFont(@"c:\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); var fontbase = BaseFont.CreateFont(fontPath + ",1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); var font = new iTextSharp.text.Font(fontbase, 8); var fontbase1 = BaseFont.CreateFont(fontPath1 + ",1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); var font1 = new iTextSharp.text.Font(fontbase1, 8); if (!string.IsNullOrEmpty(Title)) { var fonttitle = new iTextSharp.text.Font(fontbase1, 24); var titlePara = new iTextSharp.text.Paragraph(Title, fonttitle); titlePara.Alignment = Element.ALIGN_CENTER; titlePara.SpacingAfter = 10; doc.Add(titlePara); } if (!string.IsNullOrEmpty(SubTitle)) { var fontsubtitle = new iTextSharp.text.Font(fontbase, 8); var subtitlePara = new iTextSharp.text.Paragraph(SubTitle, fontsubtitle); subtitlePara.Alignment = Element.ALIGN_RIGHT; subtitlePara.SpacingAfter = 10; doc.Add(subtitlePara); } var rows = Data.Count; var cols = 0; if (rows > 0) { cols = Data[0].Count; } if (cols == 0) return; var tab = new PdfPTable(cols); var cellwidths = new List<int>(); for (var i = 0; i < cols; i++) { cellwidths.Add(width / cols); } //tab.SetWidths(cellwidths.ToArray()); tab.WidthPercentage = 100; var IsFirstRow = true; foreach (var item in Data) { var colindex = -1; foreach (var item1 in item) { colindex++; var p = new Phrase(item1, font); if (IsFirstRow) { p = new Phrase(item1, font1); } var cell = new PdfPCell(p); if (IsFirstRow) { cell.HorizontalAlignment = Element.ALIGN_CENTER; } var align = Woo.Model.WooReport.ReportExtensions.GetAlign(Aligns, colindex); switch (align) { case Model.WooReport.ColumnAlignEnum.Center: cell.HorizontalAlignment = Element.ALIGN_CENTER; break; case Model.WooReport.ColumnAlignEnum.Right: cell.HorizontalAlignment = Element.ALIGN_RIGHT; break; } //cell.Colspan = 1; //cell.Rowspan = 1; //cell.HorizontalAlignment = Element.ALIGN_CENTER; //cell.DisableBorderSide(1); //cell.DisableBorderSide(2); //cell.DisableBorderSide(4); //cell.DisableBorderSide(8); cell.NoWrap = false; tab.AddCell(cell); } IsFirstRow = false; } doc.Add(tab); doc.Close(); } private static void SetFont(BaseFont normalfont, BaseFont boldfont, PdfPTable tab) { foreach (var row in tab.Rows) { var cells = row.GetCells(); foreach (var cell in cells) { if (cell == null || cell.CompositeElements == null) continue; foreach (var el in cell.CompositeElements) { var para1 = el as Paragraph; if (para1 != null) { SetFont(normalfont, boldfont, para1); continue; } var tab1 = el as PdfPTable; if (tab1 != null) { SetFont(normalfont, boldfont, tab1); continue; } } } } } private static void SetFont(BaseFont normalfont, BaseFont boldfont, Paragraph para) { for (var i = 0; i < para.Count; i++) { var ck = para[i] as Chunk; if (ck != null) { if (ck.Font.IsBold()) { ck.Font = new iTextSharp.text.Font(boldfont, ck.Font.Size, ck.Font.Style, ck.Font.Color); } else { ck.Font = new iTextSharp.text.Font(normalfont, ck.Font.Size, ck.Font.Style, ck.Font.Color); } } } } /// <summary> /// 创建pdf到输出流 /// </summary> /// <param name="html"></param> /// <param name="FileName"></param> public static void CreatePdf(string html, string FileName = "report.pdf") { CreatePdf(html, PageSize.A4.Width, PageSize.A4.Height, FileName); } public static void CreatePdf(string html, float urx, float ury, string FileName) { var response = System.Web.HttpContext.Current.Response; response.Clear(); response.Buffer = true; response.Charset = "utf-8"; response.ContentType = "application/octet-stream"; response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName); var stm = response.OutputStream; //最后4个参数标示是左右上下的距离 var doc = new Document(new iTextSharp.text.RectangleReadOnly(urx, ury),35f,35f,-8f,2f); var writer = PdfWriter.GetInstance(doc, stm); doc.Open(); var sr = new StringReader(html); var fontPath = @"~/Content/simsun.ttc"; fontPath = IOUtility.TransFilePath(fontPath);
var fontPath1 = @"~/Content/msyhbd.ttc"; fontPath1 = IOUtility.TransFilePath(fontPath1); var fontbase = BaseFont.CreateFont(fontPath + ",1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); var font = new iTextSharp.text.Font(fontbase, 12); var fontbase1 = BaseFont.CreateFont(fontPath1 + ",1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); var font1 = new iTextSharp.text.Font(fontbase1, 12); var style = new StyleSheet(); var objs = HTMLWorker.ParseToList(sr, style); Paragraph context = new Paragraph(); foreach (var item in objs) { var para = item as Paragraph; if (para != null) { SetFont(fontbase, fontbase1, para); } var tab = item as PdfPTable; if (tab != null) { SetFont(fontbase, fontbase1, tab); } context.Add(item); } doc.Add(context); doc.Close(); } } }
|