Преобразование PDF в растровое изображение в C# WPF .NET7

У меня есть приложение WPF, которое работает на многих киосках. В приложении я вызываю API, и он отвечает на URL-адрес PDF-файла. Я хочу распечатать этот PDF-файл на принтере SEWOO LK-B425A. Но, как указано в руководстве Windows SDK, принтер позволяет печатать только растровые файлы, поэтому перед печатью мне нужно преобразовать PDF в растровое изображение. Какая бесплатная библиотека для преобразования PDF в растровое изображение в C# WPF?

Я также пытаюсь использовать FreeSpire.PDF для преобразования, но принтер не может печатать и возникает исключение. При попытке использовать другую библиотеку с лицензией принтер работает, но на нем есть водяной знак. Так что кто-нибудь порекомендует мне, какую бесплатную библиотеку использовать. Спасибо.

Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
1
0
64
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Вы можете использовать библиотеку с открытым исходным кодом Ghostscript вместе с оболочкой Ghostscript.NET.

Вот пример кода:

using System.Drawing;
using Ghostscript.NET;
using Ghostscript.NET.Rasterizer;

namespace PDFTOBitmap
{
    internal class Program
    {
        static void Main()
        { 
            // Input PDF file
            string inputPdfFile = @"C:\input\a.pdf"; 

            // Output BMP file
            string outputBmpFile = @"C:\input\output.bmp"; 

            using (var rasterizer = new GhostscriptRasterizer())
            {
                rasterizer.Open(inputPdfFile);

                // Set the DPI (dots per inch) for rendering
                int dpi = 300; // Adjust the DPI as needed

                // Render the PDF page to a bitmap at the specified DPI
                var bitmap = rasterizer.GetPage(dpi,  1);

                // Save the bitmap to a BMP file
                bitmap.Save(outputBmpFile, System.Drawing.Imaging.ImageFormat.Bmp);
            }
        }
    }
}

Я бы использовал Inkscape с Inkscape.org. Это не относится к WPF, но вы можете экспортировать PDF-файлы в другие типы.

Для экспорта в растровое изображение PNG я использую следующее:

var inkscapePath = @"C:\InkscapeFolder\Inkscape.com";
var processInfo = new ProcessStartInfo(inkscapePath);
var command = $"{PDF-PATH} -z --export-dpi=500 --export-area-drawing --export-png = {EXPORT-PATH}\\{fileName}.png";
processInfo.Arguments = command;
processInfo.CreateNoWindow = true;
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
var cmd = Process.Start(processInfo);

Ниже приведены все варианты:

Available options:
  -V, --version                             Print the Inkscape version number
  -z, --without-gui                         Do not use X server (only process
                                            files from console)
  -g, --with-gui                            Try to use X server (even if
                                            $DISPLAY is not set)
  -f, --file=FILENAME                       Open specified document(s) (option
                                            string may be excluded)
  -p, --print=FILENAME                      Print document(s) to specified
                                            output file (use '| program' for
                                            pipe)
  -e, --export-png=FILENAME                 Export document to a PNG file
  -d, --export-dpi=DPI                      Resolution for exporting to bitmap
                                            and for rasterization of filters
                                            in PS/EPS/PDF (default 90)
  -a, --export-area=x0:y0:x1:y1             Exported area in SVG user units
                                            (default is the page; 0,0 is
                                            lower-left corner)
  -D, --export-area-drawing                 Exported area is the entire
                                            drawing (not page)
  -C, --export-area-page                    Exported area is the entire page
      --export-margin=VALUE                 Only for PS/EPS/PDF, sets margin
                                            in mm around exported area
                                            (default 0)
      --export-area-snap                    Snap the bitmap export area
                                            outwards to the nearest integer
                                            values (in SVG user units)
  -w, --export-width=WIDTH                  The width of exported bitmap in
                                            pixels (overrides export-dpi)
  -h, --export-height=HEIGHT                The height of exported bitmap in
                                            pixels (overrides export-dpi)
  -i, --export-id=ID                        The ID of the object to export
  -j, --export-id-only                      Export just the object with
                                            export-id, hide all others (only
                                            with export-id)
  -t, --export-use-hints                    Use stored filename and DPI hints
                                            when exporting (only with
                                            export-id)
  -b, --export-background=COLOR             Background color of exported
                                            bitmap (any SVG-supported color
                                            string)
  -y, --export-background-opacity=VALUE     Background opacity of exported
                                            bitmap (either 0.0 to 1.0, or 1 to
                                            255)
  -l, --export-plain-svg=FILENAME           Export document to plain SVG file
                                            (no sodipodi or inkscape
                                            namespaces)
  -P, --export-ps=FILENAME                  Export document to a PS file
  -E, --export-eps=FILENAME                 Export document to an EPS file
      --export-ps-level=PS Level            Choose the PostScript Level used
                                            to export. Possible choices are 2
                                            (the default) and 3
  -A, --export-pdf=FILENAME                 Export document to a PDF file
      --export-pdf-version=PDF_VERSION      Export PDF to given version.
                                            (hint: make sure to input the
                                            exact string found in the PDF
                                            export dialog, e.g. "PDF 1.4"
                                            which is PDF-a conformant)
      --export-latex                        Export PDF/PS/EPS without text.
                                            Besides the PDF/PS/EPS, a LaTeX
                                            file is exported, putting the text
                                            on top of the PDF/PS/EPS file.
                                            Include the result in LaTeX like:
                                            \input{latexfile.tex}
  -M, --export-emf=FILENAME                 Export document to an Enhanced
                                            Metafile (EMF) File
  -m, --export-wmf=FILENAME                 Export document to a Windows
                                            Metafile (WMF) File
  -T, --export-text-to-path                 Convert text object to paths on
                                            export (PS, EPS, PDF, SVG)
      --export-ignore-filters               Render filtered objects without
                                            filters, instead of rasterizing
                                            (PS, EPS, PDF)
  -X, --query-x                             Query the X coordinate of the
                                            drawing or, if specified, of the
                                            object with --query-id
  -Y, --query-y                             Query the Y coordinate of the
                                            drawing or, if specified, of the
                                            object with --query-id
  -W, --query-width                         Query the width of the drawing or,
                                            if specified, of the object with
                                            --query-id
  -H, --query-height                        Query the height of the drawing
                                            or, if specified, of the object
                                            with --query-id
  -S, --query-all                           List id,x,y,w,h for all objects
  -I, --query-id=ID                         The ID of the object whose
                                            dimensions are queried
  -x, --extension-directory                 Print out the extension directory
                                            and exit
      --vacuum-defs                         Remove unused definitions from the
                                            defs section(s) of the document
      --verb-list                           List the IDs of all the verbs in
                                            Inkscape
      --verb=VERB-ID                        Verb to call when Inkscape opens.
      --select=OBJECT-ID                    Object ID to select when Inkscape
                                            opens.
      --shell                               Start Inkscape in interactive
                                            shell mode.

Help options:
  -?, --help                                Show this help message
      --usage                               Display brief usage message

Другие вопросы по теме