我有一些包含Omega字符(0x3A9)的文本,当我以默认的Helvetica字体显示此字符时,PDF中没有任何内容。
我正在使用
创建我的字体BaseFont Helvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
并且,正如预期的那样,Helvetica.CharExists(0x3A9)返回false。
我还为TIMES_ROMAN,SYMBOL和ZAPF_DINGBATS字体调用CharExists(0x3A9)。全部都是假的。
我的文件是英文的,但有一些特殊字符 - 加/减,左右双引号,微米等。
P.S。我看到我可以创建一个Arial字体:
BaseFont arial = BaseFont.CreateFont("c:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
并且包含字符0x3A9的字形。但显然我无法使用IDENTITY_H编码创建HELVETICA字体。
答案 0 :(得分:0)
我最终得到的结果有点复杂,但看起来很稳固。每次我都要在我的文档中添加文本,到目前为止我只是创建一个新的短语,我首先枚举字符串中的每个字符并调用BaseFont.CharExists()。如果任何字符的答案都是假的,我会根据CharExists()的连续序列为true或false将文本拆分为块。然后,对于Helvetica中存在的块,我在Helvetica中创建了一个Chunk,其他的我在Arial中创建了一个Chunk,并将这些块组装成我的短语。
我这样做的原因(这对大多数读者来说可能是显而易见的,但以防万一)是因为我不想总是将Arial字体添加到我的PDF文件中(以保持大小不变),以及95%的文档不包含需要Arial的Omega等字符。这样,我只将Arial字体添加到实际需要它的那些文档中。
Phrase phrase = null;
string s = "";
for (int i = 0 ; i < text.Length ; i++)
{
char c = text[i];
if (fonts.Regular.BaseFont.CharExists(c))
s += c; // Accumulate Helvetica characters in 's'
else
{
// Try adding the Arial font
iTextSharp.text.Font arial = fonts.Arial; // Creates the Arial font and adds it to the document if not already there
if (arial == null)
{
Debug.WriteLine(" Arial font not found");
s += c;
}
else if (!arial.BaseFont.CharExists(c))
{
Debug.WriteLine(" Arial does not contain the required glyph");
s += c;
}
else
{
// We have a character that Helvetica doesn't have, that Arial does
if (phrase == null)
{
// This is the first time we've realize that we need a split phrase
if (s.Length > 0)
{
// There was Helvetica text before the Arial character.
phrase = new Phrase(s, fonts.Regular);
// This code assumes that non-Helvetica characters generally come singly
phrase.Add(new Chunk(c, arial));
s = "";
}
else
{
// The Arial character is the first one in the string
phrase = new Phrase(new Chunk(c, arial));
}
}
else
{
// This is not the first Arial character in the string
if (s != "")
{
// There were Helvetica characters before this Arial character
phrase.Add(new Chunk(s, fonts.Regular);
s = "";
}
phrase.Add(new Chunk(c, arial));
}
}
}
}
if (phrase == null)
{
// We did not encounter any Arial characters, create a simple Phrase
phrase = new Phrase(text, fonts.Regular);
}
else if (s.Length > 0)
{
// There were Helvetica characters at the end of the string, add them now
phrase.Add(new Chunk(s, fonts.Regular));
}