在将Html转换为Pdf时显示Unicode字符

时间:2012-04-26 08:36:25

标签: c# unicode itext

我正在使用itextsharp dll将HTML转换为PDF。

HTML有一些Unicode字符,如α,β......当我尝试将HTML转换为PDF时,Unicode字符不会以PDF格式显示。

我的功能:

Document doc = new Document(PageSize.LETTER);

using (FileStream fs = new FileStream(Path.Combine("Test.pdf"), FileMode.Create, FileAccess.Write, FileShare.Read))
{
    PdfWriter.GetInstance(doc, fs);

    doc.Open();
    doc.NewPage();

    string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
                                      "ARIALUNI.TTF");

    BaseFont bf = BaseFont.CreateFont(arialuniTff, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

    Font fontNormal = new Font(bf, 12, Font.NORMAL);

    List<IElement> list = HTMLWorker.ParseToList(new StringReader(stringBuilder.ToString()),
                                                 new StyleSheet());
    Paragraph p = new Paragraph {Font = fontNormal};

    foreach (var element in list)
    {
        p.Add(element);
        doc.Add(p);
    }

    doc.Close();
}

5 个答案:

答案 0 :(得分:16)

您还可以使用新的 XMLWorkerHelper (来自库 itextsharp.xmlworker ),但是您需要覆盖默认的FontFactory实现。

void GeneratePdfFromHtml()
{
  const string outputFilename = @".\Files\report.pdf";
  const string inputFilename = @".\Files\report.html";

  using (var input = new FileStream(inputFilename, FileMode.Open))
  using (var output = new FileStream(outputFilename, FileMode.Create))
  {
    CreatePdf(input, output);
  }
}

void CreatePdf(Stream htmlInput, Stream pdfOutput)
{
  using (var document = new Document(PageSize.A4, 30, 30, 30, 30))
  {
    var writer = PdfWriter.GetInstance(document, pdfOutput);
    var worker = XMLWorkerHelper.GetInstance();

    document.Open();
    worker.ParseXHtml(writer, document, htmlInput, null, Encoding.UTF8, new UnicodeFontFactory());

    document.Close();
  }    
}

public class UnicodeFontFactory : FontFactoryImp
{
    private static readonly string FontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
      "arialuni.ttf");

    private readonly BaseFont _baseFont;

    public UnicodeFontFactory()
    {
      _baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

    }

    public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color,
      bool cached)
    {
      return new Font(_baseFont, size, style, color);
    }
}

答案 1 :(得分:11)

在处理Unicode字符和iTextSharp时,您需要注意几件事。你已经做过的第一个,那就是得到一个支持你角色的字体。第二件事是你想用iTextSharp实际注册字体,以便它知道它。

//Path to our font
string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
//Register the font with iTextSharp
iTextSharp.text.FontFactory.Register(arialuniTff);

现在我们有了一个字体,我们需要创建一个StyleSheet对象,告诉iTextSharp何时以及如何使用它。

//Create a new stylesheet
iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();
//Set the default body font to our registered font's internal name
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS");

您还需要执行的一个非HTML部分是设置一个特殊的encoding参数。此编码特定于iTextSharp,在您的情况下,您希望它是Identity-H。如果您未设置此项,则默认为Cp1252WINANSI)。

//Set the default encoding to support Unicode characters
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);

最后,我们需要将样式表传递给ParseToList方法:

//Parse our HTML using the stylesheet created above
List<IElement> list = HTMLWorker.ParseToList(new StringReader(stringBuilder.ToString()), ST);

将这些全部放在一起,从开放到结束你都有:

doc.Open();

//Sample HTML
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(@"<p>This is a test: <strong>α,β</strong></p>");

//Path to our font
string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
//Register the font with iTextSharp
iTextSharp.text.FontFactory.Register(arialuniTff);

//Create a new stylesheet
iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();
//Set the default body font to our registered font's internal name
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS");
//Set the default encoding to support Unicode characters
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);

//Parse our HTML using the stylesheet created above
List<IElement> list = HTMLWorker.ParseToList(new StringReader(stringBuilder.ToString()), ST);

//Loop through each element, don't bother wrapping in P tags
foreach (var element in list) {
    doc.Add(element);
}

doc.Close();

修改

在评论中,您会显示指定覆盖字体的HTML。 iTextSharp不会使系统占用字体,其HTML解析器不使用字体回退技术。必须手动注册HTML / CSS中指定的任何字体。

string lucidaTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "l_10646.ttf");
iTextSharp.text.FontFactory.Register(lucidaTff);

答案 2 :(得分:0)

private class UnicodeFontFactory : FontFactoryImp
{
    private BaseFont _baseFont;

    public  UnicodeFontFactory()
    {
        string FontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arialuni.ttf");
        _baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);                
    }

    public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
    {                                
        return new Font(_baseFont, size, style, color);
    }
}  

//和代码

FontFactory.FontImp = new UnicodeFontFactory();

string convertedHtml = string.Empty;
foreach (char c in htmlText)
{
     if (c < 127)  
           convertedHtml += c;
     else
           convertedHtml += "&#" + (int)c + ";";
}

List<IElement> htmlElements = XMLWorkerHelper.ParseToElementList(convertedHtml, null);

// add the IElements to the document
foreach (IElement htmlElement in htmlElements)
{                            
      document.Add(htmlElement);
}

答案 3 :(得分:0)

这必须是迄今为止我必须解决的最困难的问题之一。 Web上的答案(包括堆栈溢出)信息不佳或过时。格雷戈尔的答案非常接近。我想回馈这个社区,因为我花了很多时间来得到这个答案。

这是我用c#编写的一个非常简单的程序,作为自己笔记的示例。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;

namespace ExampleOfExportingPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //Build HTML document
            StringBuilder sb = new StringBuilder();
            sb.Append("<body>");
            sb.Append("<h1 style=\"text-align:center;\">これは日本語のテキストの例です。</h1>");
            sb.Append("</body>");

            //Create our document object
            Document Doc = new Document(PageSize.A4);


            //Create our file stream
            using (FileStream fs = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf"), FileMode.Create, FileAccess.Write, FileShare.Read))
            {
                //Bind PDF writer to document and stream
                PdfWriter writer = PdfWriter.GetInstance(Doc, fs);

                //Open document for writing
                Doc.Open();


                //Add a page
                Doc.NewPage();

                MemoryStream msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(sb.ToString()));
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, Doc, msHtml, null, Encoding.UTF8, new UnicodeFontFactory());

                //Close the PDF
                Doc.Close();
            }

        }

        public class UnicodeFontFactory : FontFactoryImp
        {
            private static readonly string FontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
          "arialuni.ttf");

            private readonly BaseFont _baseFont;

            public UnicodeFontFactory()
            {
                _baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

            }

            public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color,
          bool cached)
            {
                return new Font(_baseFont, size, style, color);
            }
        }

    }
}

希望这会在将来节省一些时间。

答案 4 :(得分:-2)

以下是在将Html转换为Pdf时显示unicode字符的几个步骤

  1. 创建HTMLWorker
  2. 注册unicode字体并指定它
  3. 创建样式表并将编码设置为Identity-H
  4. 将样式表分配给html解析器
  5. 检查以下链接以获取更多理解....

    使用此方法在从HTML转换为PDF时也会显示印地语,土耳其语和特殊字符。查看下面的演示图片。

    enter image description here