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();
            }
        }
    }
}

(0)

相关推荐

  • 利用WebBrowser彻底解决Web打印问题(包括后台打印)

    抱着"取之于众 服务于众"的思想,我总结了一下,把它拿到网上来与大家分享,希望能帮助遇到类似问题的朋友. 我主要使用了IE内置的WebBrowser控件,无需用户下载和安装.WebBrowser有很多功能,除打印外的其他功能就不再赘述了,你所能用到的打印功能也几乎全部可以靠它完成,下面的问题就是如何使用它了.先说显示后打印,后面说后台打印. 1.首先引入一个WebBrowser在需要打印的页面,可以直接添加: <object id="WebBrowser" c

  • js实现页面打印功能实例代码(附去页眉页脚功能代码)

    复制代码 代码如下: <html> <head></head> <style type="text/css" media="screen"> @media print{ .print {display:block;} .notPrint {display:none;} } </style> <script language="javascript"> function pre

  • javascript 打印页面代码

    复制代码 代码如下: <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>javascript打印页面</title> <script type="text/javascript"><!-- function fPrint(){ //隐藏不需要打印的内容. document.getElementById("divOperate

  • js打印纸函数代码(递归)

    复制代码 代码如下: //打印纸尺寸,单位MM //http://en.wikipedia.org/wiki/ISO_216 var page = function() { var A0 = { name: "A0", width: 841, height: 1189 }; //单位MM var B0 = { name: "B0", width: 1000, height: 1414 }; //单位MM var C0 = { name: "C0"

  • js 实现打印网页中定义的部分内容的代码

    1.在页面的代码头部处加入 JavaScript: 复制代码 代码如下: <script language=javascript> function doPrint() { bdhtml=window.document.body.innerHTML; sprnstr="<!--startprint-->"; eprnstr="<!--endprint-->"; prnhtml=bdhtml.substr(bdhtml.indexO

  • web 页面分页打印的实现

    1.首先引入一个WebBrowser在需要打印的页面,可以直接添加: 复制代码 代码如下: <object id="WebBrowser" classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2 height="0" width="0"> </object> 到页面,或者使用JavaScript在需要的时候临时添加也可以: 复制代码 代码如下: document.body.in

  • javascript 打印内容方法小结

    一般打印就用window.print();就OK了 但是一般都是选择性打印所以会调用方法: 复制代码 代码如下: function preview() { bdhtml=window.document.body.innerHTML; sprnstr="<!--startprint-->"; eprnstr="<!--endprint-->"; prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);

  • javascript 局部页面打印实现代码

    ie自带的有Active控件,但火狐不支持.这里使用的是js操作dom方法对窗体指定标记内文字进行打印,所以使用时需要定义相关的标签及其样式(文字大小.字体之类). 复制代码 代码如下: <script type="text/javascript"> ///*********************** ///打印指定区域页面 ///说明:obj–通过getElementById或其它方式获取标签标识,打印此obj内的文字 ///日期:2009-8-7 function s

  • 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

  • SWT(JFace)体验之GridLayout布局

    GridLayout布局 GridLayout 布局的功能非常强大,也是笔者常用的一种布局方式.GridLayout是网格式布局,它把父组件分成一个表格,默认情况下每个子组件占据一个单元格的空间,每个子组件按添加到父组件的顺序排列在表格中.GridLayout提供了很多的属性,可以灵活设置网格的信息.另外,GridLayout 布局提供了GridData类,子组件可以设置相应的GridData,例如 "dogPhoto.setLayoutData(gridData)",GridData

  • jQuery实现区域打印功能代码详解

    使用CSS控制打印样式,需要设置样式media="print",并且将页面中不需要打印的元素的样式display属性设置为none.如DEMO中,我将页头页脚及其他不需要打印的元素的样式设置如下: <style type="text/css" media="print"> #header,.top_title,#jqprint,#footer,#cssprint h3{display:none} </style> 用jQu

  • Web打印解决方案之普通报表打印功能

    做过很多的Web项目,大多数在打印页面内容的时候,采用的都是通过Javascript调用系统内置的打印方法进行打印,也就是调用PrintControl.ExecWB(?,?)实现直接打印和打印预览功能.打印的效果及控制性虽然不是很好,但是也能勉强使用,应付一般的打印还是可以的了. 代码如下所示: 代码 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->

  • JavaScript调用浏览器打印功能实例分析

    本文实例讲述了JavaScript调用浏览器打印功能的方法.分享给大家供大家参考.具体如下: 1. 通用型,支持IE,Firefox,Chrome... 复制代码 代码如下: window.print(); 2. 只支持IE打印: <script> var print=function(){ /** * WebBrowser.ExecWB(1,1) 打开 * Web.ExecWB(2,1) 关闭现在所有的IE窗口,并打开一个新窗口 * Web.ExecWB(4,1) 保存网页 * Web.Ex

  • JavaWeb实现打印功能

    废话不多说了,直接给大家贴代码了,具体代码如下所示: <script language="javascript"> function printsetup(){ // 打印页面设置 wb.execwb(8,1); } </script> </head> <body> <OBJECT classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2" height=0 id=w

  • 基于jQuery实现网页打印功能

    直接上代码 <!DOCTYPE html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>index</title> </head> <body> <div style="text-align:cent

  • python3+PyQt5实现文档打印功能

    本文通过Python3+PyQt5实现<python Qt Gui 快速编程>这本书13章文档打印功能.本文共通过三种方式: 1.使用HTML和QTextDOcument打印文档 2.使用QTextCusor和QTextDocument打印文档 3.使用QPainter打印文档 使用Qpainter打印文档比QTextDocument需要更操心和复杂的计算,但是QPainter确实能够对输出赋予完全控制. #!/usr/bin/env python3 import math import sy

  • JS 使用 window对象的print方法实现分页打印功能

    最近做项目用到了web在线打印功能,经研究使用了JS自身支持的Window对象的打印方法,此种方法兼容性比较好,在IE和火狐浏览器下使用都没有问题. 1.但是网上好多案例都不支持分页功能,最后通过CSS的page-break-after:always样式解决分页问题,以下代码纯个人编写,有需要的朋友可以直接复制到网页中使用,转载请注明出处,谢谢! <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" &quo

  • vue实现打印功能的两种方法

    第一种方法:通过npm 安装插件 1,安装  npm install vue-print-nb --save 2,引入  安装好以后在main.js文件中引入 import Print from 'vue-print-nb' Vue.use(Print); //注册 3,现在就可以使用了 <div id="printTest" > <p>锄禾日当午</p> <p>汗滴禾下土 </p> <p>谁知盘中餐</p&

随机推荐