Print Demo: Book : Print « 2D Graphics GUI « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » 2D Graphics GUI » PrintScreenshots 
Print Demo: Book
Print Demo: Book
   
/**
 @version 1.00 1999-09-11
 @author Cay Horstmann
 */

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class BookTest {
  public static void main(String[] args) {
    JFrame frame = new BookTestFrame();
    frame.show();
  }
}

class BookTestFrame extends JFrame implements ActionListener {
  public BookTestFrame() {
    setTitle("BookTest");
    setSize(300100);
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });

    Container contentPane = getContentPane();
    text = new JTextField();
    contentPane.add(text, "South");

    JPanel buttonPanel = new JPanel();

    printButton = new JButton("Print");
    buttonPanel.add(printButton);
    printButton.addActionListener(this);

    pageSetupButton = new JButton("Page setup");
    buttonPanel.add(pageSetupButton);
    pageSetupButton.addActionListener(this);

    printPreviewButton = new JButton("Print preview");
    buttonPanel.add(printPreviewButton);
    printPreviewButton.addActionListener(this);

    contentPane.add(buttonPanel, "North");
  }

  public Book makeBook() {
    if (pageFormat == null) {
      PrinterJob printJob = PrinterJob.getPrinterJob();
      pageFormat = printJob.defaultPage();
    }
    Book book = new Book();
    String message = text.getText();
    Banner banner = new Banner(message);
    int pageCount = banner.getPageCount((Graphics2DgetGraphics(),
        pageFormat);
    book.append(new CoverPage(message + " (" + pageCount + " pages)"),
        pageFormat);
    book.append(banner, pageFormat, pageCount);
    return book;
  }

  public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if (source == printButton) {
      PrinterJob printJob = PrinterJob.getPrinterJob();
      printJob.setPageable(makeBook());
      if (printJob.printDialog()) {
        try {
          printJob.print();
        catch (Exception exception) {
          JOptionPane.showMessageDialog(this, exception);
        }
      }
    else if (source == pageSetupButton) {
      PrinterJob printJob = PrinterJob.getPrinterJob();
      if (pageFormat == null)
        pageFormat = printJob.defaultPage();
      pageFormat = printJob.pageDialog(pageFormat);
    else if (source == printPreviewButton) {
      PrintPreviewDialog dialog = new PrintPreviewDialog(makeBook());
      dialog.show();
    }
  }

  private JButton printButton;

  private JButton pageSetupButton;

  private JButton printPreviewButton;

  private JTextField text;

  private PageFormat pageFormat;
}

class Banner implements Printable {
  public Banner(String m) {
    message = m;
  }

  public int getPageCount(Graphics2D g2, PageFormat pf) {
    if (message.equals(""))
      return 0;
    layoutPages(g2, pf);
    float width = scale * layout.getAdvance();
    int pages = (intMath.ceil(width / pf.getImageableWidth());
    return pages;
  }

  public int print(Graphics g, PageFormat pf, int page)
      throws PrinterException {
    Graphics2D g2 = (Graphics2Dg;
    g2.setPaint(Color.black);
    if (page > getPageCount(g2, pf))
      return Printable.NO_SUCH_PAGE;
    g2.translate(pf.getImageableX(), pf.getImageableY());

    drawPage(g2, pf, page);
    return Printable.PAGE_EXISTS;
  }

  public void layoutPages(Graphics2D g2, PageFormat pf) {
    if (message.equals(""))
      return;
    FontRenderContext context = g2.getFontRenderContext();
    Font f = new Font("Serif", Font.PLAIN, 72);
    layout = new TextLayout(message, f, context);
    float ascent = layout.getAscent();
    float descent = layout.getDescent();
    float height = ascent + descent;
    scale = (floatpf.getImageableHeight() / height;
  }

  public void drawPage(Graphics2D g2, PageFormat pf, int page) {
    if (message.equals(""))
      return;
    page--; // account for cover page
    layoutPages(g2, pf);

    drawCropMarks(g2, pf);
    g2.clip(new Rectangle2D.Double(00, pf.getImageableWidth(), pf
        .getImageableHeight()));
    g2.translate(-page * pf.getImageableWidth()0);
    g2.scale(scale, scale);
    AffineTransform transform = AffineTransform.getTranslateInstance(0,
        layout.getAscent());
    Shape outline = layout.getOutline(transform);
    g2.draw(outline);
  }

  public void drawCropMarks(Graphics2D g2, PageFormat pf) {
    final double C = 36// crop mark length = 1/2 inch
    double w = pf.getImageableWidth();
    double h = pf.getImageableHeight();
    g2.draw(new Line2D.Double(000, C));
    g2.draw(new Line2D.Double(00, C, 0));
    g2.draw(new Line2D.Double(w, 0, w, C));
    g2.draw(new Line2D.Double(w, 0, w - C, 0));
    g2.draw(new Line2D.Double(0, h, 0, h - C));
    g2.draw(new Line2D.Double(0, h, C, h));
    g2.draw(new Line2D.Double(w, h, w, h - C));
    g2.draw(new Line2D.Double(w, h, w - C, h));
  }

  private String message;

  private float scale;

  private float width;

  private TextLayout layout;
}

class CoverPage implements Printable {
  public CoverPage(String t) {
    title = t;
  }

  public int print(Graphics g, PageFormat pf, int page)
      throws PrinterException {
    if (page >= 1)
      return Printable.NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2Dg;
    g2.setPaint(Color.black);
    g2.translate(pf.getImageableX(), pf.getImageableY());
    FontRenderContext context = g2.getFontRenderContext();
    Font f = g2.getFont();
    TextLayout layout = new TextLayout(title, f, context);
    float ascent = layout.getAscent();
    g2.drawString(title, 0, ascent);
    return Printable.PAGE_EXISTS;
  }

  private String title;
}

class PrintPreviewDialog extends JDialog implements ActionListener {
  public PrintPreviewDialog(Printable p, PageFormat pf, int pages) {
    Book book = new Book();
    book.append(p, pf, pages);
    layoutUI(book);
  }

  public PrintPreviewDialog(Book b) {
    layoutUI(b);
  }

  public void layoutUI(Book book) {
    setSize(200200);

    Container contentPane = getContentPane();
    canvas = new PrintPreviewCanvas(book);
    contentPane.add(canvas, "Center");

    JPanel buttonPanel = new JPanel();

    nextButton = new JButton("Next");
    buttonPanel.add(nextButton);
    nextButton.addActionListener(this);

    previousButton = new JButton("Previous");
    buttonPanel.add(previousButton);
    previousButton.addActionListener(this);

    closeButton = new JButton("Close");
    buttonPanel.add(closeButton);
    closeButton.addActionListener(this);

    contentPane.add(buttonPanel, "South");
  }

  public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if (source == nextButton) {
      canvas.flipPage(1);
    else if (source == previousButton) {
      canvas.flipPage(-1);
    else if (source == closeButton) {
      setVisible(false);
    }
  }

  private JButton nextButton;

  private JButton previousButton;

  private JButton closeButton;

  private PrintPreviewCanvas canvas;
}

class PrintPreviewCanvas extends JPanel {
  public PrintPreviewCanvas(Book b) {
    book = b;
    currentPage = 0;
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2Dg;
    PageFormat pageFormat = book.getPageFormat(currentPage);

    double xoff; // x offset of page start in window
    double yoff; // y offset of page start in window
    double scale; // scale factor to fit page in window
    double px = pageFormat.getWidth();
    double py = pageFormat.getHeight();
    double sx = getWidth() 1;
    double sy = getHeight() 1;
    if (px / py < sx / sy// center horizontally
    {
      scale = sy / py;
      xoff = 0.5 (sx - scale * px);
      yoff = 0;
    else // center vertically
    {
      scale = sx / px;
      xoff = 0;
      yoff = 0.5 (sy - scale * py);
    }
    g2.translate((floatxoff, (floatyoff);
    g2.scale((floatscale, (floatscale);

    // draw page outline (ignoring margins)
    Rectangle2D page = new Rectangle2D.Double(00, px, py);
    g2.setPaint(Color.white);
    g2.fill(page);
    g2.setPaint(Color.black);
    g2.draw(page);

    Printable printable = book.getPrintable(currentPage);
    try {
      printable.print(g2, pageFormat, currentPage);
    catch (PrinterException exception) {
      g2.draw(new Line2D.Double(00, px, py));
      g2.draw(new Line2D.Double(0, px, 0, py));
    }
  }

  public void flipPage(int by) {
    int newPage = currentPage + by;
    if (<= newPage && newPage < book.getNumberOfPages()) {
      currentPage = newPage;
      repaint();
    }
  }

  private Book book;

  private int currentPage;
}




           
         
    
    
  
Related examples in the same category
1. The Printing code which implements Printable
2. Print an Image to print directly
3. Simplest SWT Print ExampleSimplest SWT Print Example
4. Print in Java 2: PrinterJob
5. Print in Java: page format and document
6. Print in Java: Multi page
7. Print in Java 5
8. Print in Java 6
9. Simple Book for printingSimple Book for printing
10. Shapes PrintShapes Print
11. Display the print dialog and print
12. Print the printable area outlinePrint the printable area outline
13. Print the text file and print preview themPrint the text file and print preview them
14. Printable demoPrintable demo
15. Print Swing componentsPrint Swing components
16. BookBook
17. Another print demoAnother print demo
18. Book demoBook demo
19. Printing the Combined-Java 1.2-and-1.4 WayPrinting the Combined-Java 1.2-and-1.4 Way
20. Printing the Java 1.4 Way
21. Prompting for a Printer
22. Printing the Java 1.1 WayPrinting the Java 1.1 Way
23. ScribbleScribble
24. Printable Document
25. PrintFile -- Print a file named on the command linePrintFile -- Print a file named on the command line
26. Print to the standard output
27. PrintPanel is the base for an open-ended series of classesPrintPanel is the base for an open-ended series of classes
28. Print Test Print Test
29. Pageable TextPageable Text
30. The area of the printable area
31. The area of the actual page
32. Printing Pages with Different Formats
33. Setting the Orientation of a Printed Page
34. Print Dialog: change the default printer settings(default printer, number of copies, range of pages)
35. Printing to a File
36. Listening for Print Service Status Changes
37. Print Image
38. Overriding the Default Action of a JTextComponent
39. Displaying the Page Format Dialog: changes the default page format such as orientation and paper size.
40. Printable Component
41. Create PageFormats on a higher level
w__w__w___.___j___a__va__2_s___.co_m | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.