I'm trying to add a custom font (otf file or for testing purpose ttf) to my PDF document to render text page objects with. The rendered text is always the same gibberish like ÿÿÿÿÿÿe
('e' might be the last char of my string or a random character). Creating, rendering and adding other objects like paths or images are working fine. So I'm guessing the font isn't loaded correctly.
I'm using an updated version of the C# wrapper PDFiumSharp ( https://github.com/ArgusMagnus/PDFiumSharp ), which provides the following methods: FPDFText_LoadFont(document, FontType, IsCid, byte[] fontData)
and FPDFPageObj_CreateTextObj(document, FPDF_Font font, size)
. The wiki of PDFiumSharp states that through LoadFont
the font is loaded into the document. The code snippet following runs through without problems (so fontpath is correct, can be loaded and the text object can be created).
I exchanged the pdfium.dll with the newest one from https://github.com/bblanchon/pdfium-binaries, which includes the entry point FPDF_LoadFont too.
There is also another entry point FPDF_InitLibraryWithConfig
, which gets a FPDF_LIBRARY_CONFIG
as argument. This config holds a readonly field IntPtr _userFontPaths
, which might me usable somehow, but I haven't find a way to set this.
public void AddText(int pageIndex, string text, int posX, int posY, float scale, string fontPath)
{
if (string.IsNullOrEmpty(fontPath)) return;
// load default font, if not already loaded
try
{
byte[] fontData = File.ReadAllBytes(fontPath);
_font = PDFium.FPDFText_LoadFont(_document.Handle, FontTypes.TrueType, false, fontData);
}
catch (Exception e)
{
return;
}
FPDF_PAGEOBJECT obj = PDFium.FPDFPageObj_CreateTextObj(_document.Handle,
_font,
12.0f * scale);
/* Matrix: | a, c, e| ==> | width, 0, offsetX|
* | b, d, f| | 0, height, offsetY|*/
PDFium.FPDFPageObj_Transform(obj, 1, 0, 0, 1, posX, posY);
PDFium.FPDFText_SetText(obj, text);
PDFium.FPDFPage_InsertObject(_document.Pages[pageIndex].Handle, ref obj);
}
Calling it with:
AddText(0, "Hello Snape", 10, 50, 1, @"C:\SomeFont.ttf");
The rendered result in some PDF viewers is like this: ÿÿÿÿÿÿÿÿe
or (some spaces) e
(though you can not see the spaces of course) or empty. My expected result is Hello Snape
. The transformation is okay, as the wrong texts are displayed at the wanted position.
Edit:
After updating the wrapper, so that FPDFPageObj_CreateTextObj
takes the FPDF_FONT
instead of the font name as string, the text is displayed with the correct font. The gibberish remains.(Updated code)
Ok, the problem was again in the wrapper:
The function bool FPDFText_SetText(FPDF_PAGEOBJECT text_object, [MarshalAs(UnmanagedType.LPStr)] string text)
needed a LPStr
. Changing it to LPWStr
did the trick.