Adding a new answer to this question, since the question of printing PDF in .net has been around for a long time, and most of the answers come before the Google Pdfium library, which now has a .net wrapper. For me, I myself studied this problem and tried to make hacked decisions, such as spawning Acrobat or other PDF readers, or working in commercial libraries that are expensive and do not have very compatible licensing conditions. But the Google Pdfium library and the PdfiumViewer.net wrapper are Open Source, so this is a great solution for many developers, including me. PdfiumViewer is licensed under the Apache 2.0 license.
Here you can get the NuGet package:
https://www.nuget.org/packages/PdfiumViewer/
and here you can find the source code:
https://github.com/pvginkel/PdfiumViewer
Here is a simple code that will quietly print any number of copies of a PDF file from it filename. You can also download PDFs from a stream (as is usually done), and you can easily understand this by looking at the code or examples. There is also a PDF representation of WinForm so you can also display PDF files in a view or preview them. For us, I just needed the ability to quietly print a PDF file to a specific printer on demand.
public bool PrintPDF( string printer, string paperName, string filename, int copies) { try { // Create the printer settings for our printer var printerSettings = new PrinterSettings { PrinterName = printer, Copies = (short)copies, }; // Create our page settings for the paper size selected var pageSettings = new PageSettings(printerSettings) { Margins = new Margins(0, 0, 0, 0), }; foreach (PaperSize paperSize in printerSettings.PaperSizes) { if (paperSize.PaperName == paperName) { pageSettings.PaperSize = paperSize; break; } } // Now print the PDF document using (var document = PdfDocument.Load(filename)) { using (var printDocument = document.CreatePrintDocument()) { printDocument.PrinterSettings = printerSettings; printDocument.DefaultPageSettings = pageSettings; printDocument.PrintController = new StandardPrintController(); printDocument.Print(); } } return true; } catch { return false; } }
Kendall Bennett Jan 19 '17 at 20:34 on 2017-01-19 20:34
source share