ststeiger / PdfSharpCore

Port of the PdfSharp library to .NET Core - largely removed GDI+ (only missing GetFontData - which can be replaced with freetype2)
Other
1.05k stars 234 forks source link

Print in server Side not working #351

Open WimVdSAllPhi opened 1 year ago

WimVdSAllPhi commented 1 year ago

I would like to print on Server side but the code that I have will not work properly and don't find any solution on the internet. The problem is I don't know how to translate a page to a bitmap or image that can be used for the print job. Here is my code :

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
                    }
                }
            }
        }
packdat commented 1 year ago

You are using the wrong library. This library does not support rendering PDF-Pages to bitmaps. In addition, this code:

using (var pageStream = new MemoryStream(page.Stream.Value))
{
    using (var bmp = new Bitmap(pageStream))

will not work because the stream you're using does not contain bitmap-data. I'm not really sure, WHAT that stream might contain (if it is present after all). The PDF-spec might reveal details.

Depending on the server you're using (Linux ? Windows ?), there might be different libraries/tools available, but i can't give an any recommendations, because I've never tried what you're trying to accomplish.

WimVdSAllPhi commented 1 year ago

Thanks a lot I will look for other library. I run in Windows.