I have the code rendering PDF on the ASP.NET MVC server, but some characters for example e with accent (ě) are not shown correctly. The library I use is itextsharp-LGPL from nuget.
The PDF rendering code is:
protected ActionResult ViewPdf(object model)
{
// http://www.codeproject.com/Articles/66948/Rendering-PDF-views-in-ASP-MVC-using-iTextSharp
// Create the iTextSharp document.
Document doc = new Document();
// Set the document to write to memory.
MemoryStream memStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memStream);
writer.CloseStream = false;
doc.Open();
// Render the view xml to a string, then parse that string into an XML dom.
string xmltext = this.RenderActionResultToString(this.View(model));
XmlDocument xmldoc = new XmlDocument();
xmldoc.InnerXml = xmltext.Trim();
// Parse the XML into the iTextSharp document.
ITextHandler textHandler = new ITextHandler(doc);
textHandler.Parse(xmldoc);
// Close and get the resulted binary data.
doc.Close();
byte[] buf = new byte[memStream.Position];
memStream.Position = 0;
memStream.Read(buf, 0, buf.Length);
// Send the binary data to the browser.
return new BinaryContentResult(buf, "application/pdf");
}
The Helper method of controller look like this:
public class PDFControllerBase : Controller
{
protected string RenderActionResultToString(ActionResult result)
{
// Create memory writer.
var sb = new StringBuilder();
var memWriter = new StringWriter(sb);
// Create fake http context to render the view.
var fakeResponse = new HttpResponse(memWriter);
var fakeContext = new HttpContext(System.Web.HttpContext.Current.Request, fakeResponse);
var fakeControllerContext = new ControllerContext(
new HttpContextWrapper(fakeContext),
this.ControllerContext.RouteData,
this.ControllerContext.Controller);
var oldContext = System.Web.HttpContext.Current;
System.Web.HttpContext.Current = fakeContext;
// Render the view.
result.ExecuteResult(fakeControllerContext);
// Restore data.
System.Web.HttpContext.Current = oldContext;
// Flush memory and return output.
memWriter.Flush();
string content = sb.ToString();
return content;
}
}
The view looks like:
@model MyNamespace.Model.MyModel
@{
Layout = null;
}
<?xml version="1.0" encoding="UTF-8" ?>
<itext creationdate="2/4/2015 5:49:07 pm" producer="iTextSharpXML">
<paragraph leading="18.0" font="arial" size="16.0" align="center">
<chunk>@Model.Title</chunk><newline /><newline />
</paragraph>
<paragraph leading="18.0" font="arial" size="10.0" align="justify">
<chunk>@Model.TextDetail</chunk><newline />
</paragraph>
</itext>
I tried to add following code to PDF rendering, but it does not help:
string arial = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.ttf");
FontFactory.Register(arial, "arial");