Java Tutorial/SWT/Print
Содержание
17. Get the entire printable area of the page for the selected printer
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class MainClass {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
PrintDialog dlg = new PrintDialog(shell);
dlg.setScope(PrinterData.SELECTION);
PrinterData printerData = dlg.open();
if (printerData != null) {
Printer printer = new Printer(printerData);
System.out.println(printer.getClientArea());
printer.dispose();
}
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
17. Place one-inch margins on the page
If you need centimeters instead of inches, multiply each inch value by 2.54 to get the number of centimeters.
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class MainClass {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
PrintDialog dlg = new PrintDialog(shell);
dlg.setScope(PrinterData.SELECTION);
PrinterData printerData = dlg.open();
if (printerData != null) {
Printer printer = new Printer(printerData);
System.out.println(printer.getClientArea());
Point dpi = printer.getDPI(); // Get the DPI
Rectangle rect = printer.getClientArea(); // Get the printable area
Rectangle trim = printer.ruputeTrim(0, 0, 0, 0); // Get the whole page
int left = trim.x + dpi.x; // Set left margin one inch from left side of paper
int top = trim.y + dpi.y; // Set top margin
int right = (rect.width + trim.x + trim.width) - dpi.x; // 1st three
// values give
// you the right side of the page
int bottom = (rect.height + trim.y + trim.height) - dpi.y; // Set bottom
// margin
// use left, top, right, and bottom as the boundaries that govern where
// you draw on the page.
printer.dispose();
}
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
17. Print DPI
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class PrinterDPI{
public static void main (String [] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.open ();
PrinterData data = Printer.getDefaultPrinterData();
if (data == null) {
return;
}
Printer printer = new Printer(data);
if (printer.startJob("SWT Printing Snippet")) {
Rectangle trim = printer.ruputeTrim(0, 0, 0, 0);
Point dpi = printer.getDPI();
System.out.println(trim);
System.out.println(dpi);
printer.endJob();
}
printer.dispose();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose();
}
}
17. Printing
Printer, PrinterData and PrintDialog are three main classes related to Printing.
Printer descends from Device. You can create a graphical context from it and draw on the graphical context.
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.printing.Printer;
public class DrawTextToPrint {
public static void main(String[] args) {
Printer printer = new Printer();
if (printer.startJob("Printing . . .")) {
GC gc = new GC(printer);
if (printer.startPage()) {
gc.drawText("Hello, World!", 20, 20);
printer.endPage();
}
gc.dispose();
}
printer.dispose();
}
}
17. Printing Graphics
scale any images according to the printer"s DPI to fit the page.
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class MainClass {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
Image image = new Image(display, "fileName.gif");
ImageData imageData = image.getImageData();
PrintDialog dialog = new PrintDialog(shell, SWT.NULL);
PrinterData printerData = dialog.open();
Printer printer = new Printer(printerData);
Point screenDPI = display.getDPI();
Point printerDPI = printer.getDPI();
int scaleFactor = printerDPI.x / screenDPI.x;
Rectangle trim = printer.ruputeTrim(0, 0, 0, 0);
if (printer.startJob("fileName")) {
if (printer.startPage()) {
GC gc = new GC(printer);
Image printerImage = new Image(printer, imageData);
// Draw the image
gc.drawImage(printerImage, 0, 0, imageData.width, imageData.height, -trim.x, -trim.y,
scaleFactor * imageData.width, scaleFactor * imageData.height);
// Clean up
printerImage.dispose();
gc.dispose();
printer.endPage();
}
}
// End the job and dispose the printer
printer.endJob();
printer.dispose();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
17. Printing Text
- Use GC.drawString() or GC.drawText() to print text.
- wrap text on word boundaries to fit the target printer and page.
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
public class MainClass {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
PrintDialog dialog = new PrintDialog(shell);
PrinterData printerData = dialog.open();
if (printerData != null) {
// Create the printer
Printer printer = new Printer(printerData);
try {
// Print the contents of the file
new WrappingPrinter(printer).print();
} catch (Exception e) {
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setMessage(e.getMessage());
mb.open();
}
// Dispose the printer
printer.dispose();
}
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
/**
* This class performs the printing, wrapping text as necessary Code revised
* from /* The Definitive Guide to SWT and JFace by Robert Harris and Rob Warner
* Apress 2004
*/
class WrappingPrinter {
private Printer printer; // The printer
private String fileName; // The name of the file to print
private String contents; // The contents of the file to print
private GC gc; // The GC to print on
private int xPos, yPos; // The current x and y locations for print
private Rectangle bounds; // The boundaries for the print
private StringBuffer buf; // Holds a word at a time
private int lineHeight; // The height of a line of text
/**
* WrappingPrinter constructor
*
* @param printer
* the printer
* @param fileName
* the fileName
* @param contents
* the contents
*/
WrappingPrinter(Printer printer) {
this.printer = printer;
this.fileName = "yourfilename.txt";
this.contents = "long content to wrap";
}
/**
* Prints the file
*/
void print() {
// Start the print job
if (printer.startJob(fileName)) {
// Determine print area, with margins
bounds = computePrintArea(printer);
xPos = bounds.x;
yPos = bounds.y;
// Create the GC
gc = new GC(printer);
// Determine line height
lineHeight = gc.getFontMetrics().getHeight();
// Determine tab width--use three spaces for tabs
int tabWidth = gc.stringExtent(" ").x;
// Print the text
printer.startPage();
buf = new StringBuffer();
char c;
for (int i = 0, n = contents.length(); i < n; i++) {
// Get the next character
c = contents.charAt(i);
// Check for newline
if (c == "\n") {
printBuffer();
printNewline();
}
// Check for tab
else if (c == "\t") {
xPos += tabWidth;
} else {
buf.append(c);
// Check for space
if (Character.isWhitespace(c)) {
printBuffer();
}
}
}
printer.endPage();
printer.endJob();
gc.dispose();
}
}
/**
* Prints the contents of the buffer
*/
void printBuffer() {
// Get the width of the rendered buffer
int width = gc.stringExtent(buf.toString()).x;
// Determine if it fits
if (xPos + width > bounds.x + bounds.width) {
// Doesn"t fit--wrap
printNewline();
}
// Print the buffer
gc.drawString(buf.toString(), xPos, yPos, false);
xPos += width;
buf.setLength(0);
}
/**
* Prints a newline
*/
void printNewline() {
// Reset x and y locations to next line
xPos = bounds.x;
yPos += lineHeight;
// Have we gone to the next page?
if (yPos > bounds.y + bounds.height) {
yPos = bounds.y;
printer.endPage();
printer.startPage();
}
}
/**
* Computes the print area, including margins
*
* @param printer
* the printer
* @return Rectangle
*/
Rectangle computePrintArea(Printer printer) {
// Get the printable area
Rectangle rect = printer.getClientArea();
// Compute the trim
Rectangle trim = printer.ruputeTrim(0, 0, 0, 0);
// Get the printer"s DPI
Point dpi = printer.getDPI();
// Calculate the printable area, using 1 inch margins
int left = trim.x + dpi.x;
if (left < rect.x)
left = rect.x;
int right = (rect.width + trim.x + trim.width) - dpi.x;
if (right > rect.width)
right = rect.width;
int top = trim.y + dpi.y;
if (top < rect.y)
top = rect.y;
int bottom = (rect.height + trim.y + trim.height) - dpi.y;
if (bottom > rect.height)
bottom = rect.height;
return new Rectangle(left, top, right - left, bottom - top);
}
}
17. Print out String
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class StringPrint {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.open();
PrinterData data = Printer.getDefaultPrinterData();
if (data == null) {
System.out.println("Warning: No default printer.");
}
Printer printer = new Printer(data);
if (printer.startJob("SWT Printing Snippet")) {
Color black = printer.getSystemColor(SWT.COLOR_BLACK);
GC gc = new GC(printer);
if (printer.startPage()) {
gc.setForeground(black);
String testString = "Hello World!";
gc.drawString(testString, 200, 200);
printer.endPage();
}
gc.dispose();
printer.endJob();
}
printer.dispose();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
17. Print text to printer, with word wrap and pagination
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
//package org.eclipse.swt.snippets;
/*
* Printing example snippet: print text to printer, with word wrap and pagination
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/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.swt.SWT;
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 PrintTextWrapPagetation {
Display display;
Shell shell;
Text text;
Font font;
Color foregroundColor, backgroundColor;
Printer printer;
GC gc;
FontData[] printerFontData;
RGB printerForeground, printerBackground;
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 Snippet133().open();
}
void open() {
display = new Display();
shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setText("Print Text");
text = new Text(shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
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.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
if (font != null)
font.dispose();
if (foregroundColor != null)
foregroundColor.dispose();
if (backgroundColor != null)
backgroundColor.dispose();
display.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((int) file.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(text.getFont().getFontData());
FontData fontData = fontDialog.open();
if (fontData != null) {
if (font != null)
font.dispose();
font = new Font(display, fontData);
text.setFont(font);
}
}
void menuForegroundColor() {
ColorDialog colorDialog = new ColorDialog(shell);
colorDialog.setRGB(text.getForeground().getRGB());
RGB rgb = colorDialog.open();
if (rgb != null) {
if (foregroundColor != null)
foregroundColor.dispose();
foregroundColor = new Color(display, rgb);
text.setForeground(foregroundColor);
}
}
void menuBackgroundColor() {
ColorDialog colorDialog = new ColorDialog(shell);
colorDialog.setRGB(text.getBackground().getRGB());
RGB rgb = colorDialog.open();
if (rgb != null) {
if (backgroundColor != null)
backgroundColor.dispose();
backgroundColor = new Color(display, rgb);
text.setBackground(backgroundColor);
}
}
void menuPrint() {
PrintDialog dialog = new PrintDialog(shell, SWT.NONE);
PrinterData data = dialog.open();
if (data == null)
return;
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();
/* Get the font & foreground & background data. */
printerFontData = text.getFont().getFontData();
printerForeground = text.getForeground().getRGB();
printerBackground = text.getBackground().getRGB();
/*
* 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.ruputeTrim(0, 0, 0, 0);
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);
Font printerFont = new Font(printer, printerFontData);
Color printerForegroundColor = new Color(printer, printerForeground);
Color printerBackgroundColor = new Color(printer, printerBackground);
gc.setFont(printerFont);
gc.setForeground(printerForegroundColor);
gc.setBackground(printerBackgroundColor);
tabWidth = gc.stringExtent(tabs).x;
lineHeight = gc.getFontMetrics().getHeight();
/* 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 + 1 < end) {
y = topMargin;
printer.startPage();
}
}
}
}