MVCRazorToPdf (iTextSharp) using custom font

本秂侑毒 提交于 2019-12-10 19:37:20

问题


I am trying to add a custom font to my pdf output using the nuget package MVCRazorToPdf but I am having trouble with how to do this as the documentation for iTextSharp isn't great and all seems to be outdated.

The current code I have for creating the pdf is:

return new PdfActionResult(
    "test.cshtml", 
    new TestModel(),
    (writer, document) =>
    {
        FontFactory.Register(HostingEnvironment.MapPath("~/content/fonts/vegur-regular-webfont.ttf"), "VegurRegular");
    });

Where writer is a PdfWriter and document is a Document

All the examples of using the FontFactory show that you need to use the XmlWorker but I don't have access to that, so I was wondering if there was any way to change the documents font using the writer or document?

I've seen that there is the document.HtmlStyleClass property but can't find anything about how to use this anywhere.

Any help with this would be greatly appreciated


回答1:


MVCRazorToPdf is a very, very simple wrapper around iTextSharp's XMLWorker and uses the even simpler XMLWorkerHelper with all defaults to do its work. If you look at the source you'll see this:

                document.Open();


                using (var reader = new StringReader(RenderRazorView(context, viewName)))
                {
                    XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader);

                    document.Close();
                    output = workStream.ToArray();
                }

If you're dead-set on using the NuGet version then you're stuck with this implementation and you're not going to be able to register a custom font.

However, there's an open issue regarding this that includes a fix so if you're willing to compile from source you can apply that change and you should be all set.

If you want to go one step further I'd recommend reading this great post that shows how simple parsing HTML with iTextSharp is as well Bruno's post here that shows how to register fonts.

EDIT

As per the post in the includes a fix link (just in case the link breaks in future), change the above using statement to:

        using (var reader = new MemoryStream(Encoding.UTF8.GetBytes(RenderRazorView(context, viewName))))
        {
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader, null, FontFactory.FontImp as IFontProvider);

            document.Close();
            output = workStream.ToArray();
        }

And then the font factory as registered in the question above will work when using style="font-family:VegurRegular;"



来源:https://stackoverflow.com/questions/34200416/mvcrazortopdf-itextsharp-using-custom-font

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