Document Linking in C# and .NET for PDF Objects

In modern document processing, association additional files to PDF objects is a powerful feature that enhances the usability and functionality of PDF documents. Using the Sautinsoft PDF.NET library Developers can easily link files to PDF objects, ensuring smooth integration of additional data such as spreadsheets, images, or other documents. In this article, we will tell you about the process of binding files to PDF objects using C# and .NET.

Mapping files to PDF objects allows you to:

  • Insert additional data directly into the PDF document.
  • Provide additional context or resources such as source files, diagrams, or related documents.
  • Enhance the interactivity and usability of documents.

Step-by-step guide:

  1. Add SautinSoft.PDF from NuGet.
  2. Create an empty document.
  3. Load the contents of the first page from the 'simple text.pdf' file.
  4. Load the contents of the first page from the 'chart.pdf' file.
  5. Add the 'Chart.xlsx', 'simple text.docx', 'ChartData.csv' files as an attachment to the final document.
  6. Save the document.

Input file:

associate files input

Intermediate file:

associate intermediate file

Output result:

associate files output

Complete code

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

class Program
{
    /// <summary>
    /// Associate Files.
    /// </summary>
    /// <remarks>
    /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/associate-files.php
    /// </remarks>
    static void Main()
    {
        // Before starting this example, please get a free trial key:
        // https://sautinsoft.com/start-for-free/

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

        using (var document = new PdfDocument())
        {
            // Make Attachments panel visible.
            document.PageMode = PdfPageMode.UseAttachments;

            using (var sourceDocument = PdfDocument.Load(Path.GetFullPath(@"..\..\..\simple text.pdf")))
            {
                // Import the first page of an 'Simple Text.pdf' document.
                var page = document.Pages.AddClone(sourceDocument.Pages[0]);

                // Associate the 'Simple Text.docx' file to the imported page as a source file and also add it to the document's embedded files.
                page.AssociatedFiles.Add(PdfAssociatedFileRelationshipType.Source, Path.GetFullPath(@"..\..\..\simple text.docx"), null, document.EmbeddedFiles);
            }

            using (var sourceDocument = PdfDocument.Load(Path.GetFullPath(@"..\..\..\Chart.pdf")))
            {
                // Import the first page of a 'Chart.pdf' document.
                var page = document.Pages.AddClone(sourceDocument.Pages[0]);

                // Group the content of an imported page and mark it with the 'AF' tag.
                var chartContentGroup = page.Content.Elements.Group(page.Content.Elements.First, page.Content.Elements.Last);
                var markStart = chartContentGroup.Elements.AddMarkStart(new PdfContentMarkTag(PdfContentMarkTagRole.AF), chartContentGroup.Elements.First);
                chartContentGroup.Elements.AddMarkEnd();

                // Associate the 'Chart.xlsx' to the marked content as a source file and also add it to the document's embedded files.
                // The 'Chart.xlsx' file is associated without using a file system utility code.
                var embeddedFile = markStart.AssociatedFiles.AddEmpty(PdfAssociatedFileRelationshipType.Source, Path.GetFullPath(@"..\..\..\Chart.xlsx"), null, document.EmbeddedFiles).EmbeddedFile;
                // Associated file must specify modification date.
                embeddedFile.ModificationDate = File.GetLastWriteTime(Path.GetFullPath(@"..\..\..\Chart.xlsx"));
                // Associated file stream is not compressed since the source file, 'Chart.xlsx', is already compressed.
                using (var fileStream = File.OpenRead(Path.GetFullPath(@"..\..\..\Chart.xlsx")))
                using (var embeddedFileStream = embeddedFile.OpenWrite(compress: false))
                    fileStream.CopyTo(embeddedFileStream);

                // Associate another file, the 'ChartData.csv', to the marked content as a data file and also add it to the document's embedded files.
                markStart.AssociatedFiles.Add(PdfAssociatedFileRelationshipType.Data, Path.GetFullPath(@"..\..\..\ChartData.csv"), null, document.EmbeddedFiles);
            }

            document.Save("Associated Files.pdf");
        }

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

Download

Option Infer On

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

Friend Class Program
	''' <summary>
	''' Associate Files.
	''' </summary>
	''' <remarks>
	''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/associate-files.php
	''' </remarks>
	Shared Sub Main()
		' Before starting this example, please get a free trial key:
		' https://sautinsoft.com/start-for-free/

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

		Using document = New PdfDocument()
			' Make Attachments panel visible.
			document.PageMode = PdfPageMode.UseAttachments

			Using sourceDocument = PdfDocument.Load(Path.GetFullPath("..\..\..\simple text.pdf"))
				' Import the first page of an 'Simple Text.pdf' document.
				Dim page = document.Pages.AddClone(sourceDocument.Pages(0))

				' Associate the 'Simple Text.docx' file to the imported page as a source file and also add it to the document's embedded files.
				page.AssociatedFiles.Add(PdfAssociatedFileRelationshipType.Source, Path.GetFullPath("..\..\..\simple text.docx"), Nothing, document.EmbeddedFiles)
			End Using

			Using sourceDocument = PdfDocument.Load(Path.GetFullPath("..\..\..\Chart.pdf"))
				' Import the first page of a 'Chart.pdf' document.
				Dim page = document.Pages.AddClone(sourceDocument.Pages(0))

				' Group the content of an imported page and mark it with the 'AF' tag.
				Dim chartContentGroup = page.Content.Elements.Group(page.Content.Elements.First, page.Content.Elements.Last)
				Dim markStart = chartContentGroup.Elements.AddMarkStart(New PdfContentMarkTag(PdfContentMarkTagRole.AF), chartContentGroup.Elements.First)
				chartContentGroup.Elements.AddMarkEnd()

				' Associate the 'Chart.xlsx' to the marked content as a source file and also add it to the document's embedded files.
				' The 'Chart.xlsx' file is associated without using a file system utility code.
				Dim embeddedFile = markStart.AssociatedFiles.AddEmpty(PdfAssociatedFileRelationshipType.Source, Path.GetFullPath("..\..\..\Chart.xlsx"), Nothing, document.EmbeddedFiles).EmbeddedFile
				' Associated file must specify modification date.
				embeddedFile.ModificationDate = File.GetLastWriteTime(Path.GetFullPath("..\..\..\Chart.xlsx"))
				' Associated file stream is not compressed since the source file, 'Chart.xlsx', is already compressed.
				Using fileStream = File.OpenRead(Path.GetFullPath("..\..\..\Chart.xlsx"))
				Using embeddedFileStream = embeddedFile.OpenWrite(compress:= False)
					fileStream.CopyTo(embeddedFileStream)
				End Using
				End Using

				' Associate another file, the 'ChartData.csv', to the marked content as a data file and also add it to the document's embedded files.
				markStart.AssociatedFiles.Add(PdfAssociatedFileRelationshipType.Data, Path.GetFullPath("..\..\..\ChartData.csv"), Nothing, document.EmbeddedFiles)
			End Using

			document.Save("Associated Files.pdf")
		End Using

		System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo("Associated Files.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.