【发布时间】:2014-04-03 00:25:22
【问题描述】:
如果我的系统字体目录中安装了字体,我的 PDF 文件可以正确生成中文字符。当我将它实际部署到 Azure 网站时,我将无法安装字体。
我将字体添加到项目中并且正在部署,应用程序找到了路径,但 iTextSharp 在生成 PDF 时不使用它。
当前有效的代码 -
FontFactory.Register("c:/windows/fonts/ARIALUNI.TTF");
这行不通但是路径不错-
string arialuniTffFont = System.IO.Path.Combine(Server.MapPath("~/bin/fonts/arialuni.ttf"));
FontFactory.Register(arialuniTffFont);
更新:
private void CreatePDF(IList<string> HTMLData, string fileName, bool rotate)
{
//Create PDF document
Document doc = new Document(PageSize.A4, 36, 36, 36, 36);
if (rotate)
{
doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
}
HTMLWorker parser = new HTMLWorker(doc);
string fontpath = Server.MapPath("/Fonts/arialuni.ttf");
FontFactory.Register(fontpath);
StyleSheet styles = new StyleSheet();
styles.LoadTagStyle(HtmlTags.TABLE, HtmlTags.SIZE, "6pt");
styles.LoadTagStyle(HtmlTags.H3, HtmlTags.SIZE, "10pt");
styles.LoadTagStyle(HtmlTags.H5, HtmlTags.SIZE, "6pt");
styles.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS");
styles.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);
parser.SetStyleSheet(styles);
PdfWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create));
doc.Open();
//Try/Catch removed
foreach (var s in HTMLData) {
StringReader reader = new StringReader(s);
parser.Parse(reader);
doc.NewPage();
}
doc.Close();
}
不产生汉字的整个套路。
【问题讨论】:
-
不要怀疑你,但你是否 100% 确定路径是正确的?
MapPath()不验证路径,它只会将看起来相对的东西转换成看起来绝对的东西。所以这不应该导致异常if (!File.Exists(arialuniTffFont)) { throw new FileNotFoundException(); } -
@ChrisHaas,我真的很接近完成这项工作。字体实际上是注册的,只是不使用它来显示汉字。我需要改变什么?
-
注册字体时,我建议始终手动为其分配别名,而不是依赖字体内部的内容。试试这个
FontFactory.Register(fontpath, "Arial Unicode MS"); -
@ChrisHaas,我使用了你的建议,但没有奏效。但我对这个问题做了进一步的研究。首先,我硬编码了部署 .ttf 文件的路径,但仍然无法正常工作。为了确保我没有失去理智,我将 Window/Font 文件夹中的字体复制到了 deploy 文件夹中。我猜我使用的文件不是实际的字体文件,而是预装的字体文件。事情就像他们现在应该做的那样。感谢您的帮助。
标签: c# itextsharp