PDFsharp draws text under graphics

2019-06-05 17:32发布

问题:

I am using PDFsharp to generate a PDF document from scratch. I am trying to write text on top of a gradient filled rectangle. After generating the document, the gradient appears on top of the text rendering the text completely hidden.

using (var document = new PdfDocument())
{
    var page = document.AddPage();
    var graphics = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
    graphics.SmoothingMode = XSmoothingMode.HighQuality;

    var bounds = new XRect(graphics.PageOrigin, graphics.PageSize);
    graphics.DrawRectangle(
        new XLinearGradientBrush(
            bounds,
            XColor.FromKnownColor(XKnownColor.Red),
            XColor.FromKnownColor(XKnownColor.White),
            XLinearGradientMode.ForwardDiagonal),
        bounds);
    graphics.DrawString(
        "Hello World!",
        new XFont("Arial", 20),
        XBrushes.Black,
        bounds.Center,
        XStringFormats.Center);

    document.Save("test.pdf");
    document.Close();
}

How can I make the text render on top of the rectangle?

I find that any images I draw later will appear on top of the rectangle. It’s only text that hides behind.

回答1:

Try it like this:

using (var document = new PdfDocument())
{
    var page = document.AddPage();
    var graphics = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
    graphics.SmoothingMode = XSmoothingMode.HighQuality;

    var bounds = new XRect(graphics.PageOrigin, graphics.PageSize);
    var state = graphics.Save();
    graphics.DrawRectangle(
        new XLinearGradientBrush(
            bounds,
            XColor.FromKnownColor(XKnownColor.Red),
            XColor.FromKnownColor(XKnownColor.White),
            XLinearGradientMode.ForwardDiagonal),
        bounds);
    graphics.Restore(state);
    graphics.DrawString(
        "Hello World!",
        new XFont("Arial", 20),
        XBrushes.Black,
        bounds.Center,
        XStringFormats.Center);

    document.Save("test.pdf");
    document.Close();
}

Unfortunately, there is a bug in the library's code according to this forum post. The workaround is to Save and Restore the XGraphics object's state between operations.



回答2:

The code given in the first post works fine when using the current version of PDFsharp, 1.50.

The workaround given in the previous answer is needed when PDFsharp version 1.3x or earlier is used.