Print with java.awt.PrintJob in Java
Description
The following code shows how to print with java.awt.PrintJob.
Example
//from ww w . j a v a 2 s . c o m
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.PrintJob;
import java.awt.Toolkit;
import java.util.Properties;
import javax.swing.JFrame;
public class Main extends JFrame {
public static void main(String args[]) {
String name = "Test print job";
Properties properties = new Properties();
PrintJob pj = Toolkit.getDefaultToolkit().getPrintJob(new Main(), name, properties);
if (pj != null) {
printDimensions(pj.getGraphics(), pj.getPageDimension());
pj.end();
}
}
static void printDimensions(Graphics g, Dimension size) {
int width = size.width;
int height = size.height;
int x1 = (int) (width * 0.1);
int x2 = (int) (width * 0.9);
int y1 = (int) (height * 0.1);
int y2 = (int) (height * 0.9);
g.drawRect(x1, y1, x2 - x1, y2 - y1);
g.dispose();
}
}
The code above generates the following result.