I’m generating a PDF file from a string representation of an HTML file, but I can’t set the font for the PDF file. The reason I need that is because I use many icons in my page that come from a font (Font Awesome) which are missing in my generated PDF.
What are the steps to set the right font for each section of the generated PDF? Ideally the generator would use the font-families specified in the css file that I’m loading.
I’m working with ASP.Net. With the following code I can set the font to Roboto for the first TextFragment. I could iterate over all text fragments and set the font, but I want to use different fonts and apply the font-awesome font to my icons. This is my code so far:
string source = ViewRenderer.RenderView("~/Areas/Test/Views/Test/Export_pdf.cshtml", ExportSettings);
byte[] inputBytes = Encoding.UTF8.GetBytes(source);
MemoryStream stream = new MemoryStream(inputBytes);
string dataDir = @"C:\test\fonts\";
var fs = new FolderFontSource(dataDir);
FontRepository.Sources.Add(fs);
Font font = FontRepository.FindFont(@"Roboto", true);
font.FontOptions.NotifyAboutFontEmbeddingError = true;
HtmlLoadOptions options = new HtmlLoadOptions(System.Web.HttpContext.Current.Server.MapPath("~/resrc/css/export/"));
options.PageInfo.Margin.Left = 0;
options.PageInfo.Margin.Right = 0;
options.PageInfo.Width = PageSize.A4.Width;
options.PageInfo.Height = PageSize.A4.Height;
Document doc = new Document(stream, options);
TextFragmentAbsorber absorber = new TextFragmentAbsorber();
doc.Pages[1].Accept(absorber);
absorber.TextFragments[1].TextState.Font = font;
//
PdfSaveOptions saveoptions = new PdfSaveOptions();
saveoptions.DefaultFontName = "Roboto";
//
doc.Save(outputstream, saveoptions);
Response.AddHeader("content-disposition", "attachment; filename =\"" + "Test " + DateTime.Now + ".pdf" + "\"");
Response.Buffer = true;
MemoryStream ms = new MemoryStream(outputstream.ToArray());
ms.WriteTo(Response.OutputStream);
return new FileStreamResult(ms, "application/pdf");