VintaSoft Imaging .NET SDK v8.7
Vintasoft.Imaging.Pdf Namespace / PdfDocument Class / Attachments Property
Example



In This Topic
    Attachments Property
    In This Topic
    Gets a collections of file attachments that a PDF consumer uses to enhance the presentation of file attachments stored in the PDF document.
    Syntax
    'Declaration
     
    Public ReadOnly Property Attachments As PdfAttachmentCollection
    public PdfAttachmentCollection Attachments {get;}
    public: __property PdfAttachmentCollection* get_Attachments();
    public:
    property PdfAttachmentCollection^ Attachments {
       PdfAttachmentCollection^ get();
    }
    Example
    This example shows how to create a new PDF portfolio.
    ''' <summary>
    ''' Assemblies a portfolio from files and folders from specified path.
    ''' </summary>
    ''' <param name="rootPath">The root path to assembly portfolio.</param>
    ''' <param name="outputPdfFilename">The output PDF filename.</param>
    Public Shared Sub AssemblyPortfolio(rootPath As String, outputPdfFilename As String)
    	' create PDF document (version 1.7)
    	Using document As New Vintasoft.Imaging.Pdf.PdfDocument(outputPdfFilename, Vintasoft.Imaging.Pdf.PdfFormat.Pdf_17)
    		' add page to document
    		Dim page As Vintasoft.Imaging.Pdf.Tree.PdfPage = document.Pages.Add(Vintasoft.Imaging.PaperSizeKind.A4)
                
    		' draw text on first page
    		Using g As Vintasoft.Imaging.Pdf.Drawing.PdfGraphics = page.GetGraphics()
    			Dim textBox As New Vintasoft.Imaging.Pdf.Drawing.GraphicsFigures.TextBoxFigure()
    			textBox.Font = document.FontManager.GetStandardFont(Vintasoft.Imaging.Pdf.Tree.Fonts.PdfStandardFontType.TimesRoman)
    			textBox.FontSize = 30
    			textBox.Location = New System.Drawing.PointF(0, 0)
    			textBox.Size = page.MediaBox.Size
    			textBox.TextAlignment = Vintasoft.Imaging.Pdf.Drawing.PdfContentAlignment.Top Or Vintasoft.Imaging.Pdf.Drawing.PdfContentAlignment.Left Or Vintasoft.Imaging.Pdf.Drawing.PdfContentAlignment.Right
    			textBox.TextBrush = New Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Black)
    			textBox.Text = "This document is Portfolio" & vbLf & "(Attachment Collection)" & vbLf & "To view Portfolio you should use PDF viewer compatible with PDF 1.7 ExtensionLevel 3."
    			textBox.Draw(g)
    		End Using
                
    		' create attachements
    		document.CreateAttachments(True)
                
    		' set viewer settings
    		document.Attachments.View = Vintasoft.Imaging.Pdf.Tree.FileAttachments.AttachmentCollectionViewMode.TileMode
    		document.Attachments.SplitterBar = New Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentCollectionSplitterBar(document)
    		document.Attachments.SplitterBar.Direction = Vintasoft.Imaging.Pdf.Tree.FileAttachments.AttachmentCollectionSplitterBarDirection.None
    		document.DocumentViewMode = Vintasoft.Imaging.Pdf.PdfDocumentViewMode.UseAttachments
                
    		' create field that defines sorting of files and folders in PDF viewer
    		Dim sortFieldName As String = "Order"
    		Dim sortField As New Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentCollectionSchemaField(document, "Order (Sort)", Vintasoft.Imaging.Pdf.Tree.FileAttachments.AttachmentCollectionSchemaFieldDataType.Number)
    		sortField.IsVisible = False
    		document.Attachments.Schema = New Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentCollectionSchema(document)
    		document.Attachments.Schema.Add(sortFieldName, sortField)
                
    		' create sort properties
    		document.Attachments.Sort = New Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentCollectionSort(document)
    		document.Attachments.Sort.FieldNames = New String() {sortFieldName}
                
    		' use ZIP compression for files
    		Dim filesCompression As Vintasoft.Imaging.Pdf.PdfCompression = Vintasoft.Imaging.Pdf.PdfCompression.Zip
                
    		' add files and folders to portfolio
    		AddPathRecursively(document.Attachments.RootFolder, rootPath, False, filesCompression, True, sortFieldName)
                
    		' save changes in PDF document
    		document.SaveChanges()
    	End Using
    End Sub
                
    ''' <summary>
    ''' Adds the path (all files and sub folders) to specified portfolio folder.
    ''' </summary>
    ''' <param name="folder">The portfolio folder.</param>
    ''' <param name="path">The path that should be added to the portfolio.</param>
    ''' <param name="addPathAsFolder">Determines that portfolio must contain folder with the path filename.</param>
    ''' <param name="compression">The compression that should be applied to files and folders.</param>
    ''' <param name="generateThumbnails">Determines that portfolio must contain thumbnails for files.</param>
    ''' <param name="sortFieldName">Name of the sort field.</param>
    ''' <returns>
    ''' Added folder.
    ''' </returns>
    Private Shared Function AddPathRecursively(folder As Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentFolder, path As String, addPathAsFolder As Boolean, compression As Vintasoft.Imaging.Pdf.PdfCompression, generateThumbnails As Boolean, sortFieldName As String) As Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentFolder
    	' sort order
    	Dim order As Integer = 0
                
    	' folder to which path must be added
    	Dim currentFolder As Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentFolder
    	' if portfolio must contain folder with the path filename
    	If addPathAsFolder Then
    		' add new folder to portfolio folder and use it as current folder
    		currentFolder = folder.AddFolder(System.IO.Path.GetFileName(path))
    		currentFolder.CreationDate = System.DateTime.Now
    	Else
    		' use root folder as current folder
    		currentFolder = folder
    		folder.ModificationDate = System.DateTime.Now
    	End If
                
    	' get directories in the specified path
    	Dim paths As String() = System.IO.Directory.GetDirectories(path, "*", System.IO.SearchOption.TopDirectoryOnly)
    	' for each directory
    	For Each subPath As String In paths
    		' if directory is hidden
    		If (System.IO.File.GetAttributes(subPath) And System.IO.FileAttributes.Hidden) <> 0 Then
    			' ignore directory
    			Continue For
    		End If
                
    		Try
    			' add the directory (all files and sub folders) to current portfolio folder
    			Dim addedSubFolder As Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentFolder = AddPathRecursively(currentFolder, subPath, True, compression, generateThumbnails, sortFieldName)
                
    			' if sorting must be used
    			If sortFieldName IsNot Nothing Then
    				' add data field collection to the portfolio folder
    				addedSubFolder.DataFields = New Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentDataFieldCollection(folder.Document)
    				' add data field value which defines sorting
    				addedSubFolder.DataFields.Add(sortFieldName, New Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentDataField(folder.Document, order))
    				' increment sort order
    				order += 1
    			End If
    		Catch ex As System.Exception
    			System.Console.WriteLine(String.Format("{0}: {1}", currentFolder, ex.Message))
    		End Try
    	Next
                
    	' get files in the specified path
    	Dim files As String() = System.IO.Directory.GetFiles(path, "*", System.IO.SearchOption.TopDirectoryOnly)
    	' if files are found
    	If files.Length > 0 Then
    		' for each file
    		For Each filename As String In files
    			' if file is hidden
    			If (System.IO.File.GetAttributes(filename) And System.IO.FileAttributes.Hidden) <> 0 Then
    				' ignore file
    				Continue For
    			End If
                
    			Try
    				' add file
    				System.Console.WriteLine(String.Format("Add file {0}...", filename))
    				Dim file As Vintasoft.Imaging.Pdf.Tree.PdfEmbeddedFileSpecification = currentFolder.AddFile(filename, compression)
    				file.EmbeddedFile.CreationDate = System.DateTime.Now
                
    				' if thumbnail must be generated
    				If generateThumbnails Then
    					' generate file thumbnail
    					file.Thumbnail = CreateThumbnailResource(file.Document, filename)
    				End If
                
    				' if sorting must be used
    				If sortFieldName IsNot Nothing Then
    					' add data field collection to the portfolio folder
    					file.DataFields = New Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentDataFieldCollection(folder.Document)
    					' add data field value which defines sorting
    					file.DataFields.Add(sortFieldName, New Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentDataField(folder.Document, order))
    					' increment sort order
    					order += 1
                
    				End If
    			Catch ex As System.Exception
    				System.Console.WriteLine(String.Format("{0}: {1}", filename, ex.Message))
    			End Try
    		Next
    		currentFolder.ModificationDate = System.DateTime.Now
    	End If
                
    	Return currentFolder
    End Function
                
    ''' <summary>
    ''' Creates PDF image resource with thumbnail of specified file.
    ''' </summary>
    ''' <param name="document">The PDF document.</param>
    ''' <param name="filename">The name of file for which thumbnail must be generated.</param>
    ''' <returns>Thumbnail image resource.</returns>
    Private Shared Function CreateThumbnailResource(document As Vintasoft.Imaging.Pdf.PdfDocument, filename As String) As Vintasoft.Imaging.Pdf.Tree.PdfImageResource
    	' get codec for file
    	Dim codec As Vintasoft.Imaging.Codecs.Codec = Vintasoft.Imaging.Codecs.AvailableCodecs.GetCodecByExtension(System.IO.Path.GetExtension(filename))
    	' if code is available and codec has decoder
    	If codec IsNot Nothing AndAlso codec.CanCreateDecoder Then
    		Try
    			' get an image of first page of file
    			Using image As New Vintasoft.Imaging.VintasoftImage(filename)
    				' get image thumbnail
    				Using thumbnailImage As Vintasoft.Imaging.VintasoftImage = image.Thumbnail.GetThumbnailImage(100, 100)
    					Dim compressionSettings As New Vintasoft.Imaging.Pdf.PdfCompressionSettings()
    					compressionSettings.JpegQuality = 90
    					' return PDF image-resource that contains image thumbnail
    					Return New Vintasoft.Imaging.Pdf.Tree.PdfImageResource(document, thumbnailImage, Vintasoft.Imaging.Pdf.PdfCompression.Jpeg, compressionSettings)
    				End Using
    			End Using
    		Catch
    		End Try
    	End If
    	Return Nothing
    End Function
    /// <summary>
    /// Assemblies a portfolio from files and folders from specified path.
    /// </summary>
    /// <param name="rootPath">The root path to assembly portfolio.</param>
    /// <param name="outputPdfFilename">The output PDF filename.</param>
    public static void AssemblyPortfolio(string rootPath, string outputPdfFilename)
    {
        // create PDF document (version 1.7)
        using (Vintasoft.Imaging.Pdf.PdfDocument document = new Vintasoft.Imaging.Pdf.PdfDocument(
            outputPdfFilename, Vintasoft.Imaging.Pdf.PdfFormat.Pdf_17))
        {
            // add page to document
            Vintasoft.Imaging.Pdf.Tree.PdfPage page = document.Pages.Add(
                Vintasoft.Imaging.PaperSizeKind.A4);
                
            // draw text on first page
            using (Vintasoft.Imaging.Pdf.Drawing.PdfGraphics g = page.GetGraphics())
            {
                Vintasoft.Imaging.Pdf.Drawing.GraphicsFigures.TextBoxFigure textBox =
                    new Vintasoft.Imaging.Pdf.Drawing.GraphicsFigures.TextBoxFigure();
                textBox.Font = document.FontManager.GetStandardFont(Vintasoft.Imaging.Pdf.Tree.Fonts.PdfStandardFontType.TimesRoman);
                textBox.FontSize = 30;
                textBox.Location = new System.Drawing.PointF(0, 0);
                textBox.Size = page.MediaBox.Size;
                textBox.TextAlignment =
                    Vintasoft.Imaging.Pdf.Drawing.PdfContentAlignment.Top |
                    Vintasoft.Imaging.Pdf.Drawing.PdfContentAlignment.Left |
                    Vintasoft.Imaging.Pdf.Drawing.PdfContentAlignment.Right;
                textBox.TextBrush = new Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Black);
                textBox.Text = "This document is Portfolio\n(Attachment Collection)\nTo view Portfolio you should use PDF viewer compatible with PDF 1.7 ExtensionLevel 3.";
                textBox.Draw(g);
            }
                
            // create attachements
            document.CreateAttachments(true);
                
            // set viewer settings
            document.Attachments.View = Vintasoft.Imaging.Pdf.Tree.FileAttachments.AttachmentCollectionViewMode.TileMode;
            document.Attachments.SplitterBar =
                new Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentCollectionSplitterBar(document);
            document.Attachments.SplitterBar.Direction =
                Vintasoft.Imaging.Pdf.Tree.FileAttachments.AttachmentCollectionSplitterBarDirection.None;
            document.DocumentViewMode = Vintasoft.Imaging.Pdf.PdfDocumentViewMode.UseAttachments;
                
            // create field that defines sorting of files and folders in PDF viewer
            string sortFieldName = "Order";
            Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentCollectionSchemaField sortField =
                new Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentCollectionSchemaField(
                    document, "Order (Sort)",
                    Vintasoft.Imaging.Pdf.Tree.FileAttachments.AttachmentCollectionSchemaFieldDataType.Number);
            sortField.IsVisible = false;
            document.Attachments.Schema = new Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentCollectionSchema(document);
            document.Attachments.Schema.Add(sortFieldName, sortField);
                
            // create sort properties
            document.Attachments.Sort = new Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentCollectionSort(document);
            document.Attachments.Sort.FieldNames = new string[] { sortFieldName };
                
            // use ZIP compression for files
            Vintasoft.Imaging.Pdf.PdfCompression filesCompression = Vintasoft.Imaging.Pdf.PdfCompression.Zip;
                
            // add files and folders to portfolio
            AddPathRecursively(
                document.Attachments.RootFolder,
                rootPath,
                false,
                filesCompression,
                true,
                sortFieldName);
                
            // save changes in PDF document
            document.SaveChanges();
        }
    }
                
    /// <summary>
    /// Adds the path (all files and sub folders) to specified portfolio folder.
    /// </summary>
    /// <param name="folder">The portfolio folder.</param>
    /// <param name="path">The path that should be added to the portfolio.</param>
    /// <param name="addPathAsFolder">Determines that portfolio must contain folder with the path filename.</param>
    /// <param name="compression">The compression that should be applied to files and folders.</param>
    /// <param name="generateThumbnails">Determines that portfolio must contain thumbnails for files.</param>
    /// <param name="sortFieldName">Name of the sort field.</param>
    /// <returns>
    /// Added folder.
    /// </returns>
    private static Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentFolder AddPathRecursively(
        Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentFolder folder,
        string path,
        bool addPathAsFolder,
        Vintasoft.Imaging.Pdf.PdfCompression compression,
        bool generateThumbnails,
        string sortFieldName)
    {
        // sort order
        int order = 0;
                
        // folder to which path must be added
        Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentFolder currentFolder;
        // if portfolio must contain folder with the path filename
        if (addPathAsFolder)
        {
            // add new folder to portfolio folder and use it as current folder
            currentFolder = folder.AddFolder(System.IO.Path.GetFileName(path));
            currentFolder.CreationDate = System.DateTime.Now;
        }
        else
        {
            // use root folder as current folder
            currentFolder = folder;
            folder.ModificationDate = System.DateTime.Now;
        }
                
        // get directories in the specified path
        string[] paths = System.IO.Directory.GetDirectories(path, "*", System.IO.SearchOption.TopDirectoryOnly);
        // for each directory
        foreach (string subPath in paths)
        {
            // if directory is hidden
            if ((System.IO.File.GetAttributes(subPath) & System.IO.FileAttributes.Hidden) != 0)
                // ignore directory
                continue;
                
            try
            {
                // add the directory (all files and sub folders) to current portfolio folder
                Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentFolder addedSubFolder =
                    AddPathRecursively(currentFolder, subPath, true, compression, generateThumbnails, sortFieldName);
                
                // if sorting must be used
                if (sortFieldName != null)
                {
                    // add data field collection to the portfolio folder
                    addedSubFolder.DataFields =
                        new Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentDataFieldCollection(folder.Document);
                    // add data field value which defines sorting
                    addedSubFolder.DataFields.Add(sortFieldName,
                        new Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentDataField(folder.Document, order));
                    // increment sort order
                    order++;
                }
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(string.Format("{0}: {1}", currentFolder, ex.Message));
            }
        }
                
        // get files in the specified path
        string[] files = System.IO.Directory.GetFiles(path, "*", System.IO.SearchOption.TopDirectoryOnly);
        // if files are found
        if (files.Length > 0)
        {
            // for each file
            foreach (string filename in files)
            {
                // if file is hidden
                if ((System.IO.File.GetAttributes(filename) & System.IO.FileAttributes.Hidden) != 0)
                    // ignore file
                    continue;
                
                try
                {
                    // add file
                    System.Console.WriteLine(string.Format("Add file {0}...", filename));
                    Vintasoft.Imaging.Pdf.Tree.PdfEmbeddedFileSpecification file = currentFolder.AddFile(filename, compression);
                    file.EmbeddedFile.CreationDate = System.DateTime.Now;
                
                    // if thumbnail must be generated
                    if (generateThumbnails)
                        // generate file thumbnail
                        file.Thumbnail = CreateThumbnailResource(file.Document, filename);
                
                    // if sorting must be used
                    if (sortFieldName != null)
                    {
                        // add data field collection to the portfolio folder
                        file.DataFields =
                            new Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentDataFieldCollection(folder.Document);
                        // add data field value which defines sorting
                        file.DataFields.Add(sortFieldName,
                            new Vintasoft.Imaging.Pdf.Tree.FileAttachments.PdfAttachmentDataField(folder.Document, order));
                        // increment sort order
                        order++;
                    }
                
                }
                catch (System.Exception ex)
                {
                    System.Console.WriteLine(string.Format("{0}: {1}", filename, ex.Message));
                }
            }
            currentFolder.ModificationDate = System.DateTime.Now;
        }
                
        return currentFolder;
    }
                
    /// <summary>
    /// Creates PDF image resource with thumbnail of specified file.
    /// </summary>
    /// <param name="document">The PDF document.</param>
    /// <param name="filename">The name of file for which thumbnail must be generated.</param>
    /// <returns>Thumbnail image resource.</returns>
    private static Vintasoft.Imaging.Pdf.Tree.PdfImageResource CreateThumbnailResource(
        Vintasoft.Imaging.Pdf.PdfDocument document, string filename)
    {
        // get codec for file
        Vintasoft.Imaging.Codecs.Codec codec = Vintasoft.Imaging.Codecs.AvailableCodecs.GetCodecByExtension(
            System.IO.Path.GetExtension(filename));
        // if code is available and codec has decoder
        if (codec != null && codec.CanCreateDecoder)
        {
            try
            {
                // get an image of first page of file
                using (Vintasoft.Imaging.VintasoftImage image = new Vintasoft.Imaging.VintasoftImage(filename))
                {
                    // get image thumbnail
                    using (Vintasoft.Imaging.VintasoftImage thumbnailImage = image.Thumbnail.GetThumbnailImage(100, 100))
                    {
                        Vintasoft.Imaging.Pdf.PdfCompressionSettings compressionSettings =
                            new Vintasoft.Imaging.Pdf.PdfCompressionSettings();
                        compressionSettings.JpegQuality = 90;
                        // return PDF image-resource that contains image thumbnail
                        return new Vintasoft.Imaging.Pdf.Tree.PdfImageResource(document, thumbnailImage,
                            Vintasoft.Imaging.Pdf.PdfCompression.Jpeg, compressionSettings);
                    }
                }
            }
            catch
            {
            }
        }
        return null;
    }
    Requirements

    Target Platforms: Windows 10, Windows 8, Windows 7, Windows Vista, Windows XP, Windows Server 2012, Windows Server 2008, Windows Server 2003

    See Also