Printing Example : Print « SWT JFace Eclipse « 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 » SWT JFace Eclipse » PrintScreenshots 
Printing Example
Printing Example


/******************************************************************************
 * All Right Reserved. 
 * Copyright (c) 1998, 2004 Jackwind Li Guojie
 
 * Created on 2004-5-2 11:03:19 by JACK
 * $Id$
 
 *****************************************************************************/
/*
 * Printing example snippet: print text to printer, with word wrap and pagination
 *
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.jface.window.WindowManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.StyledTextPrintOptions;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.FontDialog;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class PrintingExample {
  
  ApplicationWindow applicationWindow;
  WindowManager manager;
  
  StyledTextPrintOptions styledTextPrintOptions;
  StyledText styledText;
  
  Display display;
  Shell shell;
  Text text;
  Font font;
  Color foregroundColor, backgroundColor;
  
  Printer printer;
  GC gc;
  Font printerFont;
  Color printerForegroundColor, printerBackgroundColor;

  int lineHeight = 0;
  int tabWidth = 0;
  int leftMargin, rightMargin, topMargin, bottomMargin;
  int x, y;
  int index, end;
  String textToPrint;
  String tabs;
  StringBuffer wordBuffer;

  public static void main(String[] args) {
    new PrintingExample().open();
  }
  
  void open() {
    display = new Display();
    font = new Font(display, "Courier"10, SWT.NORMAL);
    foregroundColor = display.getSystemColor(SWT.COLOR_BLACK);
    backgroundColor = display.getSystemColor(SWT.COLOR_WHITE);
    shell = new Shell(display);
    shell.setLayout(new FillLayout());
    shell.setText("Print Text");
    shell.setMaximized(true);
    text = new Text(shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
    text.setFont(font);
    text.setForeground(foregroundColor);
    text.setBackground(backgroundColor);
    
    Menu menuBar = new Menu(shell, SWT.BAR);
    shell.setMenuBar(menuBar);
    MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
    item.setText("&File");
    Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
    item.setMenu(fileMenu);
    item = new MenuItem(fileMenu, SWT.PUSH);
    item.setText("&Open...");
    item.setAccelerator(SWT.CTRL + 'O');
    item.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        menuOpen();
      }
    });
    item = new MenuItem(fileMenu, SWT.PUSH);
    item.setText("Font...");
    item.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        menuFont();
      }
    });
    item = new MenuItem(fileMenu, SWT.PUSH);
    item.setText("Foreground Color...");
    item.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        menuForegroundColor();
      }
    });
    item = new MenuItem(fileMenu, SWT.PUSH);
    item.setText("Background Color...");
    item.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        menuBackgroundColor();
      }
    });
    item = new MenuItem(fileMenu, SWT.PUSH);
    item.setText("&Print...");
    item.setAccelerator(SWT.CTRL + 'P');
    item.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        menuPrint();
      }
    });
    new MenuItem(fileMenu, SWT.SEPARATOR);
    item = new MenuItem(fileMenu, SWT.PUSH);
    item.setText("E&xit");
    item.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        System.exit(0);
      }
    });
    
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) display.sleep();
    }
    if (font != nullfont.dispose();
    if (foregroundColor != nullforegroundColor.dispose();
    if (backgroundColor != nullbackgroundColor.dispose();
  }
    
  void menuOpen() {
    final String textString;
    FileDialog dialog = new FileDialog(shell, SWT.OPEN);
    dialog.setFilterExtensions(new String[] {"*.java""*.*"});
    String name = dialog.open();
    if ((name == null|| (name.length() == 0)) return;
  
    try {
      File file = new File(name);
      FileInputStream stream= new FileInputStream(file.getPath());
      try {
        Reader in = new BufferedReader(new InputStreamReader(stream));
        char[] readBuffer= new char[2048];
        StringBuffer buffer= new StringBuffer((intfile.length());
        int n;
        while ((n = in.read(readBuffer)) 0) {
          buffer.append(readBuffer, 0, n);
        }
        textString = buffer.toString();
        stream.close();
      catch (IOException e) {
        MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
        box.setMessage("Error reading file:\n" + name);
        box.open();
        return;
      }
    catch (FileNotFoundException e) {
      MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
      box.setMessage("File not found:\n" + name);
      box.open();
      return;
    }  
    text.setText(textString);
  }

  void menuFont() {
    FontDialog fontDialog = new FontDialog(shell);
    fontDialog.setFontList(font.getFontData());
    FontData fontData = fontDialog.open();
    if (fontData != null) {
      if (font != nullfont.dispose();
      font = new Font(display, fontData);
      text.setFont(font);
    }
  }

  void menuForegroundColor() {
    ColorDialog colorDialog = new ColorDialog(shell);
    colorDialog.setRGB(foregroundColor.getRGB());
    RGB rgb = colorDialog.open();
    if (rgb != null) {
      if (foregroundColor != nullforegroundColor.dispose();
      foregroundColor = new Color(display, rgb);
      text.setForeground(foregroundColor);
    }
  }

  void menuBackgroundColor() {
    ColorDialog colorDialog = new ColorDialog(shell);
    colorDialog.setRGB(backgroundColor.getRGB());
    RGB rgb = colorDialog.open();
    if (rgb != null) {
      if (backgroundColor != nullbackgroundColor.dispose();
      backgroundColor = new Color(display, rgb);
      text.setBackground(backgroundColor);
    }
  }

  void menuPrint() {
    PrintDialog dialog = new PrintDialog(shell, SWT.NULL);
    PrinterData data = dialog.open();
    if (data == nullreturn;
    if (data.printToFile) {
      data.fileName = "print.out"// you probably want to ask the user for a filename
    }
    
    /* Get the text to print from the Text widget (you could get it from anywhere, i.e. your java model) */
    textToPrint = text.getText();

    /* Do the printing in a background thread so that spooling does not freeze the UI. */
    printer = new Printer(data);
    Thread printingThread = new Thread("Printing") {
      public void run() {
        print(printer);
        printer.dispose();
      }
    };
    printingThread.start();
  }
  
  void print(Printer printer) {
    if (printer.startJob("Text")) {   // the string is the job name - shows up in the printer's job list
      Rectangle clientArea = printer.getClientArea();
      Rectangle trim = printer.computeTrim(0000);
      Point dpi = printer.getDPI();
      leftMargin = dpi.x + trim.x; // one inch from left side of paper
      rightMargin = clientArea.width - dpi.x + trim.x + trim.width; // one inch from right side of paper
      topMargin = dpi.y + trim.y; // one inch from top edge of paper
      bottomMargin = clientArea.height - dpi.y + trim.y + trim.height; // one inch from bottom edge of paper
      
      /* Create a buffer for computing tab width. */
      int tabSize = 4// is tab width a user setting in your UI?
      StringBuffer tabBuffer = new StringBuffer(tabSize);
      for (int i = 0; i < tabSize; i++tabBuffer.append(' ');
      tabs = tabBuffer.toString();

      /* Create printer GC, and create and set the printer font & foreground color. */
      gc = new GC(printer);
      
      FontData fontData = font.getFontData()[0];
      printerFont = new Font(printer, fontData.getName(), fontData.getHeight(), fontData.getStyle());
      gc.setFont(printerFont);
      tabWidth = gc.stringExtent(tabs).x;
      lineHeight = gc.getFontMetrics().getHeight();
      
      RGB rgb = foregroundColor.getRGB();
      printerForegroundColor = new Color(printer, rgb);
      gc.setForeground(printerForegroundColor);
    
      rgb = backgroundColor.getRGB();
      printerBackgroundColor = new Color(printer, rgb);
      gc.setBackground(printerBackgroundColor);
    
      /* Print text to current gc using word wrap */
      printText();
      printer.endJob();

      /* Cleanup graphics resources used in printing */
      printerFont.dispose();
      printerForegroundColor.dispose();
      printerBackgroundColor.dispose();
      gc.dispose();
    }
  }
  
  void printText() {
    printer.startPage();
    wordBuffer = new StringBuffer();
    x = leftMargin;
    y = topMargin;
    index = 0;
    end = textToPrint.length();
    while (index < end) {
      char c = textToPrint.charAt(index);
      index++;
      if (c != 0) {
        if (c == 0x0a || c == 0x0d) {
          if (c == 0x0d && index < end && textToPrint.charAt(index== 0x0a) {
            index++; // if this is cr-lf, skip the lf
          }
          printWordBuffer();
          newline();
        else {
          if (c != '\t') {
            wordBuffer.append(c);
          }
          if (Character.isWhitespace(c)) {
            printWordBuffer();
            if (c == '\t') {
              x += tabWidth;
            }
          }
        }
      }
    }
    if (y + lineHeight <= bottomMargin) {
      printer.endPage();
    }
  }

  void printWordBuffer() {
    if (wordBuffer.length() 0) {
      String word = wordBuffer.toString();
      int wordWidth = gc.stringExtent(word).x;
      if (x + wordWidth > rightMargin) {
        /* word doesn't fit on current line, so wrap */
        newline();
      }
      gc.drawString(word, x, y, false);
      x += wordWidth;
      wordBuffer = new StringBuffer();
    }
  }

  void newline() {
    x = leftMargin;
    y += lineHeight;
    if (y + lineHeight > bottomMargin) {
      printer.endPage();
      if (index + end) {
        y = topMargin;
        printer.startPage();
      }
    }
  }
}
          
       
Related examples in the same category
1. Print KTable (SWT Table)Example Print KTable (SWT Table)Example
2. Simple PrintSimple Print
3. ImageViewerImageViewer
4. Demonstrates printing text
5. Demonstrates printing images
6. SWT Print and 2D GraphicsSWT Print and 2D Graphics
7. Print text to printer, with word wrap and paginationPrint text to printer, with word wrap and pagination
8. Print Hello World in black, outlined in red, to default printerPrint Hello World in black, outlined in red, to default printer
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.