SWT(JFace) 打印功能

 更新时间:2009年06月25日 12:18:53   作者:  
SWT(JFace)体验之打印功能
演示代码如下:
复制代码 代码如下:

package swt_jface.demo11;
import org.eclipse.swt.graphics.GC;
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 SimplePrint {
    Display display = new Display();
    Shell shell = new Shell(display);
    public SimplePrint() {
        shell.pack();
        shell.open();
        PrintDialog dialog = new PrintDialog(shell);
        PrinterData printerData = dialog.open();
        if(printerData != null) {
            Printer printer = new Printer(printerData);
            if(printer.startJob("Text")) {
                GC gc = new GC(printer);
                if(printer.startPage()) {
                    gc.drawString("Eclipse", 200, 200);
                    printer.endPage();
                }
                gc.dispose();
                printer.endJob();
            }
            printer.dispose();
            System.out.println("Print job done.");
        }
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();
    }
    public static void main(String[] args) {
        new SimplePrint();
    }
}

常规Main菜单加入打印按钮:
复制代码 代码如下:

package swt_jface.demo11;
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 Main {

    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 Main().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 != null) font.dispose();
        if (foregroundColor != null) foregroundColor.dispose();
        if (backgroundColor != null) backgroundColor.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(font.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(foregroundColor.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(backgroundColor.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.NULL);
        PrinterData data = dialog.open();
        if (data == null) return;
        if (data.printToFile) {
            data.fileName = "print.out";
        }

        textToPrint = text.getText();
        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")) {
            Rectangle clientArea = printer.getClientArea();
            Rectangle trim = printer.computeTrim(0, 0, 0, 0);
            Point dpi = printer.getDPI();
            leftMargin = dpi.x + trim.x;
            rightMargin = clientArea.width - dpi.x + trim.x + trim.width;
            topMargin = dpi.y + trim.y;
            bottomMargin = clientArea.height - dpi.y + trim.y + trim.height;

            int tabSize = 4;
            StringBuffer tabBuffer = new StringBuffer(tabSize);
            for (int i = 0; i < tabSize; i++) tabBuffer.append(' ');
            tabs = tabBuffer.toString();
            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);

            printText();
            printer.endJob();
            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++;
                    }
                    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) {
                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();
            }
        }
    }
}

相关文章

  • spring解决循环依赖的简单方法

    spring解决循环依赖的简单方法

    这篇文章主要给大家介绍了关于spring解决循环依赖的简单方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • 轻松掌握Java工厂模式、抽象工厂模式

    轻松掌握Java工厂模式、抽象工厂模式

    这篇文章主要帮助大家轻松掌握Java工厂模式、抽象工厂模式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-10-10
  • Java 多线程并发LockSupport

    Java 多线程并发LockSupport

    这篇文章主要介绍了Java 多线程并发LockSupport,LockSupport 类是用于创建锁和其他同步类的基本线程阻塞原语,更多相关内容需要得小伙伴可以参考一下下面文章内容
    2022-06-06
  • nacos中的配置使用@Value注解获取不到值的原因及解决方案

    nacos中的配置使用@Value注解获取不到值的原因及解决方案

    这篇文章主要介绍了nacos中的配置使用@Value注解获取不到值的原因分析,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-03-03
  • 关于JAVA_HOME路径修改之后JDK的版本依然不更改的解决办法

    关于JAVA_HOME路径修改之后JDK的版本依然不更改的解决办法

    今天小编就为大家分享一篇关于JAVA_HOME路径修改之后JDK的版本依然不更改的解决办法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-04-04
  • 解决idea 暂存文件或idea切换分支代码丢失的问题

    解决idea 暂存文件或idea切换分支代码丢失的问题

    这篇文章主要介绍了解决idea 暂存文件或idea切换分支代码丢失的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • java实现高效的枚举元素集合示例

    java实现高效的枚举元素集合示例

    Set是Java集合类的重要组成部分,它用来存储不能重复的对象。枚举类型也要求其枚举元素各不相同。看起来枚举类型和集合是很相似的。然而枚举类型中的元素不能随意的增加、删除,作为集合而言,枚举类型非常不实用。EnumSet是专门为enum实现的集合类,本实例将演示其用法
    2014-03-03
  • Android开发中Socket通信的基本实现方法讲解

    Android开发中Socket通信的基本实现方法讲解

    这篇文章主要介绍了Android开发中Socket通信的基本实现方法讲解,是安卓上移动互联网程序开发的基础,需要的朋友可以参考下
    2015-12-12
  • 在MyBatis中使用 # 和 $ 书写占位符的区别说明

    在MyBatis中使用 # 和 $ 书写占位符的区别说明

    这篇文章主要介绍了在MyBatis中使用 # 和 $ 书写占位符的区别说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-10-10
  • 分布式系统下调用链追踪技术面试题

    分布式系统下调用链追踪技术面试题

    这篇文章主要为大家介绍了分布式系统下调用链追踪技术面试问题合集,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪
    2022-03-03

最新评论