如何使用 .net 6 和 PdfSharpCore 在服务器端打印?

问题描述 投票:0回答:0

我想在服务器端打印,但我的代码无法正常工作,并且在互联网上找不到任何解决方案。 我使用 nuget PdfSharpCore (版本 1.3.47)。 问题是我不知道如何将页面转换为可用于打印作业的位图或图像。 我在各处添加了评论以提供帮助。

这是我的代码:

using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using PdfSharpCore.Pdf;
using PdfSharpCore.Pdf.IO;
/// <summary>
/// The following code takes in a byte array of a PDF file, a printer name, a job name
/// (optional), and a boolean flag for whether to print in color or black and white. It then
/// prints the PDF file using the specified printer.
/// </summary>
/// <param name="pdfBytes">
/// </param>
/// <param name="printerName">
/// </param>
/// <param name="jobName">
/// </param>
/// <param name="isColor">
/// </param>
public void PrintPdf(byte[] pdfBytes, string printerName, string? jobName = null, bool isColor = true)
{
            // Use a memory stream to read the PDF bytes
            using (var pdfStream = new MemoryStream(pdfBytes))
            {
                // Use PdfSharp to open the PDF document
                using (var doc = PdfReader.Open(pdfStream))
                {
                    // Check if we are running on Windows
                    if (OperatingSystem.IsWindows())
                    {
                        // Only execute the following code if running on Windows

                        // Use PrintDocument to manage printing
                        using (var pd = new PrintDocument())
                        {
                            // Set the printer name
                            pd.PrinterSettings.PrinterName = printerName;

                            // Check if printer exists
                            if (!pd.PrinterSettings.IsValid)
                            {
                                // If the specified printer is not valid, use the default printer
                                pd.PrinterSettings.PrinterName = PrinterSettings.InstalledPrinters[0];

                                // Log all possible printers
                                foreach (string printer in PrinterSettings.InstalledPrinters)
                                {
                                    Console.WriteLine(printer);
                                }
                            }

                            // Set the print job name (if provided) or default to "Print Job"
                            pd.DocumentName = jobName ?? "Print Job";

                            // Set print settings
                            pd.DefaultPageSettings.Landscape = false;
                            pd.DefaultPageSettings.Color = isColor;

                            // Zero-based index for current page
                            int currentPage = 0;

                            // Add a PrintPageEventHandler to handle the printing of each page
                            pd.PrintPage += (sender, args) =>
                            {
                                // Check if the operating system is Windows
                                if (OperatingSystem.IsWindows())
                                {
                                    // Get the current page and its size
                                    var page = doc.Pages[currentPage];
                                    var size = new Size((int)page.Width, (int)page.Height);

                                    // Check if the page stream is not null
                                    if (page?.Stream != null)
                                    {
                                        // Render the PDF page as an image and draw it onto the bitmap
                                        using (var pageStream = new MemoryStream(page.Stream.Value))
                                        {
                                            using (var bmp = new Bitmap(pageStream))
                                            {
                                                // Check if the graphics object is not null
                                                if (args?.Graphics != null)
                                                {
                                                    try
                                                    {
                                                        // Draw the image onto the graphics object
                                                        // within the page boundaries
                                                        args.Graphics.DrawImage(bmp, args.PageBounds);
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        // Handle any exceptions that occur while
                                                        // rendering the image
                                                        Console.WriteLine($"Error rendering PDF as image: {ex.Message}");
                                                    }
                                                }
                                                else
                                                {
                                                    Console.WriteLine("Graphics object is null.");
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("PDF Stream empty.");
                                    }

                                    // Move to the next page
                                    currentPage++;

                                    // Set HasMorePages to true if there are more pages to print
                                    if (args != null)
                                    {
                                        args.HasMorePages = currentPage < doc.PageCount;
                                    }
                                }
                                else
                                {
                                    // Code for other operating systems
                                }
                            };

                            // Execute the Print Event
                            pd.Print();
                        }
                    }
                    else
                    {
                        // Code for other operating systems
                    }
                }
            }
        }
.net printing .net-6.0 server-side pdfsharpcore
© www.soinside.com 2019 - 2024. All rights reserved.