2013-02-26 127 views
1

我想用UTF-8而不是CP1250来显示国家字符。我发现支持UTF-8的AddParagraph方法,但是我找不到任何压模示例。如何在iTextSharp PDF Stamper中使用UTF-8编码?

这是代码片段与CP1250:

 PdfReader reader = new PdfReader(templatePath); 
     byte[] bytes; 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      using (PdfStamper stamper = new PdfStamper(reader, ms)) 
      { 
       PdfContentByte cb = stamper.GetOverContent(1); 

       BaseFont bf = BaseFont.CreateFont(
        BaseFont.COURIER_BOLD, 
        BaseFont.CP1250, 
        true); 

       //Begin text command 
       cb.BeginText(); 
       //Set the font information       
       cb.SetFontAndSize(bf,12f); 

       //Position the cursor for drawing 
       cb.MoveText(field.X, field.Y); 
       //Write some text 
       cb.ShowText(field.Text); 
       //End text command 
       cb.EndText(); 

       //Flush the PdfStamper's buffer 
       stamper.Close(); 
       //Get the raw bytes of the PDF 
       bytes = ms.ToArray(); 
      } 
     } 

如何使用UTF-8?

回答

7

如果您需要来自单个字体的大量字符,则很可能应将IDENTITY_H(或垂直文本中的IDENTITY_V)用作编码。

例如为:

public const string FONT = "c:/windows/fonts/arialbd.ttf"; 
BaseFont bf = BaseFont.CreateFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); 

参看供在上下文中使用的Webified iTextSharp ExampleUnicodeExample.cs

+0

奇怪,但cb.ShowText(field.Text);在解决方案中出现错误。 cb.ShowText(field.Text +“”);也工作得很好。 – 2013-02-26 13:52:37

+0

你还知道哪个错误? – mkl 2013-02-26 14:52:01

+0

如果field.Text为null,那么它将无法使用UTF-8格式。没问题,我添加“”使其为空而不是空。 – 2013-02-27 15:50:46