PDF Form XObjects Creation in C# and .NET

PDF Form XObjects are a powerful feature in the PDF specification that allows developers to create reusable content streams. These streams can be drawn multiple times within a PDF document, which is particularly useful for complex graphics, repeated elements, and templates. In this article, we will explore how to develop PDF Form XObjects using C# and the .NET framework, leveraging the capabilities of the SautinSoft PDF.Net library.

PDF Form XObjects are self-contained descriptions of a sequence of PDF content elements, such as text, images, and shapes. They can be thought of as vector-based images that can be reused multiple times within a PDF document. This not only reduces the file size but also simplifies the process of creating complex documents with repeated elements.

See the example below for how to create a form XObject, enter its contents, and draw it in multiple locations on the same PDF page using different fill colors each time:

  1. Add SautinSoft.PDF from NuGet.
  2. Create a new PDf document.
  3. Draw the formatted text at location (50, 150) from the bottom-left corner of the group/from and add the text with a black fill 50 points below the first text.
  4. Add a rectangle path with the default fill and add the same path with a black fill 50 points below the first path.
  5. Add the contents of an external Pdf form with black, green and red fills.
  6. Save the document.

Output result:

Complete code

using System;
using System.IO;
using SautinSoft;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Content;

namespace Sample
{
    class Sample
    {
        /// <summary>
        /// Form Xobjects.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/form-xobjects.php
        /// </remarks>
        static void Main(string[] args)
        {
            // Before starting this example, please get a free 100-day trial key:
            // https://sautinsoft.com/start-for-free/

            // Apply the key here:
            // PdfDocument.SetLicense("...");

            using (var document = new PdfDocument())
            {
                var form = new PdfForm(document, new PdfSize(200, 200));

                form.Content.BeginEdit();

                var textGroup = form.Content.Elements.AddGroup();

                // Add text with the default fill (fill will be inherited from outer PdfFormContent).
                using (var formattedText = new PdfFormattedText())
                {
                    formattedText.Font = new PdfFont("Helvetica", 24);
                    formattedText.Append("Hello world!");

                    // Draw the formatted text at location (50, 150) from the bottom-left corner of the group/form.
                    textGroup.DrawText(formattedText, new PdfPoint(50, 150));
                }

                // Add the same text with a black fill 50 points below the first text.
                var blackText = (PdfTextContent)textGroup.Elements.AddClone(textGroup.Elements.First);
                blackText.TextTransform = PdfMatrix.CreateTranslation(0, -50) * blackText.TextTransform;
                blackText.Format.Fill.Color = PdfColors.Black;

                var pathGroup = form.Content.Elements.AddGroup();

                // Add a rectangle path with the default fill (fill will be inherited from the outer PdfFormContent).
                var path = pathGroup.Elements.AddPath();
                path.AddRectangle(0, 50, 200, 40);
                path.Format.Fill.IsApplied = true;

                // Add the same path with a black fill 50 points below the first path.
                var blackPath = pathGroup.Elements.AddClone(path);
                blackPath.Subpaths.Transform(PdfMatrix.CreateTranslation(0, -50));
                blackPath.Format.Fill.Color = PdfColors.Black;

                form.Content.EndEdit();

                var page = document.Pages.Add();

                // Add the outer PdfFormContent with the default (black) fill.
                // Elements in the inner PdfForm that do not have a fill set, will have the default (black) fill.
                var contentGroup = page.Content.Elements.AddGroup();
                var formContent1 = contentGroup.Elements.AddForm(form);
                formContent1.Transform = PdfMatrix.CreateTranslation(100, 600);

                // Add the outer PdfFormContent with a green fill.
                // Elements in the inner PdfForm that do not have a fill set, will have a green fill.
                contentGroup = page.Content.Elements.AddGroup();
                var formContent2 = contentGroup.Elements.AddForm(form);
                formContent2.Transform = PdfMatrix.CreateTranslation(100, 350);
                formContent2.Format.Fill.Color = PdfColors.Green;

                // Add the outer PdfFormContent with a red fill.
                // Elements in the inner PdfForm that do not have a fill set, will have a red fill.
                contentGroup = page.Content.Elements.AddGroup();
                var formContent3 = contentGroup.Elements.AddClone(formContent1);
                formContent3.Transform = PdfMatrix.CreateTranslation(100, 100);
                formContent3.Format.Fill.Color = PdfColors.Red;

                document.Save("FormXObjects.pdf");
            }

            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("FormXObjects.pdf") { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.IO
Imports SautinSoft
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Content

Namespace Sample
	Friend Class Sample
		''' <summary>
		''' Form Xobjects.
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/form-xobjects.php
		''' </remarks>
		Shared Sub Main(ByVal args() As String)
			' Before starting this example, please get a free 100-day trial key:
			' https://sautinsoft.com/start-for-free/

			' Apply the key here:
			' PdfDocument.SetLicense("...");

			Using document = New PdfDocument()
				Dim form = New PdfForm(document, New PdfSize(200, 200))

				form.Content.BeginEdit()

				Dim textGroup = form.Content.Elements.AddGroup()

				' Add text with the default fill (fill will be inherited from outer PdfFormContent).
				Using formattedText = New PdfFormattedText()
					formattedText.Font = New PdfFont("Helvetica", 24)
					formattedText.Append("Hello world!")

					' Draw the formatted text at location (50, 150) from the bottom-left corner of the group/form.
					textGroup.DrawText(formattedText, New PdfPoint(50, 150))
				End Using

				' Add the same text with a black fill 50 points below the first text.
				Dim blackText = CType(textGroup.Elements.AddClone(textGroup.Elements.First), PdfTextContent)
				blackText.TextTransform = PdfMatrix.CreateTranslation(0, -50) * blackText.TextTransform
				blackText.Format.Fill.Color = PdfColors.Black

				Dim pathGroup = form.Content.Elements.AddGroup()

				' Add a rectangle path with the default fill (fill will be inherited from the outer PdfFormContent).
				Dim path = pathGroup.Elements.AddPath()
				path.AddRectangle(0, 50, 200, 40)
				path.Format.Fill.IsApplied = True

				' Add the same path with a black fill 50 points below the first path.
				Dim blackPath = pathGroup.Elements.AddClone(path)
				blackPath.Subpaths.Transform(PdfMatrix.CreateTranslation(0, -50))
				blackPath.Format.Fill.Color = PdfColors.Black

				form.Content.EndEdit()

				Dim page = document.Pages.Add()

				' Add the outer PdfFormContent with the default (black) fill.
				' Elements in the inner PdfForm that do not have a fill set, will have the default (black) fill.
				Dim contentGroup = page.Content.Elements.AddGroup()
				Dim formContent1 = contentGroup.Elements.AddForm(form)
				formContent1.Transform = PdfMatrix.CreateTranslation(100, 600)

				' Add the outer PdfFormContent with a green fill.
				' Elements in the inner PdfForm that do not have a fill set, will have a green fill.
				contentGroup = page.Content.Elements.AddGroup()
				Dim formContent2 = contentGroup.Elements.AddForm(form)
				formContent2.Transform = PdfMatrix.CreateTranslation(100, 350)
				formContent2.Format.Fill.Color = PdfColors.Green

				' Add the outer PdfFormContent with a red fill.
				' Elements in the inner PdfForm that do not have a fill set, will have a red fill.
				contentGroup = page.Content.Elements.AddGroup()
				Dim formContent3 = contentGroup.Elements.AddClone(formContent1)
				formContent3.Transform = PdfMatrix.CreateTranslation(100, 100)
				formContent3.Format.Fill.Color = PdfColors.Red

				document.Save("FormXObjects.pdf")
			End Using

			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo("FormXObjects.pdf") With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.