PDFSHARP 解決漢字問題


客戶要求生成PDF文件,使用了PDFSHARP,但發現漢字全變成了亂碼。網上也沒有找到針對性的教程。

經翻查源碼,最終解決辦法如下:

LoopNum++;
            this.textBox1.Text += ""+LoopNum.ToString()+"次循環" +"\r\n";
            // Create a new PDF document
            PdfDocument document = new PdfDocument();
            document.Info.Title = "PDFSHARP測試";

            // Create an empty page
            PdfPage page = document.AddPage();

            // Get an XGraphics object for drawing
            XGraphics gfx = XGraphics.FromPdfPage(page);

            //XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);

            System.Drawing.Text.PrivateFontCollection pfcFonts = new System.Drawing.Text.PrivateFontCollection();
            string strFontPath = @"C:/Windows/Fonts/msyh.ttf";//字體設置為微軟雅黑
            pfcFonts.AddFontFile(strFontPath);

            XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
            XFont font = new XFont(pfcFonts.Families[0], 15, XFontStyle.Regular, options);
 
            // Create a font
            //XFont font = new XFont("Times New Roman", 20, XFontStyle.BoldItalic);

            // Draw the text
            gfx.DrawString("你好,世界!", font, XBrushes.Black,
              new XRect(0, 0, page.Width, page.Height),
              XStringFormats.Center);

            // Save the document...
            string filename = "HelloWorld_"+LoopNum.ToString()+".pdf";
            document.Save(filename); 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM