複数ページを印刷する
if (job.printDialog()) {
try {
job.print();//印刷指示
} catch (Exception e) { /* handle exception */
}
}
printDialog() は、Windowsの標準の印刷ダイアログを利用します。このダイアログで、プリンタの設定や、印刷の中止を指定できます。import java.awt.*;
import java.awt.print.*;
public class PrintBook {
public static void main(String[] args) {
// 印刷をするクラスのインスタンス:jobを生成
PrinterJob job = PrinterJob.getPrinterJob();
// 横向き印刷をするページフォーマットを設定する
PageFormat pfl = job.defaultPage();
pfl.setOrientation(PageFormat.LANDSCAPE);
// Book クラスのインスタンスを作成
Book bk = new Book();
//表紙を1ページ追加
bk.append(new PaintCover(), pfl);
//本文を2ページ追加
bk.append(new PaintContent(), job.defaultPage(), 2);
//本を印刷iobに渡す
job.setPageable(bk);
// 印刷ダイアログを表示、プリンタの設定可能
if (job.printDialog()) {
try {
job.print();//印刷指示
} catch (Exception e) { /* handle exception */
}
}
System.exit(0);
}
}
//landScapeで印刷する
class PaintCover implements Printable {
Font fnt = new Font("Helvetica-Bold", Font.PLAIN, 72);
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
g.setFont(fnt);
g.setColor(Color.black);
//中央部に72ポイントで表示
int yc = (int) (pf.getImageableY() + pf.getImageableHeight() / 2);
g.drawString("中京", 72, yc + 36);
return Printable.PAGE_EXISTS;
}
}
class PaintContent implements Printable {
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
Graphics2D g2 = (Graphics2D) g;
int useRed = 0;
int xo = (int) pf.getImageableX();
int yo = (int) pf.getImageableY();
//1ページは赤と緑の円、2ページ目は四角を印刷する
for (int x = 0; x + 28 < pf.getImageableWidth(); x += 36)
for (int y = 0; y + 28 < pf.getImageableHeight(); y += 36) {
if (useRed == 0)
g.setColor(Color.red);
else
g.setColor(Color.green);
useRed = 1 - useRed;
if (pageIndex % 2 == 0)
g.drawRect(xo + x + 4, yo + y + 4, 28, 28);
else
g.drawOval(xo + x + 4, yo + y + 4, 28, 28);
}
return Printable.PAGE_EXISTS;
}
}