user2638817
user2638817

Reputation: 95

Display Unicode characters in PDF using MigraDoc DocumentRenderer

I'm trying to use Unicode characters in my PDF generator. I first create main layout for pages with PDFsharp (like watermarks and shapes on every page) and then try to add text with MigraDoc. While in PDFsharp everything goes well with fonts and the code works fine, MigraDoc creates empty characters. The simplyfied code looks like so:

//with PDFsharp
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();

XGraphics gfx = XGraphics.FromPdfPage(page);
string s = "ĄŻŹĆĘŁÓążźęćłó";
XFont font16 = new XFont("Calibri", 16, XFontStyle.Regular);
gfx.DrawString(s, font16, XBrushes.Black, 70, 50, XStringFormats.Default);

//with MigraDoc
Document doc = new Document();
Section sec = doc.AddSection();
Paragraph para = sec.AddParagraph();
para.Format.Font.Name = "Calibri";
para.Format.Font.Size = 16;
para.AddText(s);

MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
docRenderer.PrepareDocument();
docRenderer.RenderPage(gfx, 1);
//

document.Save("test.pdf");
Process.Start("test.pdf");

I tried different fonts and it gave me nothing.

Upvotes: 2

Views: 2845

Answers (1)

Try setting gfx.MUH = PdfFontEncoding.Unicode; for the gfx before invoking any MigraDoc code.

A note for beginners reading here: Life is simpler if you use PdfDocumentRenderer:
https://stackoverflow.com/a/48192026/162529
You can use images or PDF pages as page backgrounds using MigraDoc features only without having to mix MigraDoc and PDFsharp.

DocumentRenderer allows to mix PDFsharp and MigraDoc - to achieve functionality that goes beyond the capabilities of MigraDoc alone. In this case you have to use the MigraDoc Unicode Hack MUH shown above to enable Unicode support. The MUH is also used in the official mixing sample on the PDFsharp site:
http://www.pdfsharp.net/wiki/MixMigraDocAndPdfSharp-sample.ashx It is also used in this sample published on the PDFsharp forum:
http://forum.pdfsharp.net/viewtopic.php?f=8&t=3172

Upvotes: 3

Related Questions