Как добавлять и читать встроенные и настраиваемые свойства документа в C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите/создайте документ.
  3. Перейдите к свойствам документа.

Свойства документа, также известные как метаданные, представляют собой сведения о файле, которые описывают или идентифицируют его. Они включают в себя такие детали, как название, имя автора, тему и ключевые слова, которые идентифицируют тему или содержимое документа. Если вы включите свойства документа для своих файлов, вы сможете легко упорядочить и идентифицировать их позже. Вы также можете искать документы по их свойствам или вставлять их в свои документы.

В следующем примере показано, как добавить встроенные и пользовательские свойства документа (метаданные).
Прежде всего, давайте создадим простой RTF документ с надписью: "Hello World" и добавим внутрь некоторые метаданные:


               // Let's create a simple inscription.
            dc.Content.End.Insert("Hello World!!!", new CharacterFormat() { FontName = "Verdana", Size = 65.5f, FontColor = Color.Orange });
            
Следующим шагом является добавление встроенных свойств документа:

               // Let's add some documents properties: Author, Subject, Company.
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Title] = "How to add document properties. It works with DOCX, RTF, PDF, HTML etc";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Company] = "SautinSoft";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Author] = "John Smith";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Subject] = "Document.Net";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.HyperlinkBase] = "www.sautinsoft.com";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Manager] = "Alex Dickard";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Category] = "Document Object Model (DOM)";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.DateContentCreated] =
                new DateTime(2010, 1, 10).ToString();
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.DateLastSaved] =
                new DateTime(2018, 6, 30).ToString();
И последний шаг - это сохранить документ в RTF файл.

                                       // Save document as the RTF file
            dc.Save(@"d:\Download\DocumentProperties.rtf");

Если Вы хотите прочитать свойства документа из файла:


                                        DocumentCore dc = DocumentCore.Load(@"d:\Download\DocumentProperties_.docx");

Следующим шагом является считывание всей информации о файле и ее отображение.


                                        // Let's add some additional inforamtion. It can be anything you like.
            dc.Document.Properties.Custom.Add("Producer", "My Producer");

            // Add a paragraph in which all standard information about the document will be stored
            Paragraph builtInPara = new Paragraph(dc,
            new Run(dc, "Built-in document properties:"),
            new SpecialCharacter(dc, SpecialCharacterType.LineBreak));
            builtInPara.ParagraphFormat.Alignment = HorizontalAlignment.Left;
             
            foreach (var docProp in dc.Document.Properties.BuiltIn)
            {
                builtInPara.Inlines.Add(
                    new Run(dc, string.Format("{0}: {1}", docProp.Key, docProp.Value)));

                builtInPara.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak));
            }
            // Add a paragraph in which all additional information about the document will be stored
            Paragraph customPropPara = new Paragraph(dc,
               new Run(dc, "Custom document properties:"),
               new SpecialCharacter(dc, SpecialCharacterType.LineBreak));
            customPropPara.ParagraphFormat.Alignment = HorizontalAlignment.Left;

            foreach (var docProp in dc.Document.Properties.Custom)
            {
                customPropPara.Inlines.Add(
                    new Run(dc, string.Format("{0}: {1} (Type: {2})", docProp.Key, docProp.Value, docProp.Value.GetType())));

                customPropPara.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak));
            }

Вы можете найти дополнительную информацию о Document Properties.

Полный код

using System;
using SautinSoft.Document;
using SautinSoft.Document.Drawing;
using System.IO;
using System.Linq;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free 100-day key here:   
            // https://sautinsoft.com/start-for-free/

            CreateDocumentProperties();
            ReadDocumentProperties();
        }
		
        /// <summary>
        /// Create a new document (DOCX) with some built-in properties.
        /// </summary>
		/// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/document-properties.php
        /// </remarks>
        public static void CreateDocumentProperties()
        {
            string filePath = @"..\..\..\DocumentProperties.docx";

            DocumentCore dc = new DocumentCore();

            // Let's create a simple inscription.
            dc.Content.End.Insert("Hello World!!!", new CharacterFormat() { FontName = "Verdana", Size = 65.5f, FontColor = Color.Orange });

            // Let's add some documents properties: Author, Subject, Company.
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Title] = "How to add document properties. It works with DOCX, RTF, PDF, HTML etc";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Company] = "SautinSoft";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Author] = "John Smith";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Subject] = "Document .Net";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Keywords] = "reader, writer, docx, pdf, html, rtf, text";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.HyperlinkBase] = "www.sautinsoft.com";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Manager] = "Alex Dickard";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.Category] = "Document Object Model (DOM)";
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.DateContentCreated] =
                new DateTime(2010, 1, 10).ToString();
            dc.Document.Properties.BuiltIn[BuiltInDocumentProperty.DateLastSaved] =
                DateTime.Now.ToString();

            dc.CalculateStats();
            
            // Save our document to DOCX format.
            dc.Save(filePath);
			
            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true });
        }

        /// <summary>
        /// Read built-in document properties (from .docx) and enumerate them in new PDF document as small report.
        /// </summary>
		/// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/document-properties.php
        /// </remarks>
        public static void ReadDocumentProperties()
        {
            string inpFile = @"..\..\..\DocumentProperties.docx";
            string statFile = @"..\..\..\Statistics.pdf";

            DocumentCore dc = DocumentCore.Load(inpFile);
			
            // Let's add some additional information. It can be anything you like.
            dc.Document.Properties.Custom.Add("Producer", "My Producer");

            // Add a paragraph in which all standard information about the document will be stored.
            Paragraph builtInPara = new Paragraph(dc,
            new Run(dc, "Built-in document properties:"),
            new SpecialCharacter(dc, SpecialCharacterType.LineBreak));
            builtInPara.ParagraphFormat.Alignment = HorizontalAlignment.Left;

            foreach (var docProp in dc.Document.Properties.BuiltIn)
            {
                builtInPara.Inlines.Add(
                    new Run(dc, string.Format("{0}: {1}", docProp.Key, docProp.Value)));

                builtInPara.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak));
            }
			
            // Add a paragraph in which all additional information about the document will be stored.
            Paragraph customPropPara = new Paragraph(dc,
               new Run(dc, "Custom document properties:"),
               new SpecialCharacter(dc, SpecialCharacterType.LineBreak));
            customPropPara.ParagraphFormat.Alignment = HorizontalAlignment.Left;

            foreach (var docProp in dc.Document.Properties.Custom)
            {
                customPropPara.Inlines.Add(
                    new Run(dc, string.Format("{0}: {1} (Type: {2})", docProp.Key, docProp.Value, docProp.Value.GetType())));

                customPropPara.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak));
            }
			
            // Add all document properties in the document and save it as PDF file.
            dc.Sections.Clear();
            dc.Sections.Add(new Section(dc, builtInPara, customPropPara));

            dc.Save(statFile, new PdfSaveOptions());
			
            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(statFile) { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.IO
Imports SautinSoft.Document
Imports System.Linq

Module Sample
    Sub Main()
        CreateDocumentProperties()
        ReadDocumentProperties()
    End Sub
    ''' Get your free 100-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Create a new document (DOCX) with some built-in properties.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/document-properties.php
    ''' </remarks>
    Sub CreateDocumentProperties()
        Dim filePath As String = "..\..\..\DocumentProperties.docx"

        Dim dc As New DocumentCore()

        ' Let's create a simple inscription.
        dc.Content.End.Insert("Hello World!!!", New CharacterFormat() With {
            .FontName = "Verdana",
            .Size = 65.5F,
            .FontColor = Color.Orange
        })

        ' Let's add some documents properties: Author, Subject, Company.
        dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.Title) = "How to add document properties. It works with DOCX, RTF, PDF, HTML etc"
        dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.Company) = "SautinSoft"
        dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.Author) = "John Smith"
        dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.Subject) = "Document .Net"
        dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.Keywords) = "reader, writer, docx, pdf, html, rtf, text"
        dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.HyperlinkBase) = "www.sautinsoft.com"
        dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.Manager) = "Alex Dickard"
        dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.Category) = "Document Object Model (DOM)"
        dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.DateContentCreated) = (New Date(2010, 1, 10)).ToString()
        dc.Document.Properties.BuiltIn(BuiltInDocumentProperty.DateLastSaved) = Date.Now.ToString()

        dc.CalculateStats()

        ' Save our document to DOCX format.
        dc.Save(filePath)

        ' Open the result for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(filePath) With {.UseShellExecute = True})
    End Sub

    ''' <summary>
    ''' Read built-in document properties (from .docx) and enumerate them in new PDF document as small report.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/document-properties.php
    ''' </remarks>
    Sub ReadDocumentProperties()
        Dim inpFile As String = "..\..\..\DocumentProperties.docx"
        Dim statFile As String = "..\..\..\Statistics.pdf"

        Dim dc As DocumentCore = DocumentCore.Load(inpFile)

        ' Let's add some additional inforamtion. It can be anything you like.
        dc.Document.Properties.Custom.Add("Producer", "My Producer")

        ' Add a paragraph in which all standard information about the document will be stored.
        Dim builtInPara As New Paragraph(dc, New Run(dc, "Built-in document properties:"), New SpecialCharacter(dc, SpecialCharacterType.LineBreak))
        builtInPara.ParagraphFormat.Alignment = HorizontalAlignment.Left

        For Each docProp In dc.Document.Properties.BuiltIn
            builtInPara.Inlines.Add(New Run(dc, String.Format("{0}: {1}", docProp.Key, docProp.Value)))

            builtInPara.Inlines.Add(New SpecialCharacter(dc, SpecialCharacterType.LineBreak))
        Next docProp

        ' Add a paragraph in which all additional information about the document will be stored.
        Dim customPropPara As New Paragraph(dc, New Run(dc, "Custom document properties:"), New SpecialCharacter(dc, SpecialCharacterType.LineBreak))
        customPropPara.ParagraphFormat.Alignment = HorizontalAlignment.Left

        For Each docProp In dc.Document.Properties.Custom
            customPropPara.Inlines.Add(New Run(dc, String.Format("{0}: {1} (Type: {2})", docProp.Key, docProp.Value, docProp.Value.GetType())))

            customPropPara.Inlines.Add(New SpecialCharacter(dc, SpecialCharacterType.LineBreak))
        Next docProp

        ' Add all document properties in the document and save it as PDF file.
        dc.Sections.Clear()
        dc.Sections.Add(New Section(dc, builtInPara, customPropPara))

        dc.Save(statFile, New PdfSaveOptions())

        ' Open the result for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(statFile) With {.UseShellExecute = True})
    End Sub
End Module

Download


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



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

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