Printing with Java

Copyright 2005, feel free to reuse the code in any way for free under the terms of version 2 of the Apache License. This code is presented “AS IS” with no promise it will work.

If you’re looking for an easy to use Java printing library, try GDSPrinting on Source Forge.

Welcome to Java Print Hell

Java and printers don’t mix. It’s like stirring oil and water. You can keep stirring hoping the job will succeed, but it never will. It just doesn’t work.

Java and printers are the same way. You get two options when you wish to implement printing from a java program, java.awt.print and javax.print. The java.awt.print package was added back with java 1.2. The javax.print package was added with java 1.4. The first gives you raw low level control to print. The second gives you industrial strength printing options with (currently) inaccurate examples. Both are lacking in the detailed tutorial arena. Neither gives programmers what they typically want, a quick easy way to print text.

Who’s fault is this? Sun’s of course. They’ve dropped the ball on printing from java. I’d love this paragraph to become out dated.

javax.print Examples

Don’t bother. This package is either broken, or purposely hard to use. None of Sun’s current sample code even compiles, let alone works. I’ve never found anyone who wasn’t disgusted at this misguided attempt to “fix” printing. My fondest dream is that some manager got fired for producing this kind of crap. I’m sure the engineers who wrote it are embarrassed beyond belief by it.

A java.awt.print Example

This works, though it is very touchy. I found a great website on it here:

http://www.developerdotstar.com/community/node/124

Here’s my hello world code.

package com.genedavissoftware.printing;

import java.awt.*;
import java.awt.print.*;
import javax.swing.*;


/**
 * HelloPrint
 * Copyright 2005 Gene Davis Software, [email protected]
 *
 * This code is free software; you can use it, redistribute it and/or
 * modify it under the terms of version 2 of the Apache License
 * found here:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *
 *
 * Very basic "Hello World" for printing in Java. This code
 * is from:
 *
 * http://genedavissoftware.com/2014/05/17/printing-with-java/
 *
 * Some information used to create this library is based off
 * information found here:
 *
 * http://www.developerdotstar.com/community/node/124
 *
 *
 */
public class HelloPrint extends JPanel implements Printable {

   public static void main(String[] args) {
      final JFrame jf = new JFrame("Hello Frame");

      final HelloPrint gds = new HelloPrint();
      gds.setPreferredSize(new Dimension(200,200));
      gds.setMinimumSize(new Dimension(200,200));

      jf.getContentPane().add(gds);

      jf.setSize(400,400);

      //invokeLater() is used as a workaround for a java
      //gui bug.
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            try {
               jf.setVisible(true);

               //get a PrintJob
               PrinterJob pjob = PrinterJob.getPrinterJob();
               //set a HelloPrint as the target to print
               pjob.setPrintable(gds, pjob.defaultPage());
               //get the print dialog, continue if canel
               //is not clicked
               if (pjob.printDialog()) {
                  //print the target (HelloPrint)
                  pjob.print();
               }
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
      });

   }

   /**
    * We happen to implement a paint method, but this could be
    * ignored for components that already to something interesting
    * on their own.
    */
   public void paint(Graphics g) {
      super.paint(g);
      g.drawString("Hello world!", 35, 100);
   }


   /**
    * Printable's implementation
    */
   public int print(Graphics g, PageFormat pf, int pageIndex) {
      //assume the page exists until proven otherwise
      int retval = Printable.PAGE_EXISTS;

      //We only want to deal with the first page.
      //The first page is numbered '0'
      if (pageIndex > 0){
         retval = Printable.NO_SUCH_PAGE;
      } else {
         //setting up the Graphics object for printing
         g.translate((int)(pf.getImageableX()), (int)(pf.getImageableY()));
         //populate the Graphics object from HelloPrint's paint() method
         paint(g);
      }

      return retval;
   }
}