Printing PDF Programmatically in C#, Part II

In my searches for a good PDF printing library, I came about Syncfusion’s PdfToImageConverter, which is available through NuGet for WinForms, WFP, .NET Core, and ASP.NET.

As far as I know it's a free edition.

With it I was, finally, able to build a printing function that allowed me to, programmatically, print a PDF to any configurated printer, while also setting the page size configuration.


This was the code I used.

/// <summary>
/// Prints the specified <paramref name="pdfFile"/> to the specified <paramref name="printer"/>.
/// </summary>
/// <param name="printer">The printer configuration to use.</param>
/// <param name="pdfFile">The PDF file to print.</param>
/// <remarks>The PDF file is deleted after printing.</remarks>
internal static void PrintAndDeletePDF(PrinterSettingSection printer, string pdfFile)
{
    try
    {
        if (printer.Copies == 0)
        {
            Log.Write(Resources.NoCopiesConfigured, printer.Name);
            return;
        }

        Log.Write(Resources.PDFPrinting, printer.Name);

        /*
         * Configure the printer
         */
        using var ptrDoc = new PrintDocument();
        ptrDoc.PrinterSettings.Copies = printer.Copies;
        ptrDoc.PrinterSettings.PrinterName = printer.Name;
        ptrDoc.PrinterSettings.DefaultPageSettings.PaperSize = printer.PaperSize;
        ptrDoc.PrinterSettings.DefaultPageSettings.Landscape = printer.PaperSize.Landscape;
        ptrDoc.PrinterSettings.DefaultPageSettings.PaperSize.Width = (int)(printer.PaperSize.Width * 100);
        ptrDoc.PrinterSettings.DefaultPageSettings.PaperSize.Height = (int)(printer.PaperSize.Height * 100);

        /*
         * Load the PDF file
         */
        using var strm = new FileStream(pdfFile, FileMode.Open);
        using var cvtr = new PdfToImageConverter();
        cvtr.Load(strm);
        var currPage = 0;

        ptrDoc.PrintPage += (sender, args) =>
        {
            /*
             * Print the current page
             */
            using var strm2 = cvtr.Convert(currPage, true, true);
            using var img = Image.FromStream(strm2);
            args.Graphics.DrawImage(img, args.PageBounds);
            args.HasMorePages = ++currPage < cvtr.PageCount;
        };

        /*
         * Start printing
         */
        ptrDoc.Print();
    }
    catch (Exception e)
    {
        Log.Write(ex: e);
    }
    finally
    {
        File.Delete(pdfFile);
        Log.Write(Resources.FileDeleted, Path.GetFileName(pdfFile));
    }
}

 

Comments