• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to print book of components using Java

Neeraj Kumar Mishra
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear friends...
I have to print the whole book of components....the problem is that i am
getting the first page printed and for the rest only the number of pages
correctly....can any one help me out so that all my pages get printed...
Neeraj Mishra

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.print.*;
public class SimpleBook {
final static Color bg = Color.white;
private Book bk = new Book();
Component component;
PrinterJob job = PrinterJob.getPrinterJob();
PageFormat landscape = job.defaultPage();

public SimpleBook() {
public void createBook(Component comp){
RightPage rpage;

bk.append(new PaintContent(comp),landscape );

public void print() {
if (job.printDialog()) {
try { job.print(); }
catch (Exception exc) {
System.out.println("Exception in print "+exc);

class PaintContent implements Printable {
public PaintContent(Component comp){
component = comp;

public int print(Graphics g, PageFormat pf, int page)
throws PrinterException {
Graphics2D g2d = (Graphics2D)g;
double pagewidth = pf.getImageableWidth();
double pageheight = pf.getImageableHeight();

double graphicswidth = component.getSize().getWidth();
double graphicsheight = component.getSize().getHeight();

double scalewidth = pagewidth/graphicswidth;
double scaleheight = pageheight/graphicsheight;

double scale;
if (scalewidth < scaleheight)
scale = scalewidth;
scale = scaleheight;

double offsetwidth = (pagewidth - graphicswidth)/2;
double offsetheight = (pageheight - graphicsheight*scale)/2;

g2d.translate(pf.getImageableX(), pf.getImageableY());
g2d.clip(new Rectangle2D.Double(0, 0,pf.getImageableWidth(), pf.getImageableHeight()));
g2d.translate(-page * pf.getImageableWidth(), 0);
g2d.scale(scale, scale);
page ++;

return Printable.PAGE_EXISTS;

It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic