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
。これを設定しない場合、デフォルトでCp1252
(WINANSI
)になります。
//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);