Unable to Set Font Family in iTextSharp XMLWorker

回眸只為那壹抹淺笑 提交于 2019-12-11 20:23:10

问题


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.

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';
}

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

<body face = 'Arial'>

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

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);

回答1:


I see that you create your CssAppliersImpl instance without using a parameter. If you want to deal with fonts, you should create a ´FontProvider´ implementation and use an instance of that implementation as parameter for the CssAppliersImpl constructor. For instance: create a TestFontProvider class that shows you which font names are needed when parsing your HTML. That will help you understand if the right fonts are registered. If you see that all the fonts that are necessary are registered, the problem may be caused by something else. For instance: maybe the HTML is parsed using the wrong encoding...




回答2:


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)));

Thanks.



来源:https://stackoverflow.com/questions/19553399/unable-to-set-font-family-in-itextsharp-xmlworker

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!