在Windows上打印PDF時,需要根據文本中的字符選擇字體。用於粗體文本的iTextSharp.text.pdf.FontSelector
我想使用iTextSharp FontSelector,但我希望正確的字體可以是不同的粗體和普通字體。但是字體選擇器沒有粗體的參數。
我不太瞭解中文字體,但我想simsun.ttc中沒有粗體字體,simhei.ttf可以選擇粗體字體(如果我錯了,請糾正我)。我應該選擇不同的粗體字體嗎?如何?
const int fontSizeforSelector = 12;
static Font Arial;
static Font SimplifiedArabic;
static Font Andalus;
static Font TraditionalArabic;
static Font Tahoma;
static Font Simpo;
static Font Batang;
static Font Simsun;
static Font ArialUni;
static Font Simpbdo;
static Font Simhei;
static iTextSharp.text.pdf.FontSelector _fontSelector = new iTextSharp.text.pdf.FontSelector();
static MyFontSelector()
{
string winDir = Environment.GetEnvironmentVariable("WINDIR");//!-!
if (winDir.IsNullOrEmpty())
winDir = GetWindowsDirectory();
string fontDir = winDir + "\\Fonts\\";//!-!
Arial = TryCreateFont(fontDir, "arial.ttf");
SimplifiedArabic = TryCreateFont(fontDir,"simpo.ttf");
Andalus = TryCreateFont(fontDir,"andlso.ttf");
TraditionalArabic = TryCreateFont(fontDir,"trado.ttf");
Tahoma = TryCreateFontEmbedded(fontDir, "tahoma.ttf");
Simpo = TryCreateFontEmbedded(fontDir, "simpo.ttc");//!-!
Batang = TryCreateFontEmbedded(fontDir, "batang.ttc");//!-!
Simsun = TryCreateFontEmbedded(fontDir, "simsun.ttc,1");//!-!
ArialUni = TryCreateFontEmbedded(fontDir, "arialuni.ttf");//!-!
Simpbdo = TryCreateFontEmbedded(fontDir, "simpbdo.ttf");//!-!
Simhei = TryCreateFontEmbedded(fontDir, "simhei.ttf");//!-!
//http://stackoverflow.com/questions/16415074/detecting-cjk-characters-in-a-string-c/16429065#16429065
//http://www.computarat.com/files/java/Test9.java
if (Arial != null)
_fontSelector.AddFont(Arial);
if (SimplifiedArabic != null)
_fontSelector.AddFont(SimplifiedArabic);
if (Andalus != null)
_fontSelector.AddFont(Andalus);
if (SimplifiedArabic != null)
_fontSelector.AddFont(SimplifiedArabic);
if (TraditionalArabic != null)
_fontSelector.AddFont(TraditionalArabic);
if (Tahoma != null)
_fontSelector.AddFont(Tahoma);
if (Batang != null)
_fontSelector.AddFont(Batang);
if (Simsun != null)
_fontSelector.AddFont(Simsun);
if (ArialUni != null)
_fontSelector.AddFont(ArialUni);
if (Simpbdo != null)
_fontSelector.AddFont(Simpbdo);
if (Simhei != null)
_fontSelector.AddFont(Simhei);
}
private static Font TryCreateFont(string fontDir, string file)
{
try
{
return FontFactory.GetFont(fontDir + file, BaseFont.IDENTITY_H, fontSizeforSelector);
}
catch(Exception ex)
{
Trace.WriteLine(ex);
}
return null;
}
private static Font TryCreateFontEmbedded(string fontDir, string file)
{
try
{
return FontFactory.GetFont(fontDir + file, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
return null;
}
public static iTextSharp.text.pdf.FontSelector FontSelector
{
get
{
return _fontSelector;
}
}
public static BaseFont GetBaseFont(string text)
{
Phrase phrase = _fontSelector.Process(text);
return phrase.Font.GetCalculatedBaseFont(true);
}