How to position and center text in PDFsharp?

I want a "Job Setup Sheet" in the center under the heading. How should this be done?

Here's what I tried:

// Create an empty page
PdfPage page = document.AddPage();
page.Size = PageSize.Letter;
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);

//XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode,
                                                PdfFontEmbedding.Always);

// Create a font
XFont HeadingFont = new XFont("Times New Roman", 20, XFontStyle.Bold);
XFont BodyFont = new XFont("Times New Roman", 12);
// Draw the text
gfx.DrawString("Texas Exterior Systems", HeadingFont, XBrushes.Black,
  new XRect(0, 0, page.Width, page.Height),
  XStringFormats.TopCenter);

gfx.DrawString("Job Setup Sheet", BodyFont, XBrushes.Black,
  new XRect(0, 0, page.Width, page.Height),
  XStringFormats.Center);

      

+3


source to share


1 answer


The XRect you pass to DrawString always spans the entire page. By providing the correct top and / or bottom position with a rectangle, the text can be drawn at that position.

Sample code can be found here :



void DrawText(XGraphics gfx, int number)
{
    BeginBox(gfx, number, "Text Styles");

    const string facename = "Times New Roman";

    //XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
    XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.WinAnsi, PdfFontEmbedding.Default);

    XFont fontRegular = new XFont(facename, 20, XFontStyle.Regular, options);
    XFont fontBold = new XFont(facename, 20, XFontStyle.Bold, options);
    XFont fontItalic = new XFont(facename, 20, XFontStyle.Italic, options);
    XFont fontBoldItalic = new XFont(facename, 20, XFontStyle.BoldItalic, options);

    // The default alignment is baseline left (that differs from GDI+)
    gfx.DrawString("Times (regular)", fontRegular, XBrushes.DarkSlateGray, 0, 30);
    gfx.DrawString("Times (bold)", fontBold, XBrushes.DarkSlateGray, 0, 65);
    gfx.DrawString("Times (italic)", fontItalic, XBrushes.DarkSlateGray, 0, 100);
    gfx.DrawString("Times (bold italic)", fontBoldItalic, XBrushes.DarkSlateGray, 0, 135);

    EndBox(gfx);
}

      

+4


source







All Articles