Как сохранить документ в различных форматах

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите или создайте документ.
  3. Сохраните в желаемом формате.

SautinSoft.Document поддерживает форматы:

PDF DOCX RTF HTML Текст Изображения
Create/Read/Write Create/Read/Write Create/Read/Write Create/Read/Write Create/Read/Write Create/Read(OCR)/Write

Предположим, что мы уже загрузили или создали документ внутри нашего класса DocumentCore.

Для сохранения документа в файл достаточно одной строки.

В этом примере метод Save() автоматически определяет формат сохранения (в данном случае PDF) по расширению «.pdf»:


            // Save our document 'dc' into a PDF file.
            dc.Save(@"d:\Book.pdf");

В большинстве случаев Вам потребуется явно указать формат сохранения и установить некоторые параметры сохранения. Учитывая этот момент, метод Save() имеет несколько перегрузок и принимает SaveOptions в качестве второго параметра.


            // Save our document 'dc' into HTML-fixed format.
            dc.Save(@"d:\Menu.html", new HtmlFixedSaveOptions()
            {
                CssExportMode = CssExportMode.Inline,
                PageBorder = false,
                EmbedImages = true
            });

Все параметры сохранения являются производными от базового абстрактного класса SaveOptions: PdfSaveOptions , DocxSaveOptions , HtmlFixedSaveOptions , HtmlFlowingSaveOptions , RtfSaveOptions и так далее.

Сохранить в память:


            using (MemoryStream msRtf = new MemoryStream())
            {
                // Save our document in RTF format to a stream.
                dc.Save(msRtf, new RtfSaveOptions());
            }

Полный код

using System.IO;
using SautinSoft.Document;

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

            SaveToFile();
            SaveToStream();
        }
		
        /// <summary>
        /// Creates a new document and saves it as DOCX file.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document.php
        /// </remarks>
        static void SaveToFile()
        {
            // Assume we already have a document 'dc'.
            DocumentCore dc = new DocumentCore();
            dc.Content.End.Insert("Hey Guys and Girls!");

            string filePath = @"Result.docx";

            // The file format will be detected automatically from the file extension: ".docx".
            dc.Save(filePath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true });
        }

        /// <summary>
        /// Creates a new document and saves it as PDF using MemoryStream.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document.php
        /// </remarks>
        static void SaveToStream()
        {
            // There variables are necessary only for demonstration purposes.
            byte[] fileData = null;
            string filePath = @"Result.pdf";

            // Assume we already have a document 'dc'.
            DocumentCore dc = new DocumentCore();
            dc.Content.End.Insert("Hey Guys and Girls!");

            // Let's save our document to a MemoryStream.
            using (MemoryStream ms = new MemoryStream())
            {
                // 2nd parameter: we've explicitly set to save our document in PDF format.
                dc.Save(ms, new PdfSaveOptions());

                fileData = ms.ToArray();
            }

            File.WriteAllBytes(filePath, fileData);
            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true });
        }
    }
}

Download

Imports System
Imports System.IO
Imports SautinSoft.Document

Module Sample
    Sub Main()
        SaveToFile()
        SaveToStream()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Creates a new document and saves it as DOCX file.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document.php
    ''' </remarks>
    Sub SaveToFile()
        ' Assume we already have a document 'dc'.
        Dim dc As New DocumentCore()
        dc.Content.End.Insert("Hey Guys and Girls!")

        Dim filePath As String = "Result.docx"

        ' The file format will be detected automatically from the file extension: ".docx".
        dc.Save(filePath)

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

    ''' <summary>
    ''' Creates a new document and saves it as PDF using MemoryStream.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document.php
    ''' </remarks>
    Sub SaveToStream()
        ' There variables are necessary only for demonstration purposes.
        Dim fileData() As Byte = Nothing
        Dim filePath As String = "Result.pdf"

        ' Assume we already have a document 'dc'.
        Dim dc As New DocumentCore()
        dc.Content.End.Insert("Hey Guys and Girls!")

        ' Let's save our document to a MemoryStream.
        Using ms As New MemoryStream()
            ' 2nd parameter: we've explicitly set to save our document in PDF format.
            dc.Save(ms, New PdfSaveOptions())

            fileData = ms.ToArray()
        End Using

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

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



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

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