C# - How to programmatically print an existing PDF file using PrintDocument
Asked Answered
F

1

8

I want to print an existing pdf file a second time with a pdf printer.

I try to use PrintDocument. But how do I tell PrintDocument the name of the existing document??

Thanks in advance!

Fortunetelling answered 17/12, 2017 at 17:9 Comment(0)
C
16

There are several ways you can print an existing file to different printer. There are several third party libraries as well. Some are paid and some are free. However I shall explain the way I had achieved it after 2 days.

Install the nuget package PdfiumViewer. But do not install the latest version as you will have to install another package for pdfium.dll and that is hectic.

Install-Package PdfiumViewer -Version 2.10.0

This version comes with the pdfium.dll file so that you do not have to install it separately. Expand your solution explorer and right click on pdfium.dll inside x64 and x86 folder. Go to properties and set the Copy to Output Directory = Copy always.

enter image description here

Now that the setup is complete, you can go ahead with the code.

var path = @"path\file.pdf";
using (var document = PdfDocument.Load(path))
{
    using (var printDocument = document.CreatePrintDocument())
    {
        printDocument.PrinterSettings.PrintFileName = "Report_9ae93aa7-4359-444e-a033-eb5bf17f5ce6.pdf";
        printDocument.PrinterSettings.PrinterName = @"printerName";
        printDocument.DocumentName = "file.pdf";
        printDocument.PrinterSettings.PrintFileName = "file.pdf";
        printDocument.PrintController = new StandardPrintController();
        printDocument.Print();
    }
}
Cylinder answered 31/1, 2018 at 8:5 Comment(1)
And use "printDocument.PrinterSettings.PrintToFile = true;" to skip the save file dialog.Diantha

© 2022 - 2024 — McMap. All rights reserved.