天天看點

C#使用iTextSharp操作PDF檔案

概述

html檔案怎麼轉成PDF檔案?有的招聘網上的履歷導成DOC檔案,不能直接使用,這樣造成很大的困擾,那麼它還有一個格式,那就是html格式。将檔案導出成html格式,然後再轉成PDF檔案,這樣便可以直接使用了。平常在項目中也是很多這樣的需求,需要把内容轉成pdf檔案。

下面我們來看下使用  iTextSharp實作HTML轉PDF的方法。

代碼實作

1、nuget 安裝iTextSharp。

C#使用iTextSharp操作PDF檔案
using iTextSharp.text;
using iTextSharp.text.pdf;      

2、将Html文檔轉換為pdf。

/// <summary>
        /// 将Html文檔轉換為pdf
        /// </summary>
        /// <param name="htmlText"></param>
        /// <returns></returns>
        public byte[] ConvertHtmlTextToPDF(string htmlText)
        {
            if (string.IsNullOrEmpty(htmlText))
                return null;
            //避免當htmlText無任何html tag标簽的純文字時,轉PDF時會挂掉,是以一律加上<p>标簽
            htmlText = "<p>" + htmlText + "</p>";
            using (var outputStream = new MemoryStream())
            {
                byte[] data = Encoding.UTF8.GetBytes(htmlText);
                var msInput = new MemoryStream(data);
                var doc = new Document();//pdf文檔,預設A4格式。
                var writer = PdfWriter.GetInstance(doc, outputStream);
                doc.Open();
                //使用XMLWorkerHelper把Html parse到PDF
                iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());
                //指定預設縮放比例為100%
                var pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
                //将預設設定寫入pdf
                var action = PdfAction.GotoLocalPage(1, pdfDest, writer);
                writer.SetOpenAction(action);
                doc.Close();
                msInput.Close();
                outputStream.Close();
                return outputStream.ToArray();
            }
        }      

3、Unicode 字型支援。

/// <summary>
        /// Unicode 字型支援
        /// </summary>
        public class UnicodeFontFactory : FontFactoryImp
        {
            public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
            {
                //使用微軟雅黑字型解決中文亂碼的問題,因為雅黑字型為字型集合是以需要使用,0來指定具體的字型。
                //var chineseFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "msyh.ttc,0");
                //宋體
                //BaseFont baseFont = BaseFont.CreateFont(@"c:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                //黑體
                BaseFont baseFont = BaseFont.CreateFont(@"c:\Windows\Fonts\SIMHEI.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                //var baseFont = BaseFont.CreateFont(chineseFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                return new Font(baseFont, size, style, color);
            }
        }      
string content = temp.Content;
            foreach (var dict in dicts)
            {
                content = content.Replace("{{" + dict.Key + "}}", dict.Value);
            }
            var path = _esignInfo.Value.ContractPath;
            //if (entity.ContractType == ContractType.First)
            //{
            //    path += "/" + appId + "/Agreements";
            //}
            entity.OriginalFileUrl = _pdfHelper.WritePdfFile(content, contractNo, path, "PDF");
            bool isSucc = !String.IsNullOrEmpty(entity.OriginalFileUrl);