Java has a very flexible printing system called JPS which makes printing very easy. Any JComponent can be made to print its contents by adding a print method
public int print(Graphics graphics, PageFormat pf, int page) throws PrinterException {}
When Java needs to print, it calls this method and whatever you paint onto the graphics object will be printed. The graphics object is an ‘abstract’ concept which is then scaled down to fit the printed page by Java.The page size is set and Java prints it all for you. Here is some example code
Paper paper = new Paper(); //Create default Page format A4
//use this command to alter area in which it prints
//paper.setImageableArea(a,b,c,d);
pf.setPaper(paper);
MyJComponent decode_pdf=new MyJComponent(); //has print method
//debug code discussed below
//decode_pdf.showImageableArea();
printJob.setPrintable(decode_pdf,pf);
//Print document
printJob.print(attributeSet); //attributeSet can be null or specific Print values
The printer page defines a page size to match the printer page, with an imageable area (some printers have a non-printable strip around a page which cannot be printed onto). It is very flexible and allows you to add alsorts of features. Learn more about some ideas of what is possible.
We have setup some sample values for different page sizes (A4, A5, A4 (Borderless) in a Java class PaperSizes.java
Unfortunately, Java does not let you read what are appropriate values, and it lets you define values which do not work – you can give Java values which result in things being printed off the page or in the non-printable area without any errors being generated.
The workaround we have adopted is to draw a box with a diagonal line so we can choose the correct settings through trial and error with a method to enable debugging (showImageableArea()). It is not perfect but provides a workaround. If you have also come across this problem, we hopes this helps (and if you have a better solution please let us know!).