Printing in Java

Hi guys,

Seems like printing is one of the toughest things to do in Java. Maybe I might be wrong but I have a strong feeling in my guts that am right. But, say you have a JTextArea (lets say a text editor is in the workshop). There is the print button on the toolbar. Please complete the code below:

printButton.addActionListener(new ActionListener()

{

publicvoid actionPerformed(ActionEvent e)

{

// Fill the code;

}

});

Thanks and long live Java!

[746 byte] By [Jamwaa] at [2007-11-27 10:14:47]
# 1

> Hi guys,

>

> Seems like printing is one of the toughest things to

> do in Java. Maybe I might be wrong but I have a

> strong feeling in my guts that am right. But, say you

> have a JTextArea (lets say a text editor is in the

> workshop). There is the print button on the toolbar.

> Please complete the code below:

>

> > printButton.addActionListener(new ActionListener()

> {

> public void actionPerformed(ActionEvent e)

> {

>// Fill the code;

> });

>

>

> Thanks and long live Java!

printButton.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e) {

print();

});

Phew.... next Q?

ita6cgra at 2007-7-28 15:35:29 > top of Java-index,Java Essentials,Java Programming...
# 2

private void print()

{

//more code for you to provide

}

Jamwaa at 2007-7-28 15:35:29 > top of Java-index,Java Essentials,Java Programming...
# 3

Pay me and I will if you have a specific Q I will answer.... have you even tried to implement it?

ita6cgra at 2007-7-28 15:35:29 > top of Java-index,Java Essentials,Java Programming...
# 4

try this code:

import java.awt.*;

import java.awt.print.*;

import javax.swing.*;

/**

* This wrapper class encapsulates a Component and allows it to be printed

* using the Java 2 printing API.

*/

public class PrintableComponent extends JFrame implements Printable {

// The component to be printed.

Component c;//JTextArea //////////////////////////////

/** Create a PrintableComponent wrapper around a Component */

public PrintableComponent(Component c) { this.c = c; }

/**

* This method is not part of the Printable interface. It is a method

* that sets up the PrinterJob and initiates the printing.

*/

public void print() throws PrinterException {

// Get the PrinterJob object

PrinterJob job = PrinterJob.getPrinterJob();

// Get the default page format, then allow the user to modify it

PageFormat format = job.pageDialog(job.defaultPage());

// Tell the PrinterJob what to print

job.setPrintable(this, format);

// Ask the user to confirm, and then begin the printing process

if (job.printDialog())

job.print();

}

/**

* This is the "callback" method that the PrinterJob will invoke.

* This method is defined by the Printable interface.

*/

public int print(Graphics g, PageFormat format, int pagenum) {

// The PrinterJob will keep trying to print pages until we return

// this value to tell it that it has reached the end.

if (pagenum > 0)

return Printable.NO_SUCH_PAGE;

// We're passed a Graphics object, but it can always be cast to Graphics2D

Graphics2D g2 = (Graphics2D) g;

// Use the top and left margins specified in the PageFormat Note

// that the PageFormat methods are poorly named. They specify

// margins, not the actual imageable area of the printer.

g2.translate(format.getImageableX(), format.getImageableY());

// Tell the component to draw itself to the printer by passing in

// the Graphics2D object. This will not work well if the component

// has double-buffering enabled.

c.paint(g2);

// Return this constant to tell the PrinterJob that we printed the page.

return Printable.PAGE_EXISTS;

}

printButton.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

try{

print();

}catch(Exception e){

e.printStackTrace();

}

}

});

}

your main frame should implements Printable interface.

in your actionPerfomed(Event ev), call print.

Hope That Help

Message was edited by:

java_2006

java_2006a at 2007-7-28 15:35:29 > top of Java-index,Java Essentials,Java Programming...
# 5

There are Ten dukes for you on completion of the mission. To implement it, all docs from Sun assume a panel that is being painted on. Can you paint() a JTextArea?

Jamwaa at 2007-7-28 15:35:29 > top of Java-index,Java Essentials,Java Programming...
# 6

so ?

java_2006a at 2007-7-28 15:35:29 > top of Java-index,Java Essentials,Java Programming...
# 7

So here is thy suggestion put to the test:

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.print.*;

import javax.swing.*;

/**

* This wrapper class encapsulates a Component and allows it to be printed

* using the Java 2 printing API.

*/

public class PrintPage extends JFrame implements Printable

{

// The component to be printed.

Component c;//JTextArea //////////////////////////////

JButton printButton = new JButton("Print");

/** Create a PrintableComponent wrapper around a Component */

public PrintPage(Component c)

{

super("Printer");

this.c = c;

setSize(500, 500);

printButton.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

try

{

print();

}

catch(Exception err)

{

err.printStackTrace();

}

}

});

setLayout(new BorderLayout());

getContentPane().add(printButton, BorderLayout.NORTH);

}

/**

* This method is not part of the Printable interface. It is a method

* that sets up the PrinterJob and initiates the printing.

*/

public void print() throws PrinterException

{

// Get the PrinterJob object

PrinterJob job = PrinterJob.getPrinterJob();

// Get the default page format, then allow the user to modify it

PageFormat format = job.pageDialog(job.defaultPage());

// Tell the PrinterJob what to print

job.setPrintable(this, format);

// Ask the user to confirm, and then begin the printing process

if (job.printDialog())

job.print();

}

/**

* This is the "callback" method that the PrinterJob will invoke.

* This method is defined by the Printable interface.

*/

public int print(Graphics g, PageFormat format, int pagenum)

{

// The PrinterJob will keep trying to print pages until we return

// this value to tell it that it has reached the end.

if (pagenum > 0)

return Printable.NO_SUCH_PAGE;

// We're passed a Graphics object, but it can always be cast to Graphics2D

Graphics2D g2 = (Graphics2D) g;

// Use the top and left margins specified in the PageFormat Note

// that the PageFormat methods are poorly named. They specify

// margins, not the actual imageable area of the printer.

g2.translate(format.getImageableX(), format.getImageableY());

// Tell the component to draw itself to the printer by passing in

// the Graphics2D object. This will not work well if the component

// has double-buffering enabled.

c.paint(g2);

// Return this constant to tell the PrinterJob that we printed the page.

return Printable.PAGE_EXISTS;

}

}

with a main class

/*

* Main.java

*

* Created on July 11, 2007, 4:47 PM

*

* To change this template, choose Tools | Template Manager

* and open the template in the editor.

*/

import java.awt.TextArea;

/**

*

* @author arthur

*/

public class Main

{

public static void main(String[] args)

{

String printThis =

"Seems like printing is one of the toughest things to do in Java." +

"Maybe I might be wrong but I have a strong feeling in my guts that " +

"am right. But, say you have a JTextArea (lets say a text editor is in" +

"the workshop). There is the print button on the toolbar. Please complete" +

"the code below";

new PrintPage(new TextArea(printThis, 100, 300)).setVisible(true);

}

}

But all it prints is a blank page.

Jamwaa at 2007-7-28 15:35:29 > top of Java-index,Java Essentials,Java Programming...
# 8

Search the web for my StandardPrint.java class. It makes printing a snap

http://forum.java.sun.com/thread.jspa?threadID=661036&messageID=3879270

ps you're welcome

tjacobs01a at 2007-7-28 15:35:29 > top of Java-index,Java Essentials,Java Programming...
# 9

i suggest this:

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.print.*;

import javax.swing.*;

/**

* This wrapper class encapsulates a Component and allows it to be printed using

* the Java 2 printing API.

*/

public class PrintPage extends JFrame implements Printable {

// The component to be printed.

JPanel p;// JTextArea //////////////////////////////

JButton printButton = new JButton("Print");

/** Create a PrintableComponent wrapper around a Component */

public PrintPage(Component c) {

super("Printer");

this.p = new JPanel();

this.p.add(new JLabel(((TextArea)c).getText()));

add(p);

setSize(500, 500);

printButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

try {

print();

} catch (Exception err) {

err.printStackTrace();

}

}

});

Container container = getContentPane();

container.setLayout(new BorderLayout());

container.add(p, BorderLayout.CENTER);///////////////////////////ADD YOUR PANEL

container.add(printButton, BorderLayout.NORTH);

}

/**

* This method is not part of the Printable interface. It is a method that

* sets up the PrinterJob and initiates the printing.

*/

public void print() throws PrinterException {

// Get the PrinterJob object

PrinterJob job = PrinterJob.getPrinterJob();

// Get the default page format, then allow the user to modify it

PageFormat format = job.pageDialog(job.defaultPage());

// Tell the PrinterJob what to print

job.setPrintable(this, format);

// Ask the user to confirm, and then begin the printing process

if (job.printDialog())

job.print();

}

/**

* This is the "callback" method that the PrinterJob will invoke. This method

* is defined by the Printable interface.

*/

public int print(Graphics g, PageFormat format, int pagenum) {

// The PrinterJob will keep trying to print pages until we return

// this value to tell it that it has reached the end.

if (pagenum > 0)

return Printable.NO_SUCH_PAGE;

// We're passed a Graphics object, but it can always be cast to Graphics2D

Graphics2D g2 = (Graphics2D) g;

// Use the top and left margins specified in the PageFormat Note

// that the PageFormat methods are poorly named. They specify

// margins, not the actual imageable area of the printer.

g2.translate(format.getImageableX(), format.getImageableY());

// Tell the component to draw itself to the printer by passing in

// the Graphics2D object. This will not work well if the component

// has double-buffering enabled.

p.paint(g2);

// Return this constant to tell the PrinterJob that we printed the page.

return Printable.PAGE_EXISTS;

}

public static void main(String[] args) {

String printThis = "Seems like printing is one of the toughest things to do in Java."

+ "Maybe I might be wrong but I have a strong feeling in my guts that "

+ "am right. But, say you have a JTextArea (lets say a text editor is in"

+ "the workshop). There is the print button on the toolbar. Please complete" + "the code below";

new PrintPage(new TextArea(printThis, 10, 50)).setVisible(true);

}

}

You can also make a screenshot of your component:

import java.awt.*;

import java.awt.image.*;

import java.io.*;

import javax.imageio.*;

public class Screenshot {

public static void main(String[] args) throws Exception {

// make sure we have exactly two arguments,

// a waiting period and a file name

if (args.length != 2) {

System.err.println("Usage: java Screenshot " +

"WAITSECONDS OUTFILE.png");

System.exit(1);

}

// check if file name is valid

String outFileName = args[1];

if (!outFileName.toLowerCase().endsWith(".png")) {

System.err.println("Error: output file name must " +

"end with \".png\".");

System.exit(1);

}

// wait for a user-specified time

try {

long time = Long.parseLong(args[0]) * 1000;

System.out.println("Waiting " + (time / 1000) +

" second(s)...");

Thread.sleep(time);

} catch(NumberFormatException nfe) {

System.err.println(args[0] + " does not seem to be a " +

"valid number of seconds.");

System.exit(1);

}

// determine current screen size

Toolkit toolkit = Toolkit.getDefaultToolkit();

Dimension screenSize = toolkit.getScreenSize();

Rectangle screenRect = new Rectangle(screenSize);

// create screen shot

Robot robot = new Robot();

BufferedImage image = robot.createScreenCapture(screenRect);

// save captured image to PNG file

ImageIO.write(image, "png", new File(outFileName));

// give feedback

System.out.println("Saved screen shot (" + image.getWidth() +

" x " + image.getHeight() + " pixels) to file \"" +

outFileName + "\".");

// use System.exit if the program hangs after writing the file;

// that's an old bug which got fixed only recently

// System.exit(0);

}

}

Message was edited by:

java_2006

java_2006a at 2007-7-28 15:35:29 > top of Java-index,Java Essentials,Java Programming...
# 10

Using the first option, I am able to print fine (thanks by the way). However, how come it prints only the visible part of the TextArea? Is it possible to make it print instead of printing part of it, scrolling to what remains then finishing (coz this seems like the only way out)?

Jamwaa at 2007-7-28 15:35:29 > top of Java-index,Java Essentials,Java Programming...