⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 printtest.java

📁 还在做的,没有写完,现上传,完整版写完后再上传
💻 JAVA
字号:
package com.szallcom.tools;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.PrintJob;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.ServiceUI;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import wf.common.SystemProperties;
public class PrintTest extends JFrame
implements ActionListener, Printable
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -3691487690403090089L;
	private JButton printTextButton = new JButton("Print Text");
    private JButton previewButton = new JButton("Print Preview");
	private JButton printText2Button = new JButton("Print Text2");
	private JButton printFileButton = new JButton("Print File");
    private JButton printFrameButton = new JButton("Print Frame");
    private JButton exitButton = new JButton("Exit");
    private JTextArea area = new JTextArea();
    private JScrollPane scroll = new JScrollPane(area);
    private JPanel buttonPanel = new JPanel();

    private int PAGES = 0;
    private String printStr;

    public PrintTest()
    {
        this.setTitle("Print Test");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setBounds((int)((SystemProperties.SCREEN_WIDTH - 800) / 2), (int)((SystemProperties.SCREEN_HEIGHT - 600) / 2), 800, 600);
        initLayout();
    }

    private void initLayout()
    {
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(scroll, BorderLayout.CENTER);
        printTextButton.setMnemonic('P');
        printTextButton.addActionListener(this);
        buttonPanel.add(printTextButton);
        previewButton.setMnemonic('v');
        previewButton.addActionListener(this);
        buttonPanel.add(previewButton);
        printText2Button.setMnemonic('e');
        printText2Button.addActionListener(this);
        buttonPanel.add(printText2Button);
        printFileButton.setMnemonic('i');
        printFileButton.addActionListener(this);
        buttonPanel.add(printFileButton);
        printFrameButton.setMnemonic('F');
        printFrameButton.addActionListener(this);
        buttonPanel.add(printFrameButton);
        exitButton.setMnemonic('x');
        exitButton.addActionListener(this);
        buttonPanel.add(exitButton);
        this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    }

    public void actionPerformed(ActionEvent evt)
    {
        Object src = evt.getSource();
        if (src == printTextButton)
            printTextAction();
        else if (src == previewButton)
            previewAction();
        else if (src == printText2Button)
            printText2Action();
        else if (src == printFileButton)
            printFileAction();
        else if (src == printFrameButton)
            printFrameAction();
        else if (src == exitButton)
            exitApp();
    }


    /**
     * @param g Graphic类型,指明打印的图形环境
     * @param pf PageFormat类型,指明打印页面格式(页面大小以点为计量单位)A4纸张大约为595*842
     * @param page 页数
     */
    public int print(Graphics g, PageFormat pf, int page) throws PrinterException
	{
        Graphics2D g2 = (Graphics2D)g;
        g2.setPaint(Color.black); //设置打印颜色为黑色
	    if (page >= PAGES)  //当打印页号大于需要打印的总页数时候,打印工作结束
	        return Printable.NO_SUCH_PAGE;
        g2.translate(pf.getImageableX(), pf.getImageableY()); //换转坐标,确定打印边界
        drawCurrentPageText(g2, pf, page); //打印当前页面文本
        return Printable.PAGE_EXISTS; //存在打印页面时候,继续打印工作
	}

    /**
     *  打印指定页号的具体文本内容
     * @param g2
     * @param pf
     * @param page
     */
    private void drawCurrentPageText(Graphics2D g2, PageFormat pf, int page)
	{
        String s = getDrawText(printStr)[page]; //获取当前页的待打印文本内容
        Font f = area.getFont(); //获取默认字体及相应尺寸
         String drawText;
        float ascent = 16;
        int k, i = f.getSize(), lines = 0;
        while(s.length() > 0 && lines < 54) //每页限定在54行以内
        {
            k = s.indexOf('\n'); //获取每一个回车符的位置
            if (k != -1)  //存在回车符
            {
                lines += 1; //计算行数
                drawText = s.substring(0, k); //获取每一行文本
                g2.drawString(drawText, 0, ascent); //打印具体每一行文本,同时移走纸张
                if (s.substring(k + 1).length() > 0) 
                {
                    s = s.substring(k + 1); //截取尚未打印的文本
                    ascent += i;
                }
            }
            else //不存在回车符
            {
                lines += 1;  //计算行数
                drawText = s; //获取每一行文本
                g2.drawString(drawText, 0, ascent); //具体打印每一行文本,同时走纸移位
                s = ""; //文本结束
            }
        }
	}

    /**
     * 
     * @param s
     * @return 将打印目标文本按页存放字符串数组中
     */
    public String[] getDrawText(String s)
    {
        String[] drawText = new String[PAGES]; //根据页数初始化数组
        for (int i = 0; i < PAGES; i++)
            drawText[i] = ""; //数组元素初始化为空字符串

        int k, suffix = 0, lines = 0;
        while(s.length() > 0)
        {
            if(lines < 54) //不够一页时候
            {
                k = s.indexOf('\n');
                if (k != -1) //存在回车符
                {
                    lines += 1; //计数累加
                    drawText[suffix] = drawText[suffix] + s.substring(0, k + 1); //计算该页的具体文本内容,存放到相应的数组元素
                    if (s.substring(k + 1).length() > 0)
                        s = s.substring(k + 1);
                }
                else
                {
                    lines += 1; //行数累加
                    drawText[suffix] = drawText[suffix] + s; // 将文本内容存放到相应的数组元素
                    s = "";
                }
            }
            else  //已满一页
            {
                lines = 0; //行数统计清零
                suffix++; //数字下标加1
            }
        }
        return drawText;
    }

    public int getPagesCount(String curStr)
	{
        int page = 0;
        int position, count = 0;
        String str = curStr;
	    while(str.length() > 0) //文本尚未计算完毕
	    {
	        position = str.indexOf('\n'); //计算回车符的位置
            count += 1; //统计行数
	        if (position != -1)
                str = str.substring(position + 1); //截取尚未计算的文本
	        else
	            str = ""; //文本已计算完毕
	    }

	    if (count > 0)
	        page = count / 54 + 1; //以总行数处以54获取总页面数

        return page; //返回需要打印的总页数
	}

    private void printTextAction()
    {
        printStr = area.getText().trim(); //获取需要打印的目标文本
        if (printStr != null && printStr.length() > 0) //当打印内容不为空时
        {
            PAGES = getPagesCount(printStr); //获取打印总页数
            PrinterJob myPrtJob = PrinterJob.getPrinterJob(); //获取默认打印作业
            PageFormat pageFormat = myPrtJob.defaultPage(); //获取默认打印页面格式
            myPrtJob.setPrintable(this, pageFormat); //设置打印工作
            if (myPrtJob.printDialog()) //显示打印对话框
            {
                try
                {
                    myPrtJob.print(); //进行每一项的具体打印操作
                }
                catch(PrinterException pe)
                {
                    pe.printStackTrace();
                }
            }
        }
        else //如果打印内容为空,提示用户取消打印
        {
            JOptionPane.showConfirmDialog(null, "Sorry, Printer Job is Empty, Print Cancelled!", "Empty"
                                        , JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
        }
    }

    private void previewAction()
    {
        printStr = area.getText().trim();
        PAGES = getPagesCount(printStr);
        (new PrintPreviewDialog(this, "Print Preview", true, this, printStr)).setVisible(true);
    }

    private void printText2Action()
    {
    	
        printStr = area.getText().trim(); //获得需要打印的目标文本
        if (printStr != null && printStr.length() > 0) //当打印内容不为空时
        {
            PAGES = getPagesCount(printStr); //获取打印总页数
            DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE; //定位默认的打印服务
            PrintService printService = PrintServiceLookup.lookupDefaultPrintService(); //创建打印作业
            DocPrintJob job = printService.createPrintJob(); //设置页面属性
            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
            DocAttributeSet das = new HashDocAttributeSet(); //指定打印内容
            Doc doc = new SimpleDoc(this, flavor, das); //不显示打印对话框,直接进行打印工作

            try
            {
                job.print(doc, pras); //进行每一页的具体打印操作
            }
            catch(PrintException pe)
            {
                pe.printStackTrace();
            }
        }
        else //如果打印为空时候,提示用户取消打印
        {
            JOptionPane.showConfirmDialog(null, "Sorry, Printer Job is Empty, Print Cancelled!", "Empty"
                                        , JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
        }
    }

    /**
     * 打印指定的文件
     *
     */
    private void printFileAction()
    {
        JFileChooser fileChooser = new JFileChooser(SystemProperties.USER_DIR); //构造一个文件选择器,默认为当前目录
         int state = fileChooser.showOpenDialog(this); //弹出文件选择对话框
        if (state == fileChooser.APPROVE_OPTION)  //如果用户选定了文件
        {
            File file = fileChooser.getSelectedFile();  //获取选择的文件
            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet(); //构建打印请求属性表
            DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;  //设置打印格式,因为未确定文件类型,故选择AUTOSENSE
            PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras); // 查找所有的可用打印服务
            PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();  //定位默认的打印服务
            PrintService service = ServiceUI.printDialog(null, 200, 200, printService  //显示对话框
                                                        , defaultService, flavor, pras);
            if (service != null)
            {
                try
                {
                    DocPrintJob job = service.createPrintJob();  // 创建打印作业
                    FileInputStream fis = new FileInputStream(file); //构造待打印的文件流
                    DocAttributeSet das = new HashDocAttributeSet(); 
                    Doc doc = new SimpleDoc(fis, flavor, das);  //建立打印文件格式
                    job.print(doc, pras); //进行文件的打印
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 打印指定的窗体及其包含的组件
     *
     */
    private void printFrameAction()
    {
        Toolkit kit = Toolkit.getDefaultToolkit(); //获取工具箱
        Properties props = new Properties();
        props.put("awt.print.printer", "durango"); //设置打印属性
        props.put("awt.print.numCopies", "2");
        if(kit != null)
        {
            PrintJob printJob = kit.getPrintJob(this, "Print Frame", props); //获取工具箱自带的打印对象
            if(printJob != null)
            {
                Graphics pg = printJob.getGraphics();  //获取打印对象的图像的图形环境
                if(pg != null)
                {
					try
					{
                        this.printAll(pg);  //打印该窗体及其所有的组件
                    }
                    finally
                    {
                        pg.dispose();  //注销图形环境
                    }
                }
                printJob.end();  //结束打印作业
            }
        }
    }

    private void exitApp()
    {
        this.setVisible(false);
        this.dispose();
        System.exit(0);
    }

    public static void main(String[] args)
    {
        (new PrintTest()).setVisible(true);
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -