Customizing PDF Content with Color Spaces in C# and .NET

In modern programming, working with PDF documents is a standard task. One aspect that can significantly improve the perception of a document is the correct use of color. In this article, we will look at how you can improve the PDF format using color spaces in C# and .NET using the SautinSoft.Pdf .Net library.

Color spaces are techniques that allow you to programmatically represent and manipulate colors. Various types of color spaces are supported in PDF, such as DeviceGray, DeviceRGB and DeviceCMYK, as well as CIE-based (CalGray, CalRGB, Lab and ICCBased) and special (Indexed, Separation and DeviceN).

PDF .Net from SautinSoft provides convenient tools for working with colors in PDF documents. Below is an example code that demonstrates the use of different color spaces to style text in a PDF document:

  1. Add SautinSoft.PDF from NuGet.
  2. Create a new PDF document.
  3. Apply three different ways in color spaces: DeviceGray, DeviceRGB and DeviceCMYK.
  4. Add a rectangle with a specific color formatting.
  5. Save the document.

Output result:

Using color spaces in PDF documents allows you to create more attractive and professional-looking documents. SautinSoft.Pdf Library .Net provides developers with powerful tools for working with color, making the process of creating and editing PDF documents more flexible and convenient.

Complete code

using System;
using SautinSoft.Pdf;
using System.IO;
using System.Security.Cryptography;
using SautinSoft.Pdf.Content;
using SautinSoft.Pdf.Objects;
using SautinSoft.Pdf.Content.Colors;
using SautinSoft.Pdf.Text;

class Program
{
    /// <summary>
    /// Work with Color
    /// </summary>
    /// <remarks>
    /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/pdf-content-formatting-color.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", 24);

                // Three different ways to specify gray color in the DeviceGray color space:
                formattedText.Color = PdfColors.Gray;
                formattedText.Append("Hello world! ");
                formattedText.Color = PdfColor.FromGray(0.5);
                formattedText.Append("Hello world! ");
                formattedText.Color = new PdfColor(PdfColorSpace.DeviceGray, 0.5);
                formattedText.AppendLine("Hello world!");

                // Three different ways to specify red color in the DeviceRGB color space:
                formattedText.Color = PdfColors.Red;
                formattedText.Append("Hello world! ");
                formattedText.Color = PdfColor.FromRgb(1, 0, 0);
                formattedText.Append("Hello world! ");
                formattedText.Color = new PdfColor(PdfColorSpace.DeviceRGB, 1, 0, 0);
                formattedText.AppendLine("Hello world!");

                // Three different ways to specify yellow color in the DeviceCMYK color space:
                formattedText.Color = PdfColors.Yellow;
                formattedText.Append("Hello world! ");
                formattedText.Color = PdfColor.FromCmyk(0, 0, 1, 0);
                formattedText.Append("Hello world! ");
                formattedText.Color = new PdfColor(PdfColorSpace.DeviceCMYK, 0, 0, 1, 0);
                formattedText.Append("Hello world!");

                page.Content.DrawText(formattedText, new PdfPoint(100, 500));
            }

            // Create an Indexed color space
            // as specified in Adobe
            // Base color space is DeviceRGB and the created Indexed color space consists of two colors:
            // at index 0: green color (0x00FF00)
            // at index 1: blue color (0x0000FF)
            var indexedColorSpaceArray = PdfArray.Create(4);
            indexedColorSpaceArray.Add(PdfName.Create("Indexed"));
            indexedColorSpaceArray.Add(PdfName.Create("DeviceRGB"));
            indexedColorSpaceArray.Add(PdfInteger.Create(1));
            indexedColorSpaceArray.Add(PdfString.Create("\x00\xFF\x00\x00\x00\xFF", PdfEncoding.Byte, PdfStringForm.Hexadecimal));
            var indexedColorSpace = PdfColorSpace.FromArray(indexedColorSpaceArray);

            // Add a rectangle.
            // Fill it with color at index 0 (green) of the Indexed color space.
            // Stroke it with color at index 1 (blue) of the Indexed color space.
            var path = page.Content.Elements.AddPath();
            path.AddRectangle(100, 300, 200, 100);
            var format = path.Format;
            format.Fill.IsApplied = true;
            format.Fill.Color = new PdfColor(indexedColorSpace, 0);
            format.Stroke.IsApplied = true;
            format.Stroke.Color = new PdfColor(indexedColorSpace, 1);
            format.Stroke.Width = 5;

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

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

Download

Option Infer On

Imports System
Imports SautinSoft.Pdf
Imports System.IO
Imports System.Security.Cryptography
Imports SautinSoft.Pdf.Content
Imports SautinSoft.Pdf.Objects
Imports SautinSoft.Pdf.Content.Colors
Imports SautinSoft.Pdf.Text

Friend Class Program
	''' <summary>
	''' Work with Color
	''' </summary>
	''' <remarks>
	''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/pdf-content-formatting-color.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", 24)

				' Three different ways to specify gray color in the DeviceGray color space:
				formattedText.Color = PdfColors.Gray
				formattedText.Append("Hello world! ")
				formattedText.Color = PdfColor.FromGray(0.5)
				formattedText.Append("Hello world! ")
				formattedText.Color = New PdfColor(PdfColorSpace.DeviceGray, 0.5)
				formattedText.AppendLine("Hello world!")

				' Three different ways to specify red color in the DeviceRGB color space:
				formattedText.Color = PdfColors.Red
				formattedText.Append("Hello world! ")
				formattedText.Color = PdfColor.FromRgb(1, 0, 0)
				formattedText.Append("Hello world! ")
				formattedText.Color = New PdfColor(PdfColorSpace.DeviceRGB, 1, 0, 0)
				formattedText.AppendLine("Hello world!")

				' Three different ways to specify yellow color in the DeviceCMYK color space:
				formattedText.Color = PdfColors.Yellow
				formattedText.Append("Hello world! ")
				formattedText.Color = PdfColor.FromCmyk(0, 0, 1, 0)
				formattedText.Append("Hello world! ")
				formattedText.Color = New PdfColor(PdfColorSpace.DeviceCMYK, 0, 0, 1, 0)
				formattedText.Append("Hello world!")

				page.Content.DrawText(formattedText, New PdfPoint(100, 500))
			End Using

			' Create an Indexed color space
			' as specified in Adobe
			' Base color space is DeviceRGB and the created Indexed color space consists of two colors:
			' at index 0: green color (0x00FF00)
			' at index 1: blue color (0x0000FF)
			Dim indexedColorSpaceArray = PdfArray.Create(4)
			indexedColorSpaceArray.Add(PdfName.Create("Indexed"))
			indexedColorSpaceArray.Add(PdfName.Create("DeviceRGB"))
			indexedColorSpaceArray.Add(PdfInteger.Create(1))
			indexedColorSpaceArray.Add(PdfString.Create(ChrW(&H00).ToString() & ChrW(&HFF).ToString() & ChrW(&H00).ToString() & ChrW(&H00).ToString() & ChrW(&H00).ToString() & ChrW(&HFF).ToString(), PdfEncoding.Byte, PdfStringForm.Hexadecimal))
			Dim indexedColorSpace = PdfColorSpace.FromArray(indexedColorSpaceArray)

			' Add a rectangle.
			' Fill it with color at index 0 (green) of the Indexed color space.
			' Stroke it with color at index 1 (blue) of the Indexed color space.
			Dim path = page.Content.Elements.AddPath()
			path.AddRectangle(100, 300, 200, 100)
			Dim format = path.Format
			format.Fill.IsApplied = True
			format.Fill.Color = New PdfColor(indexedColorSpace, 0)
			format.Stroke.IsApplied = True
			format.Stroke.Color = New PdfColor(indexedColorSpace, 1)
			format.Stroke.Width = 5

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

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

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.