Silent Printing from Java


Are you having trouble printing from Java?

Do you have a perfect PDF — maybe one you made with iText — but when you print it the edge is cut off?

And you have checked and double-checked your Java, and nothing seems to be wrong?


Here is a helpful hint — make sure your page size is LETTER, and not, say ISO A4. I know you are too smart to confuse the two, but if you are presumptive and did not check Wikipedia and just remember that one time you were in Office Depot and they seemed like the same, mebs you might make this mistake and struggle with it for two days. Mebs.

Point is, A4 is a little longer and a little skinnier than LETTER — enough to cut off some of your beautiful letter document.


If you use iText, make your document size like this:

Document document = new Document(PageSize.LETTER);

Or if you are feeling sassy and landscape-y, like this:

Document document = new Document(PageSize.LETTER.rotate());


And when you print, do like this (super simple and dangerous, assuming printer can handle everything, using default and printing silently, etc.):

DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
DocAttributeSet printAttributes = new HashDocAttributeSet();

PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();

DocPrintJob job = defaultService.createPrintJob();

System.out.println(“Printing ” + outputFilePath + ” to ” + defaultService.getName());

InputStream inputStream;
try {
inputStream = new FileInputStream(outputFilePath);
Doc doc = new SimpleDoc(inputStream, flavor, printAttributes);

try {
job.print(doc, null);
} catch (PrintException e) { e.printStackTrace(); }

} catch (FileNotFoundException e1) { e1.printStackTrace(); }

Or… you know what? If you’re on a Mac, and you want to live even MORE dangerously? (Or maybe just eliminate the possibility of problems with your document, rather than your printing?) SHA-POW:

try {

Runtime.getRuntime().exec(“lp ” + outputFilePath);

System.out.println(“Successfully printed ” + outputFilePath);
} catch (IOException e) {
System.out.println(“Document ‘” + outputFilePath + “‘ failed to print.”);


(Also, incidentally, iText has an class with a silent printing method, but I couldn’t get it to work. Not that that sez anything.)


Draws. Sweats. Eats too much sugar-free candy.

You may also like...

%d bloggers like this: