1. 程式人生 > >C#關於iTextSharp將html轉換為pdf不支援中文問題

C#關於iTextSharp將html轉換為pdf不支援中文問題

使用iTextSharp的XMLWorker來解析帶html標籤的文字

修改iTextSharp\iTextSharp\textFontFactoryImp.cs中的public virtual int RegisterDirectories()方法使其掃描自己所需要的中文字型

            {
                int count = 0;
                string PATH = "自己字型所在的路徑";
                count += RegisterDirectory(PATH);
                return count;
            }

由於C:\Windows\Fonts字型檔案很多 掃描需要時間就會長  只把自己需要的拿出來用就可以了

程式碼

                FontFactory.RegisterDirectories();


                Document document = new Document();


                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath(NewPdfPath), FileMode.Create));


                document.Open();


                TextReader stringReader = new StringReader(htmlText.ToString());


                XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, stringReader);


                document.Close();
            }

其中htmlText是一串有HTML標籤的程式碼的字串

更多疑問就看看(iText in Action, 2nd Edition)英文文字版  

一些簡單的使用可以看看  XMLWorker Documentation

http://demo.itextsupport.com/xmlworker/itextdoc/flatsite.html