Robar
Robar

Reputation: 1971

Changing text color in PdfSharp

I'm currently creating a PDF with PdfSharp which mostly consists of text and some images. The text elements have different colors. My problem is that as soon as I use a different color than the color I started with, the text is not visible in the resulting PDF (e.g. I start with black text, switch to a red text, the red text is not visible). All text elements are in the resulting PDF (I can select them), but the red elements are invisible.

So here is the code:

// Create a new PDF document with one page
var document = new PdfDocument();
var page = document.AddPage();
page.Width = 800;
page.Height = 600;
var defaultFont = new XFont("Arial", 12, XFontStyle.Regular, new XPdfFontOptions(PdfFontEmbedding.Always));
var gfx = XGraphics.FromPdfPage(page);

// black text
gfx.DrawString("black", defaultFont, XBrushes.Black, new XRect(x, y, width, height), XStringFormats.Center);

// red text
gfx.DrawString("red", defaultFont, XBrushes.Red, new XRect(x2, y2, width2, height2), XStringFormats.Center);

I've already found a solution (re-creating the XGraphics object) but it's quiete messy because it needs to be called after each color change:

// ...

// black text
gfx.DrawString("black", defaultFont, XBrushes.Black, new XRect(x, y, width, height), XStringFormats.Center);

// disposing the old graphics context and creating a new one seems to help
gfx.Dispose();
gfx = XGraphics.FromPdfPage(page);

// red text
gfx.DrawString("red", defaultFont, XBrushes.Red, new XRect(x2, y2, width2, height2), XStringFormats.Center);

I guess there is a better solution, but I couldn't find one yet.

Edit

As suggested in this answer, I wanted to create a SSCCE. During the creation I found the actual bug. Instead of XBrushes.Red I used an own defined XBrush, but didn't mention it in the above code snippet, because I thought it was unnecessary.

Upvotes: 7

Views: 13440

Answers (2)

Robar
Robar

Reputation: 1971

As already mentioned in the last section of the question, I used an own defined brush instead of XBrushes.Red.

I defined it the following way:

XBrush redBrush = new XSolidBrush(new XColor {R = 207, G = 0, B = 44});

This way the brush only worked after I disposed the graphics object and created a new one. But after some googling I found the correct way to define a brush:

XBrush redBrush = new XSolidBrush(XColor.FromArgb(207, 0, 44));

Upvotes: 21

I tried to replicate your problem using your code snippet and PDFsharp version 1.32. I used VS Express 2013 which automatically converted all projects to .NET 4.5.

I tried both builds (GDI+ and WPF) and all colours worked fine for me.

So instead of just a code snippet you should provide an SSCCE.

See also:
http://forum.pdfsharp.net/viewtopic.php?p=2094#p2094

Upvotes: 1

Related Questions