-->

C# - How to programmatically print an existing PDF

2020-07-27 04:35发布

问题:

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!

回答1:

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.

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 = "Letter_SkidTags_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();
    }
}