MVCRazorToPdf (iTextSharp) using custom font

2.4k views Asked by At

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

There are 1 answers

1
Chris Haas On BEST ANSWER

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