PDFsharp: First Steps

Modified on 2009/08/12 12:05 by Thomas Hövel — Categorized as: Articles, PDFsharp Articles

Both PDFsharp and MigraDoc provide a lot of AddXxx functions. Typically these functions return the newly created objects. Once you’ve learned the basic principles it’s quite easy to work with. Intellisense helps a lot then. And the new help system that integrates with the Visual Studio online help will provide information about any class in PDFsharp and MigraDoc – simply by hitting F1.

PDFsharp - Getting Started

A good place to start is the Samples folder that comes with the source code. This wiki also shows the PDFsharp Samples.

We’ll discuss a few lines of the Hello World sample here.

You’ll need a PDF document:
PdfDocument document = new PdfDocument();
And you need a page:
PdfPage page = document.AddPage();
Drawing is done with an XGraphics object:
XGraphics gfx = XGraphics.FromPdfPage(page);
Then you'll create a font:
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
And you use that font to draw a string:
gfx.DrawString("Hello, World!", font, XBrushes.Black,
  new XRect(0, 0, page.Width, page.Height),
  XStringFormat.Center);
When drawing is done, write the file:
string filename = "HelloWorld.pdf";
document.Save(filename);
A PC application might show the file:
Process.Start(filename);
A web application would return the PDF file in an HTTP response. Look at our web samples how to do this.

The Hello World sample is also available as an Visual Basic sample.

See also: PDFsharp Samples