无法在iTextSharp XMLWorker中设置字体系列

问题描述:

我正在尝试使用itextsharp XMLWorker库将一些HTML解析为PDF.它工作正常,但是我无法在pdf中呈现一些Unicode字符(土耳其语).

I am trying to parse some HTML to PDF using itextsharp XMLWorker library. It is working fine but I am unable to render some Unicode characters (Turkish) into my pdf.

我已经阅读了几个有关此问题的博客,他们都建议注册支持Unicode字符的字体.然后在外部CSS文件中,我需要指定要使用的字体系列.

I have read several blogs about the problem and they all propose registering a font which supports unicode characters. Then in external css file, I need to specify the font family to use.

html
{
    font-family: 'Arial Unicode MS';
}

我也尝试了所有Arial作为家庭.我也尝试过在html中设置家庭.

I also tried all Arial as family too. I tried setting the family in html as well.

<body face = 'Arial'>

他们都没有工作.字体注册没有问题,并且外部CSS文件也可以正常工作.

None of them are working. Font is registered without problems and external CSS file is working too.

这就是我将HTML转换为PDF的方式,

This is how I convert HTML to PDF,

string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
FontFactory.Register(arialuniTff);

// Resolve CSS
var cssResolver = new StyleAttrCSSResolver();
var cssFile = XMLWorkerHelper.GetCSS(new FileStream(Server.MapPath("~/Content/Editor.css"), FileMode.Open));
cssResolver.AddCss(cssFile);

// HTML
CssAppliers ca = new CssAppliersImpl();
HtmlPipelineContext hpc = new HtmlPipelineContext(ca);
hpc.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

// PIPELINES
PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
HtmlPipeline htmlPipe = new HtmlPipeline(hpc, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, htmlPipe);

XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
StringReader sr = new StringReader("<html><head></head><body>" + topMessage.Replace("<br>", "<br></br>") + "</body></html>");
p.Parse(sr);

这是经过多次尝试的有效解决方案:

Here is the working solution after so many attempts:

 string fontPath = Path.Combine(@"fonts\Gaegu-Regular.ttf");
 var fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
 fontProvider.Register(fontPath);            
 CssAppliers ca = new CssAppliersImpl(fontProvider);
 HtmlPipelineContext htmlContext = new HtmlPipelineContext(ca);
 var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));

谢谢.