PDFsharp draws text under graphics

风流意气都作罢 提交于 2020-01-02 15:40:47

问题


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.



来源:https://stackoverflow.com/questions/34935268/pdfsharp-draws-text-under-graphics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!