Skip to main content
.NET Framework 4.5.2+

PdfGraphics Class

Allows you to draw graphics content on a PDF page.

Namespace: DevExpress.Pdf

Assembly: DevExpress.Pdf.v21.2.Drawing.dll

Declaration

public class PdfGraphics :
    PdfDisposableObject

Remarks

Use the PdfGraphics class to draw graphics content on a PDF page. Call the PdfDocumentProcessor.CreateGraphics() method to create a new PdfGraphics object. The PdfGraphics class uses the world coordinate system.

Note

Add a reference to the DevExpress.Pdf.Drawing.v21.2 assembly to use the PdfGraphics class.

The following graphics content is available:

  • Page content
  • Text
  • Image
  • Shape (rectangle, ellipse, polygon, line, Bezier curve, path)
  • Form Field
  • Link

Draw Graphics Content on a Page

Call the following methods to draw graphics content to a page:

PdfGraphics.AddToPageForeground, PdfGraphics.AddToPageBackground
These methods allow you to draw content on an existing page.
PdfDocumentProcessor.RenderNewPage
Draws content on a new page.

Draw Page Content

Call the DrawPageContent method to draw content.

The code sample below scales source content of two document pages and draws these pages in a landscape page.

Draw Two Pages in a Landscape Page

using DevExpress.Pdf;
using System.Drawing;
//...

using (PdfDocumentProcessor processor = new PdfDocumentProcessor()) {
    processor.CreateEmptyDocument();
    PdfPage page = processor.AddNewPage(PdfPaperSize.A4Rotated);
    using (PdfDocumentProcessor processor2 = new PdfDocumentProcessor()) {
        processor2.LoadDocument(@"FirstLook.pdf");

        using (PdfGraphics graphics = processor.CreateGraphics()) {
            graphics.SaveGraphicsState();

            // Obtain the first document page's boundaries.
            PdfRectangle clip = processor2.Document.Pages[0].CropBox;

            // Resize the source page content to fit half of the target page.
            graphics.ScaleTransform((float)((page.CropBox.Width / 2) / clip.Width), (float)((page.CropBox.Width / 2) / clip.Width));

            // Draw the content of the first document page.
            graphics.DrawPageContent(processor2.Document.Pages[0]);
            graphics.RestoreGraphicsState();

            // Define the position to insert the second page content to the target page.
            graphics.SaveGraphicsState();
            graphics.TranslateTransform((float)(page.CropBox.Width / 2), 0);

            // Obtain the second document page's boundaries.
            clip = processor2.Document.Pages[1].CropBox;

            // Resize the source page content to fit half of the target page.
            graphics.ScaleTransform((float)(page.CropBox.Width / clip.Width / 2), (float)(page.CropBox.Width / clip.Width / 2));

            // Draw the content of the second document page.
            graphics.DrawPageContent(processor2.Document.Pages[1]);
            graphics.RestoreGraphicsState();

            // Add graphics content to the target page.
            graphics.AddToPageForeground(page, 72, 72);
        }
        processor.SaveDocument("out2.pdf");
    }
}

Draw Text

Call the DrawString method to add text at the specified page area or point. You can specify the text font, brush and format parameters.

Use the MeasureString method to calculate the size of the drawn text and a point where you can draw text.

The x and y parameters in the DrawString method overloads define the point where the text’s upper-left corner is located. Set the TextOrigin property to Baseline to make the x and y parameters define the point where the start of the text’s baseline is located. Set this property before the DrawString method call.

The code sample below draws text in the center of an empty page:

draw string result

using DevExpress.Pdf;
using System.Drawing;
//...

using (var processor = new PdfDocumentProcessor()) {
    processor.CreateEmptyDocument();
    using (PdfGraphics graphics = processor.CreateGraphics()) {
        // Obtain the first document page
        PdfPage page = processor.AddNewPage(PdfPaperSize.A4);
        PdfRectangle pageSize = page.CropBox;

        // Specify text to draw
        string text = "PDF Document API";
        using (SolidBrush textBrush = new SolidBrush(Color.FromArgb(255, Color.DarkOrange))) {
            using (Font font = new Font("Segoe UI", 20, FontStyle.Regular)) {
                // Calculate text size
                SizeF textSize = graphics.MeasureString(text, font);

                // Calculate a point where to draw text
                PointF textPoint =
                    new PointF((float)((pageSize.Width - textSize.Width) / 2), (float)((pageSize.Height - textSize.Height) / 2));

                // Draw text at the calculated point
                graphics.DrawString(text, font, textBrush, textPoint);

                // Add graphics content to the page foreground
                graphics.AddToPageForeground(page, 72, 72);
            }
        }
    }
    processor.SaveDocument("result.pdf");
}

Draw Image

Call the DrawImage method to add an image to a page.

This method renders an image with its original resolution (DPI). The following formats are available:

  • BMP
  • JPEG
  • PNG
  • EMF
  • EMF+
  • TIFF
  • GIF

The method’s dpiX and dpiY parameters do not affect image quality. They are used to convert world coordinates to page coordinates only.

If you embed a multi-page TIFF image into the document, the PdfGraphics instance draws the active frame only (the default active frame is the first frame). Use the Image.SelectActiveFrame method to select a frame to use. The compression retains for TIFF images with CCITT T.4 or CCITT T.6 compression.

You can use the following properties to reduce the image size and the size of the resulting PDF:

  • ConvertImagesToJpeg - Specifies whether to convert bitmap images into JPEG to reduce the size of the resulting PDF file.
  • JpegImageQuality - Gets or sets the quality of JPEG images in the resulting PDF file.

Tip

The PdfDocumentProcessor caches image data used as the DrawImage method parameter. If you need to draw the same image on multiple pages, you can reuse image data to improve the application performance and reduce the resulting file size.

To draw an image on the PDF page, use one of the following methods:

PdfGraphics.AddToPageForeground, PdfGraphics.AddToPageBackground
These methods allow you to draw content on an existing page.
PdfDocumentProcessor.RenderNewPage
Draws content on a new page.

The code sample below shows how to draw an image in the page center:

image at the center

using DevExpress.Pdf;
using System.Drawing;

using (var processor = new PdfDocumentProcessor()) {
    processor.LoadDocument("Documents//Document.pdf");

    using (PdfGraphics graphics = processor.CreateGraphics()) {
        // Obtain the first document page
        PdfPage page = processor.Document.Pages[0];

        // Specify an image to draw
        using (Image image = Image.FromFile("Documents//DevExpress.png")) {

          // Calculate the image position
          var point = new PointF((float)rect.Center.X-image.Width/2, (float)rect.Center.Y);

          // Draw an image into the calculated area
          graphics.DrawImage(image, point);

          // Add graphics content to the page foreground
          graphics.AddToPageForeground(page, 72, 72);
        }
    }
    processor.SaveDocument("result.pdf");
}

Draw Shapes

The table below lists supported shape types and API used to draw and fill each type.

Shape Type Draw Shape Fill Shape
Rectangle DrawRectangle FillRectangle
Ellipse DrawEllipse FillEllipse
Polygon DrawPolygon FillPolygon
Line DrawLine
DrawLines
No method
Bezier Curve DrawBezier
DrawBeziers
No method
Path DrawPath FillPath

The code sample below draws a rectangle in the specified area of the document page.

Draw a Rectangle

using DevExpress.Pdf;
using System.Drawing;
//...

using (PdfDocumentProcessor processor = new PdfDocumentProcessor()) {
    processor.CreateEmptyDocument();
    PdfPage page = processor.AddNewPage(PdfPaperSize.A4);
    using (PdfGraphics graphics = processor.CreateGraphics()) {

        // Draw a rectangle.
        using (var pen = new Pen(Color.Red, 5))
            graphics.DrawRectangle(pen, new RectangleF(50, 50, 500, 300));

        // Add graphics content to the document page.
        graphics.AddToPageForeground(page, 72, 72);
    }
    processor.SaveDocument("out2.pdf");
}
Process.Start("out.pdf");

Draw a Form Field

Call the AddFormField to draw a form field. The table below lists available form fields and API used to create each type. Pass the required class instance as the AddFormField method parameter.

Form Field Class Method
Check Box PdfGraphicsAcroFormCheckBoxField No method
Combo Box PdfGraphicsAcroFormComboBoxField PdfGraphicsAcroFormField.CreateComboBox
List Box PdfGraphicsAcroFormListBoxField PdfGraphicsAcroFormField.CreateListBox
Radio Group PdfGraphicsAcroFormRadioGroupField PdfGraphicsAcroFormField.CreateRadioGroup
Signature PdfGraphicsAcroFormSignatureField PdfGraphicsAcroFormField.CreateSignature
Text Box PdfGraphicsAcroFormTextBoxField PdfGraphicsAcroFormField.CreateTextBox

This example shows how to use PDF Graphics API to add interactive form fields – text box and radio button group.

View Example

using DevExpress.Pdf;
using System.Drawing;

using (var processor = new PdfDocumentProcessor()) {
    // Create an empty document.
    processor.CreateEmptyDocument("..\\..\\Result.pdf");

    // Create graphics and draw form fields.
    using (PdfGraphics graphics = processor.CreateGraphics()) {
        DrawFormFields(graphics);

        // Render a page with graphics.
        processor.RenderNewPage(PdfPaperSize.Letter, graphics);
    }
}


static void DrawFormFields(PdfGraphics graphics){
    // Create a text box field and specify its location on the page.
    var textBox =
         new PdfGraphicsAcroFormTextBoxField("text box", new RectangleF(30, 10, 200, 30));

    // Specify text and appearance parameters.
    textBox.Text = "Text Box";
    textBox.Appearance.FontSize = 12;
    textBox.Appearance.BackgroundColor = Color.AliceBlue;

    // Add the text box field to graphics.
    graphics.AddFormField(textBox);

    // Create a radio group field.
    var radioGroup =
         new PdfGraphicsAcroFormRadioGroupField("First Group");

    // Add the first radio button to the group and specify its location.
    radioGroup.AddButton("button1", new RectangleF(30, 60, 20, 20));

    // Add the second radio button to the group.
    radioGroup.AddButton("button2", new RectangleF(30, 90, 20, 20));

    // Specify radio group selected index
    radioGroup.SelectedIndex = 0;

    // Specify appearance options:
    radioGroup.Appearance.BorderAppearance =
         new PdfGraphicsAcroFormBorderAppearance()
        {
            Color = Color.Red,
            Width = 3
        };

    // Add the radio group field to graphics.
    graphics.AddFormField(radioGroup);
}

Use the AddLinkToPage or AddLinkToUri method to create a link to a URI or document page, respectively.

This example shows how to create a document with graphics, add a hyperlink and URI to a page.

using DevExpress.Pdf;
using System;
using System.Drawing;
//...
static void Main(string[] args) {
    using (PdfDocumentProcessor processor = new PdfDocumentProcessor()) {
        // Create an empty document.
        processor.CreateEmptyDocument("..\\..\\Result.pdf");

        // Create and draw PDF graphics.
        using (PdfGraphics graph = processor.CreateGraphics()) {

        DrawGraphics(graph);

        // Create a link to a page
        graph.AddLinkToPage(new Rectangle(180, 160, 480, 30), 1, 168, 230);

        // Create a link to URI  
        graph.AddLinkToUri(new Rectangle(110, 350, 180, 15), new Uri("https://www.devexpress.com"));

        // Render a page with graphics.
        processor.RenderNewPage(PdfPaperSize.Letter, graph);
        }
    }
}

static void DrawGraphics(PdfGraphics graph) {

    // Draw text lines on the page. 
    SolidBrush black = (SolidBrush)Brushes.Black;
    using (Font font1 = new Font("Times New Roman", 32, FontStyle.Bold)) {

        graph.DrawString("PDF Document Processor", font1, black, 180, 150);
    }
    using (Font font2 = new Font("Arial", 20)) {

        graph.DrawString("Display, Print and Export PDF Documents", font2, black, 168, 230);
    }
    using (Font font3 = new Font("Arial", 10)) {
        graph.DrawString("The PDF Document Processor is a non-visual component " +
                            "that provides the application programming interface of the PDF Viewer.", font3, black, 16, 300);
        graph.DrawString("Learn more at", font3, black, 20, 350);
        SolidBrush blue = (SolidBrush)Brushes.Blue;
        graph.DrawString("https://www.devexpress.com", font3, blue, 110, 350);
    }
}

Transform Graphics Content

The table below lists available actions with graphics content and API used to perform these actions:

Action Method
Scale graphics content ScaleTransform
Rotate graphics content RotateTransform
Translate the coordinate system origin TranslateTransform
Crop the clip region IntersectClip

The code sample below scales the coordinate system and draws shapes in the initial and scaled coordinate systems.

Scale the Coordinate System

using DevExpress.Pdf;
using System.Drawing;
//...

using (PdfDocumentProcessor processor = new PdfDocumentProcessor()) {
    processor.CreateEmptyDocument();
    PdfPage page = processor.AddNewPage(PdfPaperSize.A4);
        using (PdfGraphics graphics = processor.CreateGraphics()) {
            var rectangle = new RectangleF(0, 0, 300, 300);

            // Draw a blue square.
            using (var brush = new SolidBrush(Color.Blue))
                graphics.FillRectangle(brush, rectangle);

            // Scale the coordinate system.
            graphics.ScaleTransform(0.5f, 0.5f);

            // Draw a red square in the scaled coordinate system.
            using (var brush = new SolidBrush(Color.Red))
                graphics.FillRectangle(brush, rectangle);

            // Add graphics content to the document page.
            graphics.AddToPageForeground(page, 72, 72);
        }
    processor.SaveDocument("out2.pdf");
}
Process.Start("out.pdf");

Save and Restore Graphics State

The graphics state is a data structure that contains the drawing parameters of the PdfGraphics object (the clip region in which graphics are drawn and the transformation matrix). Call the SaveGraphicsState() method to save the current graphics state to the stack.

After you modify the PdfGraphics object’s drawing parameters, call the RestoreGraphicsState paired method to return the parameters to the most recently saved graphics state. This graphics state is removed from the stack when you call the RestoreGraphicsState method.

You can nest calls to the SaveGraphicsState method to save multiple graphics states. Pair each call to the SaveGraphicsState method with the RestoreGraphicsState method.

The following example saves the current graphics state, draws a shape in the translated coordinate system, restores the saved graphics state, and draws another shape in the restored coordinate system.

restore

using DevExpress.Pdf;
using System.Drawing;
//...

using (PdfDocumentProcessor processor = new PdfDocumentProcessor()) {
    processor.CreateEmptyDocument();
    PdfPage page = processor.AddNewPage(PdfPaperSize.A4);
        using (PdfGraphics graphics = processor.CreateGraphics()) {

            // Save the current graphics state (the coordinate system origin is (0, 0)).
            graphics.SaveGraphicsState();

            // Translate the origin of the coordinate system to the point (300, 300).
            graphics.TranslateTransform(300, 300);

            // Draw a blue square in the translated coordinate system.
            using (var brush = new SolidBrush(Color.Blue))
                graphics.FillRectangle(brush, new RectangleF(0, 0, 200, 200));

            // Restore the saved graphics state (the coordinate system origin is (0, 0)).
            graphics.RestoreGraphicsState();

            // Draw a red square in the restored coordinate system.
            using (var brush = new SolidBrush(Color.Red))
                graphics.FillRectangle(brush, new RectangleF(0, 0, 200, 200));

            // Add graphics content to the document page.
            graphics.AddToPageForeground(page, 72, 72);
        }
    processor.SaveDocument("out2.pdf");
}
Process.Start("out.pdf");

The following code snippets (auto-collected from DevExpress Examples) contain references to the PdfGraphics class.

Note

The algorithm used to collect these code examples remains a work in progress. Accordingly, the links and snippets below may produce inaccurate results. If you encounter an issue with code examples below, please use the feedback form on this page to report the issue.

Inheritance

Object
DevExpress.Pdf.Native.PdfDisposableObject
PdfGraphics
See Also