Print any files using printer in Java

Java Print Service with code. You can print any files or images (pdf,jpeg,png,docs) by using java programming code.

If you are using Maven projects then include this dependencies in your POM file.

<!-- -->

    <!-- -->

    <!-- -->
	<!-- -->

commons-logging dependency must be included otherwise exception may occurs as “org.apache.commons.logging.LogFactory”.

If you are using Java projects then download these jars and add it to your projects by right click on your project then build path => configure build path=> add external jars and hit apply button.

Java Print Service with code. Must be sure that versions should not be less or much higher otherwise exceptions may occurs and also donot include more than one dependencies with different versions.As only one versions is allowed.

Here is the code for printing any files or images using java.

import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.printing.PDFPageable;


public class AutoPrintInvoice {
	  public static void main(String[] args) throws WriterException, IOException {
          String filePath = "sample.pdf";//path of the pdf file which you want to print
          String printerName="Canon G200";//Give the printer(Printer diver setup must be done in your computer)
          try {
			String print=printer(filePath,printerName);
                   System.out.println("Auto printed of pdf file"+print);
		} catch (PrinterException e) {
			// TODO Auto-generated catch block
		}//pass the all parameters.

	public static String printer(String filePath, String printerName)
			throws InvalidPasswordException, IOException, PrinterException {

		String flag = "Error";
		PDDocument document = PDDocument.load(new File(filePath));
		PrintService myPrintService = findPrintService(printerName);
		PrinterJob job = PrinterJob.getPrinterJob();
		job.setPageable(new PDFPageable(document));
			flag = "Success";
		job = null;
		myPrintService = null;
		return flag;

	private static PrintService findPrintService(String printerName) {
		PrintService[] printServices = PrintServiceLookup.lookupPrintServices(
				null, null);
		for (PrintService printService : printServices) {
			if (printService.getName().trim().equals(printerName)) {
				return printService;
		return null;

Make sure your printer is on and you have entered a correct printer name.

If you find any exceptions or error then feel free to contact us!! We are happy to help you.(I hope no exceptions would occurs).


About the author

Ravi Kumar

View all posts
0 0 vote
Article Rating
Notify of
Inline Feedbacks
View all comments