📄 printdemo2.java
字号:
// PrintDemo2.java
import java.awt.*;
import java.awt.geom.*;
import java.awt.print.*;
class PrintDemo2
{
public static void main (String [] args)
{
// Get a PrinterJob
PrinterJob job = PrinterJob.getPrinterJob ();
// Create a landscape page format.
PageFormat pf = job.defaultPage ();
pf.setOrientation (PageFormat.LANDSCAPE);
// Set up a book.
Book bk = new Book ();
bk.append (new paintCover (), pf);
bk.append (new paintContent (), job.defaultPage (), 1);
// Pass the book to the PrinterJob.
job.setPageable (bk);
// Specify the job name.
job.setJobName ("My book");
// Put up the dialog box.
if (job.printDialog ())
{
// Print the job if the user didn't cancel printing
try
{
job.print ();
}
catch (PrinterException e)
{
System.out.println (e);
}
}
System.exit (0);
}
}
class paintContent implements Printable
{
public int print (Graphics g, PageFormat pf, int pageIndex)
throws PrinterException
{
System.out.println ("Page index = " + pageIndex);
// pageIndex 1 corresponds to page number 2.
if (pageIndex > 2)
return Printable.NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D) g;
double w = pf.getImageableWidth ();
double h = pf.getImageableHeight ();
int xo = (int) pf.getImageableX ();
int yo = (int) pf.getImageableY ();
Rectangle2D r = new Rectangle2D.Double (xo, yo, w, h);
g2.setColor (Color.red);
g2.draw (r);
for (int x = 0; x + 32 < w; x += 36)
for (int y = 0; y + 32 < h; y += 36)
{
g2.setColor (new Color (rnd (256), rnd (256), rnd (256)));
Shape s = new Ellipse2D.Double (xo + x + 4, yo + y + 4,
32, 32);
g2.fill (s);
}
return Printable.PAGE_EXISTS;
}
int rnd (int limit)
{
return ((int) (Math.random () * limit));
}
}
class paintCover implements Printable
{
Font fnt = new Font ("TimesRoman", Font.ITALIC, 72);
public int print (Graphics g, PageFormat pf, int pageIndex)
throws PrinterException
{
Graphics2D g2 = (Graphics2D) g;
double w = pf.getImageableWidth ();
double h = pf.getImageableHeight ();
int xo = (int) pf.getImageableX ();
int yo = (int) pf.getImageableY ();
Rectangle2D r = new Rectangle2D.Double (xo, yo, w, h);
g2.setColor (Color.red);
g2.draw (r);
PrinterGraphics p = (PrinterGraphics) g2;
String s = p.getPrinterJob ().getJobName ();
int x = s.length () / 10;
g2.setFont (fnt);
int y = g2.getFont ().getSize () * 5 / 2;
g2.translate (xo + x, yo + y);
AffineTransform old = g2.getTransform ();
g2.shear (-0.95, 0.0);
g2.scale (1.0, 3.0);
g2.setPaint (Color.lightGray);
g2.drawString (s, 0, 0);
g2.setTransform (old);
g2.setPaint (Color.black);
g2.drawString (s, 0, 0);
return Printable.PAGE_EXISTS;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -