Сохранение PDF-документа в виде изображений PNG и JPEG (создание миниатюры документа) в C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите PDF-документ.
  3. Выполните разбиение документа на страницы.
  4. Сохраните каждую страницу в формате PNG или Jpeg.

   В этом примере мы растеризуем/сохраним 1-ю и 2-ю страницы PDF-документа как изображения PNG и JPEG.

Полный код

using System;
using System.IO;
using System.Runtime.Intrinsics.Arm;
using SautinSoft.Document;
using SkiaSharp;

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

            RasterizePdfToPicture();
        }

        /// <summary>
        /// Rasterizing - save PDF document as PNG and JPEG images.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/rasterize-save-pdf-document-as-png-jpeg-images-net-csharp-vb.php
        /// </remarks>
        static void RasterizePdfToPicture()
        {
            // In this example we'll how rasterize/save 1st and 2nd pages of PDF document
            // as PNG and JPEG images.
            string inputFile = @"..\..\..\example.pdf";
            string jpegFile = "Result.jpeg";
            string pngFile = "Result.png";

            DocumentCore dc = DocumentCore.Load(inputFile, new PdfLoadOptions()
            {
                DetectTables = false,
                ConversionMode = PdfConversionMode.Exact
            });

            DocumentPaginator documentPaginator = dc.GetPaginator(new PaginatorOptions() { UpdateFields = true });

            int pagesToRasterize = 2;
            int currentPage = 1;

            foreach (DocumentPage page in documentPaginator.Pages)
            {

                // Save to a PNG file.
                if (currentPage == 1)
                    page.Save(pngFile, new ImageSaveOptions { DpiX = 300, DpiY = 300, Format = ImageSaveFormat.Png });

                // Save to a JPEG file.
                else if (currentPage == 2)
                    page.Save(jpegFile, new ImageSaveOptions { DpiX = 300, DpiY = 300, Format = ImageSaveFormat.Jpeg });

                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 });
        }
    }
}

Download

Imports System
Imports System.IO
Imports SautinSoft.Document
Imports SkiaSharp

Namespace Example
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            RasterizePdfToPicture()
        End Sub
        ''' Get your free trial key here:   
        ''' https://sautinsoft.com/start-for-free/
        ''' <summary>
        ''' Rasterizing - save PDF document as PNG and JPEG images.
        ''' </summary>
        ''' <remarks>
        ''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/rasterize-save-pdf-document-as-png-jpeg-images-net-csharp-vb.php
        ''' </remarks>
        Private Shared Sub RasterizePdfToPicture()
            ' In this example we'll how rasterize/save 1st and 2nd pages of PDF document
            ' as PNG and JPEG images.
            Dim inputFile As String = "..\..\..\example.pdf"
            Dim jpegFile As String = "Result.jpg"
            Dim pngFile As String = "Result.png"

            Dim dc As DocumentCore = DocumentCore.Load(inputFile, New PdfLoadOptions() With {
                .DetectTables = False,
                .ConversionMode = PdfConversionMode.Exact
            })

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

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

            For Each page As DocumentPage In documentPaginator.Pages

                ' Save to a PNG file.
                If currentPage = 1 Then
                    page.Save(pngFile, New ImageSaveOptions() With {
                        .Format = ImageSaveFormat.Png, .DpiX = 72, .DpiY = 72})

                    ' Save to a JPEG file.
                ElseIf currentPage = 2 Then
                    page.Save(jpegFile, New ImageSaveOptions() With {
                        .Format = ImageSaveFormat.Jpeg, .DpiX = 72, .DpiY = 72})
                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

Download


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



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

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