2017-10-08 40 views
0

我将创建一个用于在单击按钮后生成PDF文件的应用程序。该应用程序适用于英语,但不适用于中文。我使用utf-8进行编码,所以我无法确定导致问题的原因。下面是主要的脚本:使用.NET创建PDF作为问号标记显示中文

using PdfSharp.Drawing; 
using PdfSharp.Pdf; 
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Diagnostics; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace WindowsFormsApp1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      PdfDocument pdf = new PdfDocument(); 
      pdf.Info.Title = "My First PDF"; 
      PdfPage pdfPage = pdf.AddPage(); 
      XGraphics graph = XGraphics.FromPdfPage(pdfPage); 
      XFont font = new XFont("Microsoft Himalaya", 35, XFontStyle.Regular); 
      graph.DrawString("香港", font, XBrushes.Black, new XRect(0, 0, pdfPage.Width.Point, 170), XStringFormats.Center); 
      string pdfFilename = "firstpage.pdf"; 
      pdf.Save(pdfFilename); 
      Process.Start(pdfFilename); 
     } 
    } 
} 

这是在app.config:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <startup> 
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> 
    </startup> 
</configuration> 

回答

0

你在程序中使用不要紧的编码,您的PDF创建字体是一个ANSI字体。

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

XFont font = new XFont("Times New Roman", 12, XFontStyle.Regular, options); 

参见:
http://pdfsharp.net/wiki/Unicode-sample.ashx

embedding选项移除IIRC,但你还是要设置编码。

+0

感谢您的回复。使用完全相同的代码后,中文字符会从问号变为方块。我将Unicode更改为其他字体编码方法,但字符消失。有没有其他解决问题的方法? –

+0

还要确保您使用的字体包含您需要的字形。在我的电脑上,“微软喜马拉雅”包含藏文,但没有CJK字符。也许试试“微软JhengHei”。使用'charmap.exe'来检查所需的字形是否可用。 –

相关问题