Enhancing PDF Functionality with Basic Object Manipulation in C# and .NET

PDF documents are a staple in digital communication, offering a reliable format for sharing information across various platforms. However, to fully leverage the power of PDFs, developers often need to go beyond basic creation and manipulation. This is where basic object manipulation in C# and .NET comes into play, allowing for advanced PDF functionalities. In this article, we will explore how to enhance PDF functionality using basic objects with the help of SautinSoft's PDF.Net library.

The PDF Objects supported by SautinSoft.Pdf are:

  • Null
  • PdfBoolean
  • PdfInteger and PdfNumber
  • PdfName
  • PdfString
  • PdfArray
  • PdfDictionary
  • PdfStream

The following example shows how you can use a page-piece dictionary to hold private application data.

  1. Add SautinSoft.PDF from NuGet.
  2. Load a PDF document.
  3. Get document's trailer dictionary and document catalog dictionary from the trailer.
  4. Either retrieve "PieceInfo" entry value from document catalog or create a page-piece dictionary and set it to document catalog under "PieceInfo" entry.
  5. Create page-piece data dictionary for "SautinSoft.Pdf" conforming product and set it to page-piece dictionary.
  6. Create a private data dictionary that will hold private data that "SautinSoft.Pdf" conforming product understands.
  7. Set "Title" and "Version" entries to private data.
  8. Specify date of the last modification of "SautinSoft.Pdf" private data (required by PDF specification).
  9. Save the document.

Output result:

Полный код

using System;
using System.Globalization;
using System.IO;
using SautinSoft;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Content;
using SautinSoft.Pdf.Objects;
using SautinSoft.Pdf.Text;

namespace Sample
{
    class Sample
    {
        /// <summary>
        /// Use basic PDF objects for currently unsupported PDF features.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/basic-objects.php
        /// </remarks>
        static void Main(string[] args)
        {
            string pdfFile = Path.GetFullPath(@"..\..\..\simple text.pdf");

            using (var document = PdfDocument.Load(pdfFile))
            {
                // Get document's trailer dictionary.
                var trailer = document.GetDictionary();
                // Get document catalog dictionary from the trailer.
                var catalog = (PdfDictionary)((PdfIndirectObject)trailer[PdfName.Create("Root")]).Value;

                // Either retrieve "PieceInfo" entry value from document catalog or create a page-piece dictionary and set it to document catalog under "PieceInfo" entry.
                PdfDictionary pieceInfo;
                var pieceInfoKey = PdfName.Create("PieceInfo");
                var pieceInfoValue = catalog[pieceInfoKey];
                switch (pieceInfoValue.ObjectType)
                {
                    case PdfBasicObjectType.Dictionary:
                        pieceInfo = (PdfDictionary)pieceInfoValue;
                        break;
                    case PdfBasicObjectType.IndirectObject:
                        pieceInfo = (PdfDictionary)((PdfIndirectObject)pieceInfoValue).Value;
                        break;
                    case PdfBasicObjectType.Null:
                        pieceInfo = PdfDictionary.Create();
                        catalog[pieceInfoKey] = PdfIndirectObject.Create(pieceInfo);
                        break;
                    default:
                        throw new InvalidOperationException("PieceInfo entry must be dictionary.");
                }

                // Create page-piece data dictionary for "SautinSoft.Pdf" conforming product and set it to page-piece dictionary.
                var data = PdfDictionary.Create();
                pieceInfo[PdfName.Create("SautinSoft.Pdf")] = data;

                // Create a private data dictionary that will hold private data that "SautinSoft.Pdf" conforming product understands.
                var privateData = PdfDictionary.Create();
                data[PdfName.Create("Data")] = privateData;

                // Set "Title" and "Version" entries to private data.
                privateData[PdfName.Create("Title")] = PdfString.Create("SautinSoft PDF. Document");
                privateData[PdfName.Create("Version")] = PdfString.Create("The latest version");

                // Specify date of the last modification of "SautinSoft.Pdf" private data (required by PDF specification).
                data[PdfName.Create("LastModified")] = PdfString.Create(DateTimeOffset.Now);

                document.Save("Basic Objects.pdf");
            }

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

Download

Option Infer On

Imports System
Imports System.Globalization
Imports System.IO
Imports SautinSoft
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Content
Imports SautinSoft.Pdf.Objects
Imports SautinSoft.Pdf.Text

Namespace Sample
	Friend Class Sample
		''' <summary>
		''' Use basic PDF objects for currently unsupported PDF features.
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/basic-objects.php
		''' </remarks>
		Shared Sub Main(ByVal args() As String)
			Dim pdfFile As String = Path.GetFullPath("..\..\..\simple text.pdf")

			Using document = PdfDocument.Load(pdfFile)
				' Get document's trailer dictionary.
				Dim trailer = document.GetDictionary()
				' Get document catalog dictionary from the trailer.
				Dim catalog = CType(CType(trailer(PdfName.Create("Root")), PdfIndirectObject).Value, PdfDictionary)

				' Either retrieve "PieceInfo" entry value from document catalog or create a page-piece dictionary and set it to document catalog under "PieceInfo" entry.
				Dim pieceInfo As PdfDictionary
				Dim pieceInfoKey = PdfName.Create("PieceInfo")
				Dim pieceInfoValue = catalog(pieceInfoKey)
				Select Case pieceInfoValue.ObjectType
					Case PdfBasicObjectType.Dictionary
						pieceInfo = CType(pieceInfoValue, PdfDictionary)
					Case PdfBasicObjectType.IndirectObject
						pieceInfo = CType(CType(pieceInfoValue, PdfIndirectObject).Value, PdfDictionary)
					Case PdfBasicObjectType.Null
						pieceInfo = PdfDictionary.Create()
						catalog(pieceInfoKey) = PdfIndirectObject.Create(pieceInfo)
					Case Else
						Throw New InvalidOperationException("PieceInfo entry must be dictionary.")
				End Select

				' Create page-piece data dictionary for "SautinSoft.Pdf" conforming product and set it to page-piece dictionary.
				Dim data = PdfDictionary.Create()
				pieceInfo(PdfName.Create("SautinSoft.Pdf")) = data

				' Create a private data dictionary that will hold private data that "SautinSoft.Pdf" conforming product understands.
				Dim privateData = PdfDictionary.Create()
				data(PdfName.Create("Data")) = privateData

				' Set "Title" and "Version" entries to private data.
				privateData(PdfName.Create("Title")) = PdfString.Create("SautinSoft PDF. Document")
				privateData(PdfName.Create("Version")) = PdfString.Create("The latest version")

				' Specify date of the last modification of "SautinSoft.Pdf" private data (required by PDF specification).
				data(PdfName.Create("LastModified")) = PdfString.Create(DateTimeOffset.Now)

				document.Save("Basic Objects.pdf")
			End Using

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

Download


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



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

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