8

itextsharpdllを使用して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();
}
4

5 に答える 5

16

新しいXMLWorkerHelper(ライブラリitexsharp.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);
    }
}
于 2013-01-09T12:16:26.907 に答える
13

Unicode文字とiTextSharpを扱う場合、注意が必要なことがいくつかあります。あなたがすでに行った最初のものであり、それはあなたのキャラクターをサポートするフォントを手に入れています。2つ目は、フォントを実際に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);
于 2012-04-26T15:26:09.953 に答える
1
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);
}
于 2018-07-24T08:28:31.987 に答える
0

これは、私がこれまでに理解しなければならなかった最も難しい問題の1つでなければなりません。スタックオーバーフローを含む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;\">これは日本語のテキストの例です。&lt;/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);
            }
        }

    }
}

うまくいけば、これは将来誰かを節約するでしょう。

于 2018-10-24T22:06:06.613 に答える
-2

HTMLをPDFに変換する際にUnicode文字を表示するためのいくつかの手順は次のとおりです。

  1. HTMLWorkerを作成する
  2. Unicodeフォントを登録して割り当てます
  3. スタイルシートを作成し、エンコーディングをIdentity-Hに設定します
  4. スタイルシートをhtmlパーサーに割り当てます

詳細については、以下のリンクを確認してください。

この方法を使用してHTMLからPDFに変換するときに、ヒンディー語、トルコ語、および特殊文字も表示されます。以下のデモ画像を確認してください。

ここに画像の説明を入力してください

于 2015-12-23T17:57:05.830 に答える