How to Automate Printing PDF Documents
Automating the printing of PDF documents is a common task in various applications. In this article, we explore how to efficiently send PDF files to the printer queue and have them printed directly from your code.
.NET Windows Forms Approach
For a Windows Forms .NET 4 application running on Windows XP, one approach involves utilizing a command line to print the PDF file. Here's how to implement this:
using System.Diagnostics; using System.IO; public void SendToPrinter(string filePath) { // Convert full file path to short path for command line use string shortPath = Path.GetShortPathName(filePath); // Prepare the command line arguments string args = $"/p \"{shortPath}\""; // Create a new Process object Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = "/C start " + args; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; // Execute the command line process.Start(); }
Enhanced Solution with PdfiumViewer
Another option, particularly suitable for PDF printing, is to leverage the Google Pdfium library and its .NET wrapper, PdfiumViewer. This open source library provides a robust PDF printing capability:
using PdfiumViewer; public bool PrintPDF( string printer, string paperName, string filePath, int copies) { try { // Create printer settings var printerSettings = new PrinterSettings { PrinterName = printer, Copies = (short)copies, }; // Create page settings for paper size 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; } } // Print PDF document using (var document = PdfDocument.Load(filePath)) { using (var printDocument = document.CreatePrintDocument()) { printDocument.PrinterSettings = printerSettings; printDocument.DefaultPageSettings = pageSettings; printDocument.PrintController = new StandardPrintController(); printDocument.Print(); } } return true; } catch { return false; } }
This enhanced approach provides more control over the printing process and enables silent printing without user interaction.
The above is the detailed content of How to Automate PDF Printing from .NET Applications?. For more information, please follow other related articles on the PHP Chinese website!