Как растрировать документ DOCX в PNG и JPEG с помощью C# и .NET

Полный код

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

namespace Example
{
    class Program
    {      
        static void Main(string[] args)
        {
            RasterizeDocxToPicture();         
        }

        /// <summary>
        /// Rasterize DOCX document into PNG and JPEG.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/rasterize-docx-document-to-png-jpeg-net-csharp-vb.php
        /// </remarks>
        static void RasterizeDocxToPicture()
        {
            // In this example we'll how rasterize/convert 1st and 2nd pages of DOCX document
            // into PNG and JPEG images.
            string inputFile = @"..\..\example.docx";
            string jpegFile = "Result.jpg";
            string pngFile = "Result.png";
            // The file format is detected automatically from the file extension: ".docx".
            // But as shown in the example below, we can specify DocxLoadOptions as 2nd parameter
            // to explicitly set that a loadable document has Docx format.
            DocumentCore dc = DocumentCore.Load(inputFile);
            
            DocumentPaginator documentPaginator = dc.GetPaginator(new PaginatorOptions() { UpdateFields = true });

            int dpi = 300;

            int pagesToRasterize = 2;
            int currentPage = 1;
            
            foreach (DocumentPage page in documentPaginator.Pages)
            {
                // Save the page into Bitmap with specified dpi and background.
                Bitmap picture = page.Rasterize(dpi, SautinSoft.Document.Color.White);

                // Save the Bitmap to a file.
                if (currentPage == 1)
                    picture.Save(pngFile);
                else if (currentPage == 2)
                    picture.Save(jpegFile);

                currentPage++;

                if (currentPage > pagesToRasterize)
                    break;
            }

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

Скачать

Imports System
Imports System.IO
Imports SautinSoft.Document
Imports System.Drawing

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			RasterizeDocxToPicture()
		End Sub

		''' <summary>
		''' Rasterize DOCX document into PNG and JPEG.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/rasterize-docx-document-to-png-jpeg-net-csharp-vb.php
		''' </remarks>
		Private Shared Sub RasterizeDocxToPicture()
			' In this example we'll how rasterize/convert 1st and 2nd pages of DOCX document
			' into PNG and JPEG images.
			Dim inputFile As String = "..\example.docx"
			Dim jpegFile As String = "Result.jpg"
			Dim pngFile As String = "Result.png"
			' The file format is detected automatically from the file extension: ".docx".
			' But as shown in the example below, we can specify DocxLoadOptions as 2nd parameter
			' to explicitly set that a loadable document has Docx format.
			Dim dc As DocumentCore = DocumentCore.Load(inputFile)

			Dim documentPaginator As DocumentPaginator = dc.GetPaginator(New PaginatorOptions() With {.UpdateFields = True})

			Dim dpi As Integer = 300

			Dim pagesToRasterize As Integer = 2
			Dim currentPage As Integer = 1

			For Each page As DocumentPage In documentPaginator.Pages
				' Save the page into Bitmap with specified dpi and background.
				Dim picture As Bitmap = page.Rasterize(dpi, SautinSoft.Document.Color.White)

				' Save the Bitmap to a file.
				If currentPage = 1 Then
					picture.Save(pngFile)
				ElseIf currentPage = 2 Then
					picture.Save(jpegFile)
				End If

				currentPage += 1

				If currentPage > pagesToRasterize Then
					Exit For
				End If
			Next page

			' Open the results for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(pngFile) With {.UseShellExecute = True})
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(jpegFile) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Скачать


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



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

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