ststeiger / PdfSharpCore

Port of the PdfSharp library to .NET Core - largely removed GDI+ (only missing GetFontData - which can be replaced with freetype2)
Other
1.08k stars 237 forks source link

Problem with XGraphics and XTextFormatter Draw methods #445

Open debirus opened 5 months ago

debirus commented 5 months ago

I found that after using any Draw method of the XGraphics object it is no longer possible to use the DrawString method of the XTextFormatter on the same object, example:

//-----
XGraphics graf = XGraphics.FromPdfPage(page);
//-----
graf.DrawImage(img, new XRect(x, y, w, h));
//-----
tf = new XTextFormatter(graf);
tf.Alignment = format;
tf.DrawString(text, fontCache.FontChar, fontCache.Brush, rect, XStringFormats.TopLeft);

When I save the PDF at the end, the img is present on the page while the text is not, it cannot be seen even if it is in effect present as text on the document, but remains invisible.

By reversing the order, i.e. using tf.DrawString first and then graf.DrawImage, both img and text can be seen clearly on the final PDF.

The same problem is present after using any graf Draw method.

After several attempts I found a workaround to solve the problem, after using a graf Draw method I recall these instructions:

PdfPage page = graf.PdfPage;
graf.Dispose();
graf = XGraphics.FromPdfPage(page);

Somehow it returns the graf object to its original state while maintaining the changes made to the pdf page