A PDFsharp form is a drawable object composed of graphics, text, images, and other forms. It is similar to the concept of Windows metafiles. Forms are useful when the same group of graphical output is needed in more than one place in a document. Instead of drawing the same shapes several times and thus increasing the size of the output file unnecessarily a form can be used. The content of a form is saved only once in the document and each invocation of the form references the same resources. Note:
This article has nothing to do with the concept of AcroForms which can be filled out.
Forms are represented by the class XForm
is derived from XImage
and is drawn with the DrawImage
Creating a Form
The following code creates a new form:
XForm form = new XForm(document,
To make a form drawable on a particular document the form must be bound to it on its creation. This is why the first parameter is required.
An XGraphics object for drawing the content of the form is created with the following code:
XGraphics formGfx = XGraphics.FromForm(form);
With this graphics object the content of the form is drawn as usual:
formGfx.DrawEllipse(XBrushes.Red, 20, 20, 50, 50);
When finished with the drawing of the content the XGraphics
object should be closed.
Disposing is not strictly required. If you do not dispose the graphics object it is automatically disposed when the form gets used the first time for drawing.
Now the form is ready to be used for drawing in a document.
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
gfx.DrawImage(form, 20, 50); // Draw form like an image
Note that because the form was bound to a document during its creation you can draw the form only on pages of this document.
PDF Form Objects
A specialized form is the derived class XPdfForm
. This form represents a page of an existing PDF document.
XPdfForm pdfForm = XPdfForm.FromFile("MyFile.pdf");
It is not possible to draw on such a form because the underlying document is opened read-only.
By default the form represents the first page of the document specified during initialization. If the document has more than one page the property PageNumber selects the page the form represents:
pdfForm.PageNumber = 7; // one-based page number
object represents one page at any one time, but you can change the page number as often as you like. Drawing operations draw always the currently selected page. Also note that the page number is one-based.
A typical use of XPdfForm
objects is a document that contains background graphics created with applications like Adobe Illustrator or InDesign. You open that document as an XPdfForm
object and draw its pages as the background content of your own document.
In contrast to the class XForm
, objects of type XPdfForm
are not bound to a document when they are created. You can create an XPdfForm
and reuse it for drawing in a series of documents.
The XForms sample
illustrates the use of the XForm