准备工作,创建html模板,在需要动态显示的地方使用占位符,以便后台随时替换。
在Controller里面,获取html模板。并替换占位符。
var result = new SingleRecordResult<string>(); try { new GeneratePDFHelper().DeleteOldFile();
//获取模板路径 var url = Directory.GetCurrentDirectory() + "/Template/DeliveryTemplate.html";
//读取html里面的代码 var HtmlTemplate = new GeneratePDFHelper().getUrltoHtml(url); generatePDFView.tripName = _serviceClient.GetTripDetail(generatePDFView.tripId)?.TripName; generatePDFView.customerName = _serviceClient.GetCustomerDetail(generatePDFView.customer)?.TradingName; generatePDFView.carrierName = _serviceClient.GetCarrierDetail(generatePDFView.carrier)?.CarrierName; generatePDFView.fisheryName = generatePDFView.fishery == 0 ? "" : _serviceClient.GetFisheryDetail(generatePDFView.fishery)?.FisheryName; generatePDFView.portName = generatePDFView.port == 0 ? "" : _serviceClient.GetPortDetail(generatePDFView.port)?.PortName;
//将实体代入方法,替换占位符 var HtmlCode = new GeneratePDFHelper().ConvertHtmlofModel(HtmlTemplate, generatePDFView);
//开始生成PDF result.Data = new GeneratePDFHelper().Generate(HtmlCode, "/OutPut"); } catch (Exception ex) { result.Status = -1; result.Message = ex.Message; _logger.LogError(ex, string.Concat(ex.Message)); } return result;
生成PDF的核心代码:
public class GeneratePDFHelper { public string Generate(string htmlText,string savePath) { string path = Directory.GetCurrentDirectory() + savePath; if (!Directory.Exists(path)) Directory.CreateDirectory(path);
//将要生成的PDF名字和路径 string filePath = "/Report_" + DateTime.Now.ToString("yyyyMMddHHmmsss") + ".pdf"; this.ConvertHtmlTextToPDF(htmlText, path + filePath); return savePath + filePath; } public void ConvertHtmlTextToPDF(string htmlText,string filePath) { if (string.IsNullOrEmpty(htmlText)) { return; } var fs = new FileStream(filePath, FileMode.Create); var doc = new Document(PageSize.A4); var pdfWriter = PdfWriter.GetInstance(doc, fs);
//重写PageEventHelper, 输入PDF页脚的页码
PageEventHelper pageEventHelper = new PageEventHelper();
pdfWriter.PageEvent = pageEventHelper;
doc.Open();
//插入LOGO if (!string.IsNullOrEmpty(Directory.GetCurrentDirectory() + "/Img/logo.png")) { Image img = Image.GetInstance(Directory.GetCurrentDirectory() + "/Img/logo.png"); img.SetAbsolutePosition(20, (doc.PageSize.Height - 130) - 20); img.ScaleAbsolute(100, 130); doc.Add(img); }
var css = new StreamReader(Directory.GetCurrentDirectory() + "/Template/Report.css").ReadToEnd(); using (var msCss = new MemoryStream(Encoding.UTF8.GetBytes(css))) { using (var msHtml = new MemoryStream(Encoding.UTF8.GetBytes(htmlText))) { XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, doc, msHtml, null, Encoding.UTF8); } } doc.Close(); fs.Close(); pdfWriter.Close(); } public string getUrltoHtml(string url) { string html = ""; try { using (StreamReader reader = new StreamReader(url)) { html = reader.ReadToEnd(); } return html; } catch { } return ""; } public string ConvertHtmlofModel(string html, GeneratePDFViewModel generatePDF) {return html.Replace("{{PrintData}}", DateTime.Now.ToString("dd MMM yyyy HH:mm")) .Replace("{{TripNumber}}", generatePDF.tripName) .Replace("{{Customer}}", generatePDF.customerName) .Replace("{{Address}}", generatePDF.address) .Replace("{{Carrier}}", generatePDF.carrierName) .Replace("{{TrailerNumber}}", generatePDF.trailer) .Replace("{{Consignment}}", generatePDF.consignment) .Replace("{{CarrierContact}}", generatePDF.carrierContact) .Replace("{{CarrierPhone}}", generatePDF.carrierPhone) .Replace("{{TrackingURL}}", generatePDF.trackingurl) .Replace("{{Fishery}}", generatePDF.fisheryName) .Replace("{{Port}}", generatePDF.portName) .Replace("{{PalletCount}}", generatePDF.pallets) .Replace("{{ContainerCount}}", generatePDF.boxes != 0 ? generatePDF.boxes.ToString() : "") .Replace("{{BagCount}}", generatePDF.bags != 0 ? generatePDF.bags.ToString() : "") .Replace("{{ETADate}}", generatePDF.etadate) .Replace("{{ETATime}}", generatePDF.etatime) .Replace("{{Temps}}", temperatureHtml) .Replace("{{Comments}}", generatePDF.Additional) .Replace("{{SpeciesDetail}}", reviewOrder); } public void DeleteOldFile() { try { var temp = Directory.GetCurrentDirectory() + "/OutPut"; System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(temp); System.IO.FileInfo[] files = directoryInfo.GetFiles("*.*"); for (int i = 0; i < files.Length; i++) { if (files[i].CreationTime.AddDays(1) < DateTime.Now) { System.IO.File.Delete(files[i].FullName.Trim()); } } } catch { } } }
自定义页码的辅助类:
public class PageEventHelper: PdfPageEventHelper { PdfContentByte cb; PdfTemplate template; BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\Arial.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); public override void OnOpenDocument(PdfWriter writer, Document document) { cb = writer.DirectContent; template = cb.CreateTemplate(50, 50); } public override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); int pageN = writer.PageNumber; String text = "Page " + pageN.ToString() + " of "; iTextSharp.text.Rectangle pageSize = document.PageSize; cb.BeginText(); cb.SetFontAndSize(font, 12); cb.SetTextMatrix(document.LeftMargin, pageSize.GetBottom(document.BottomMargin)); cb.ShowText(text); cb.EndText(); cb.AddTemplate(template, document.LeftMargin + 60, pageSize.GetBottom(document.BottomMargin)); } public override void OnCloseDocument(PdfWriter writer, Document document) { base.OnCloseDocument(writer, document); template.BeginText(); template.SetFontAndSize(font, 12); template.SetTextMatrix(0, 0); template.ShowText("" + (writer.PageNumber)); template.EndText(); } }