While developing a project, we come across some requirement to print PDF files silently. The challenge was to push the file to a selected or desired printer. It shouldn't always print in the default printer. Also, it should work in Servoy Web client. Here, let me clarify that this code looks for the printers connected in Servoy Server machine for web client.
After quite some investigation, we come across some Java code that runs fine for the requirement. This code uses Apache PDF Box Java Library.
function silentPrint(filePath, preferredPrinter) {
var printerJob = Packages.java.awt.print.PrinterJob.getPrinterJob();
if (preferredPrinter) {
var _printServices = Packages.javax.print.PrintServiceLookup.lookupPrintServices(null, null)
for (var _i = 0; _i<_printServices.length; _i++) {
if (_printServices[_i].getName() == preferredPrinter) {
printerJob.setPrintService(_printServices[_i]);
break;
}
}
if (_i == _printServices.length) return false;
} else {
var _printService = new Packages.javax.print.PrintServiceLookup.lookupDefaultPrintService();
if (!_printService) return false;
printerJob.setPrintService(_printService);
}
if (!printerJob) return false;
try {
var printDocument = Packages.org.apache.pdfbox.pdmodel.PDDocument.load(filePath);
if (!printDocument) return false;
printDocument.silentPrint(printerJob);
}
catch (exception) { }
finally {
printDocument.close();
}
return true;
}
Let's go through the code a little bit.
var _printServices = Packages.javax.print.PrintServiceLookup.lookupPrintServices(null, null)
for (var _i = 0; _i<_printServices.length; _i++) {
if (_printServices[_i].getName() == preferredPrinter) {
printerJob.setPrintService(_printServices[_i]);
break;
}
}
This is basically looping through the available Printer Services and associates the Printer Job object with the Printer Service matching our selected Printer name.
var _printService = new Packages.javax.print.PrintServiceLookup.lookupDefaultPrintService();
When no preferred printer name is provided, it looks for the default printer available and uses that printer for printing.
var printDocument = Packages.org.apache.pdfbox.pdmodel.PDDocument.load(filePath);
We are using Apache PDF Box library to read the PDF file. This jar need to be copied to Beans folder in application_server
. You can download it from here.
printDocument.silentPrint(printerJob);
This sends the loaded file into the printer’s job queue silently.