Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position and center text in PDFsharp?

Tags:

c#

pdfsharp

I need the "Job Setup Sheet" centered under the Heading. How should that be done?

Here is 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);
like image 845
texas697 Avatar asked Sep 17 '14 03:09

texas697


1 Answers

The XRect you pass to DrawString always covers the whole page. By providing the correct top and/or bottom position with the rect, 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);
}
like image 179
I liked the old Stack Overflow Avatar answered Oct 04 '22 21:10

I liked the old Stack Overflow