Personalizing PDF Forms in C# and .NET

Formatting the contents of PDF documents is an important task when working with PDF files in C# and .NET. In this article, we will look at how you can fill in and format the contents of PDF documents using the SautinSoft.Pdf .NET library.

Using this SDK, you can easily fill out forms and format PDF documents in C# and .NET by following a few steps.

  1. Add SautinSoft.PDF from NuGet.
  2. Create a new PDF document.
  3. Add text with formatting.
  4. Create a five-pointed star and make the outline red (in the DeviceRGB color space).
  5. Clone a five-pointed star and create a yellow outline (in the DeviceCMYK color space).
  6. Save the document.

Output result:

Полный код

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

class Program
{
    /// <summary>
    /// Filling
    /// </summary>
    /// <remarks>
    /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/pdf-content-formatting-filling.php
    /// </remarks>
    static void Main()
    {
        // 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 page = document.Pages.Add();

            // PdfFormattedText currently supports just Device color spaces (DeviceGray, DeviceRGB, and DeviceCMYK).
            using (var formattedText = new PdfFormattedText())
            {
                formattedText.Font = new PdfFont("Helvetica", 100);

                // Make the text fill black (in DeviceGray color space) and 50% opaque.
                formattedText.Color = PdfColor.FromGray(0);
                // In PDF, opacity is defined separately from the color.
                formattedText.Opacity = 0.5;
                formattedText.Append("Hello world!");

                page.Content.DrawText(formattedText, new PdfPoint(50, 700));
            }

            // Path filled with non-zero winding number rule.
            var path = page.Content.Elements.AddPath();
            var center = new PdfPoint(300, 500);
            double radius = 150, cos1 = Math.Cos(Math.PI / 10), sin1 = Math.Sin(Math.PI / 10), cos2 = Math.Cos(Math.PI / 5), sin2 = Math.Sin(Math.PI / 5);
            // Create a five-point star.
            path.
            BeginSubpath(center.X - sin2 * radius, center.Y - cos2 * radius). // Start from the point in the bottom-left corner.
            LineTo(center.X + cos1 * radius, center.Y + sin1 * radius). // Continue to the point in the upper-right corner.
            LineTo(center.X - cos1 * radius, center.Y + sin1 * radius). // Continue to the point in the upper-left corner.
            LineTo(center.X + sin2 * radius, center.Y - cos2 * radius). // Continue to the point in the bottom-right corner.
            LineTo(center.X, center.Y + radius). // Continue to the point in the upper-center.
            CloseSubpath(); // End with the starting point.
            var format = path.Format;
            format.Fill.IsApplied = true;
            format.Fill.Rule = PdfFillRule.NonzeroWindingNumber;
            // Make the path fill red (in DeviceRGB color space) and 40% opaque.
            format.Fill.Color = PdfColor.FromRgb(1, 0, 0);
            format.Fill.Opacity = 0.4;

            // Path filled with even-odd rule.
            path = page.Content.Elements.AddClone(path);
            path.Subpaths.Transform(PdfMatrix.CreateTranslation(0, -300));
            format = path.Format;
            format.Fill.IsApplied = true;
            format.Fill.Rule = PdfFillRule.EvenOdd;
            // Make the path fill yellow (in DeviceCMYK color space) and 60% opaque.
            format.Fill.Color = PdfColor.FromCmyk(0, 0, 1, 0);
            format.Fill.Opacity = 0.6;

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

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

Download

Option Infer On

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

Friend Class Program
	''' <summary>
	''' Filling
	''' </summary>
	''' <remarks>
	''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/pdf-content-formatting-filling.php
	''' </remarks>
	Shared Sub Main()
		' 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 page = document.Pages.Add()

			' PdfFormattedText currently supports just Device color spaces (DeviceGray, DeviceRGB, and DeviceCMYK).
			Using formattedText = New PdfFormattedText()
				formattedText.Font = New PdfFont("Helvetica", 100)

				' Make the text fill black (in DeviceGray color space) and 50% opaque.
				formattedText.Color = PdfColor.FromGray(0)
				' In PDF, opacity is defined separately from the color.
				formattedText.Opacity = 0.5
				formattedText.Append("Hello world!")

				page.Content.DrawText(formattedText, New PdfPoint(50, 700))
			End Using

			' Path filled with non-zero winding number rule.
			Dim path = page.Content.Elements.AddPath()
			Dim center = New PdfPoint(300, 500)
			Dim radius As Double = 150, cos1 As Double = Math.Cos(Math.PI / 10), sin1 As Double = Math.Sin(Math.PI / 10), cos2 As Double = Math.Cos(Math.PI / 5), sin2 As Double = Math.Sin(Math.PI / 5)
			' Create a five-point star.
			path.BeginSubpath(center.X - sin2 * radius, center.Y - cos2 * radius).LineTo(center.X + cos1 * radius, center.Y + sin1 * radius).LineTo(center.X - cos1 * radius, center.Y + sin1 * radius).LineTo(center.X + sin2 * radius, center.Y - cos2 * radius).LineTo(center.X, center.Y + radius).CloseSubpath() ' End with the starting point.
			Dim format = path.Format
			format.Fill.IsApplied = True
			format.Fill.Rule = PdfFillRule.NonzeroWindingNumber
			' Make the path fill red (in DeviceRGB color space) and 40% opaque.
			format.Fill.Color = PdfColor.FromRgb(1, 0, 0)
			format.Fill.Opacity = 0.4

			' Path filled with even-odd rule.
			path = page.Content.Elements.AddClone(path)
			path.Subpaths.Transform(PdfMatrix.CreateTranslation(0, -300))
			format = path.Format
			format.Fill.IsApplied = True
			format.Fill.Rule = PdfFillRule.EvenOdd
			' Make the path fill yellow (in DeviceCMYK color space) and 60% opaque.
			format.Fill.Color = PdfColor.FromCmyk(0, 0, 1, 0)
			format.Fill.Opacity = 0.6

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

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

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.