By more researching on web I solved my problem. I'm giving it here for those else who might need it;
I concluded the solution from this web site:
http://webmoli.com/2008/11/03/java-print-pdf/
Note: You need to install PdfRenderer .jar library to your project to run the code given in the website: The code initially in PrintPdf.java here doesn't give my solution however the author added a method in comments section to set different printers to print on runtime.
The method is:
/**
* Sets the printer service to be used for printing
*
* @param argPrintServiceName
* @throws PrinterException
*/
public void setPrintService(String argPrintServiceName) throws PrinterException {
PrintService[] printServices = PrinterJob.lookupPrintServices();
int i;
for (i = 0; i < printServices.length; i++) {
if (printServices[i].getName().equalsIgnoreCase(argPrintServiceName)) {
printerJob.setPrintService(printServices[i]);
break;
}
}
if (i == printServices.length) {
throw new PrinterException(“Invalid print service name: ” + argPrintServiceName);
}
}
You need to make a few changes on this method. Since printerJob is not a global variable it will not effect printing. To do this set return parameter of this method to PrintService as:
public static PrintService setPrintService(String argPrintServiceName) throws PrinterException {
PrintService psr = null;
PrintService[] printServices = PrinterJob.lookupPrintServices();
int i;
for (i = 0; i < printServices.length; i++) {
if (printServices[i].getName().equalsIgnoreCase(argPrintServiceName)) {
psr = printServices[i];
break;
}
}
if (i == printServices.length) {
throw new PrinterException("Invalid print service name: " + argPrintServiceName);
}
return psr;
}
In main method call the method like:
PrintService ps = setPrintService("Printer Name Here");
Now, you need to send this service to other methods;
Change this:
PrintPdf printPDFFile = new PrintPdf(fis, "Test Print PDF");
to
PrintPdf printPDFFile = new PrintPdf(fis, "Test Print PDF", ps);
And those are other methods that you need to change as:
public PrintPdf(byte[] content, String jobName, PrintService ps) throws
IOException, PrinterException
{
initialize(content, jobName, ps);
}
public PrintPdf(InputStream inputStream, String jobName, PrintService ps)
{
*
*
initialize(pdfContent, jobName, ps);
}
Add this line of code after assigning pjob: pjob.setPrintService(ps);
private void initialize(byte[] pdfContent, String jobName, PrintService ps) throws
IOException, PrinterException
{
*
*
pjob = PrinterJob.getPrinterJob();
pjob.setPrintService(ps);
*
*
...
}
This code works perfectly plus it is capable to direct-pdf printing.