Java AWT Printable implement

Description

Java AWT Printable implement

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.swing.JComponent;

class PrintingDocuments extends JComponent implements Printable {

  @Override//from   w  w w . ja v a 2  s  . co  m
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    draw(g);
  }

  private void draw(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setBackground(Color.WHITE);
    g2d.clearRect(0, 0, getParent().getWidth(), getParent().getHeight());

    // antialising
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // Serif with drop shadow
    Font serif = new Font("Serif", Font.PLAIN, 30);
    g2d.setFont(serif);
    g2d.setPaint(new Color(50, 50, 50, 150));
    g2d.drawString("demo2s.com", 52, 52);

  }

  @Override
  public int print(Graphics g, PageFormat pgFormat, int page) throws PrinterException {
    if (page > 0) {//print only one page
      return NO_SUCH_PAGE;
    }
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(pgFormat.getImageableX(), pgFormat.getImageableY());
    draw(g2d);
    return PAGE_EXISTS;
  }

  public static void main(String[] args) {
    Printable printSurface = new PrintingDocuments();

    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(printSurface);
    boolean ok = job.printDialog();
    if (ok) {
      try {
        job.print();
      } catch (PrinterException ex) {
        ex.printStackTrace();
      }
    }
  }
}



PreviousNext

Related