How to add shapes to PDF on WPF applications

We often use shape to the PDF file to make it obvious and show the data clearly. With Spire.PDF for WPF, developers can easily use the object Spire.Pdf.PdfPageBase.Canvas to add different kind of shapes, such as rectangle, circle and Ellipse, etc. This article will demonstrate how to add shapes to PDF in C# on WPF applications.

Note: Before Start, please download the latest version of Spire.PDF and add Spire.Pdf.Wpf.dll in the bin folder as the reference of Visual Studio.

Here comes to the steps of how to add shapes to PDF file in C#:

Step 1: Create a new PDF document and add a page to it.

PdfDocument pdfDoc = new PdfDocument();
PdfPageBase page = pdfDoc.Pages.Add();

Step 2: Save graphics state.

PdfGraphicsState state = page.Canvas.Save();

Step 3: Set the color for the shapes.

PdfPen pen = new PdfPen(System.Drawing.Color.ForestGreen, 0.1f);
PdfPen pen1 = new PdfPen(System.Drawing.Color.Red, 3f);
PdfBrush brush = new PdfSolidBrush(System.Drawing.Color.DeepSkyBlue);

Step 4: Draw shapes and set the position for them.

page.Canvas.DrawRectangle(pen, new System.Drawing.Rectangle(new System.Drawing.Point(2, 22), new System.Drawing.Size(120, 120)));
page.Canvas.DrawPie(pen1, 150, 30, 100, 90, 360, 360);
page.Canvas.DrawEllipse(brush, 350, 40, 20, 60);

Step 5: Restore graphics.

page.Canvas.Restore(state);

Step 6: Save the PDF document to file.

pdfDoc.SaveToFile("Shapes.pdf");

Effective screenshots of the adding shapes to PDF file:

How to add shapes to PDF on WPF applications

Full codes:

private void button1_Click(object sender, RoutedEventArgs e)
{
    PdfDocument pdfDoc = new PdfDocument();
    PdfPageBase page = pdfDoc.Pages.Add();
    PdfGraphicsState state = page.Canvas.Save();
    PdfPen pen = new PdfPen(System.Drawing.Color.ForestGreen, 0.1f);
    PdfPen pen1 = new PdfPen(System.Drawing.Color.Red, 3f);
    PdfBrush brush = new PdfSolidBrush(System.Drawing.Color.DeepSkyBlue);

    //draw rectangle
    page.Canvas.DrawRectangle(pen, new System.Drawing.Rectangle(new System.Drawing.Point(2, 22), new System.Drawing.Size(120, 120)));
    //draw circle
    page.Canvas.DrawPie(pen1, 150, 30, 100, 90, 360, 360);
    //draw ellipse
    page.Canvas.DrawEllipse(brush, 350, 40, 20, 60);
    
    page.Canvas.Restore(state);
    pdfDoc.SaveToFile("Shapes.pdf");
}