1. 程式人生 > 其它 >基於iTextSharp, 使用HTML模板生成PDF

基於iTextSharp, 使用HTML模板生成PDF

準備工作,建立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();

        }
    }