Java 打印程序设计实例
3.1 打印文本
3.1.1 应用场景
假设我们需要打印一个窗体的某个文本编辑域(可能只有几行,也可能包含多页)的内容,并且每页最多打印 54 行,如何实现呢?
3.1.2 解决方法
基本思路如下:首先我们需要实现 Printable 接口,然后按照每页最多 54 行的格式计算共需要打印多少页,当打印文本的按钮被点击时,执行相应的打印动作。打印文本的具体操作可通过 Graphics2D 的 drawString 方法来实现。
1、实现 Printable 接口
- /*Graphic 指明打印的图形环境;PageFormat 指明打印页格式(页面大小以点为计量单位,
- 点为 1 英寸的 1/72,1 英寸为 25.4 毫米。A4 纸大致为 595 × 842 点);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; // 存在打印页时,继续打印工作
- }
- /* 打印指定页号的具体文本内容 */
- private void drawCurrentPageText(Graphics2D g2, PageFormat pf, int page)
- {
- String s = getDrawText(printStr)[page];// 获取当前页的待打印文本内容
- // 获取默认字体及相应的尺寸
- FontRenderContext context = g2.getFontRenderContext();
- 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 = ""; // 文本已结束
- }
- }
- }
- /* 将打印目标文本按页存放为字符串数组 */
- 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;
- }
2、计算需要打印的总页数
- 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; // 返回需打印的总页数
- }
3.1、以 jdk1.4 以前的版本实现打印动作按钮监听,并完成具体的打印操作
- 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);
- }
- }
3.2、以 jdk1.4 新版本提供的 API 实现打印动作按钮监听,并完成具体的打印操作
- private void printText2Action()
- {
- printFlag = 0; // 打印标志清零
- 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);
- }
- }
3.2 打印预览
3.2.1 应用场景
大多数商业应用都需要提供打印预览机制,它可以让我们在屏幕上看到页面,这样就不会因为不喜欢的打印结果而浪费纸张。 假设我们在打印上一节所说的文本之前,需要先进行打印预览。那么该怎么实现呢?
界面实现图示如下:(Next 预览下一页,Preview 预览前一页,Close 则关闭预览)
3.2.2 解决方法
基本思路:虽然 Java2 平台的打印 API 并不提供标准的打印预览对话框,但是自己来进行设计也并不复杂。正常情况下,print 方法将页面环境绘制到一个打印机图形环境上,从而实现打印。而事实上,print 方法并不能真正产生打印页面,它只是将待打印内容绘制到图形环境上。所以,我们可以忽略掉屏幕图形环境,经过适当的缩放比例,使整个打印页容纳在一个屏幕矩形里,从而实现精确的打印预览。
在打印预览的设计实现中,主要需要解决两个问题。第一,如何将打印内容按合适的比例绘制到屏幕;第二,如何实现前后翻页。下面我给出这两个问题的具体实现方法,完整的实现请参看附件中的 PrintPreviewDialog.java 文件。
- /* 将待打印内容按比例绘制到屏幕 */
- public void paintComponent(Graphics g)
- {
- super.paintComponent(g);
- Graphics2D g2 = (Graphics2D)g;
- PageFormat pf = PrinterJob.getPrinterJob().defaultPage(); // 获取页面格式
- double xoff; // 在屏幕上页面初始位置的水平偏移
- double yoff; // 在屏幕上页面初始位置的垂直偏移
- double scale; // 在屏幕上适合页面的比例
- double px = pf.getWidth(); // 页面宽度
- double py = pf.getHeight(); // 页面高度
- double sx = getWidth() - 1;
- double sy = getHeight() - 1;
- if (px / py < sx / sy)
- {
- scale = sy / py; // 计算比例
- xoff = 0.5 * (sx - scale * px); // 水平偏移量
- yoff = 0;
- }
- else
- {
- scale = sx / px; // 计算比例
- xoff = 0;
- yoff = 0.5 * (sy - scale * py); // 垂直偏移量
- }
- g2.translate((float)xoff, (float)yoff); // 转换坐标
- g2.scale((float)scale, (float)scale);
- Rectangle2D page = new Rectangle2D.Double(0, 0, px, py); // 绘制页面矩形
- g2.setPaint(Color.white); // 设置页面背景为白色
- g2.fill(page);
- g2.setPaint(Color.black);// 设置页面文字为黑色
- g2.draw(page);
- try
- {
- preview.print(g2, pf, currentPage); // 显示指定的预览页面
- }
- catch(PrinterException pe)
- {
- g2.draw(new Line2D.Double(0, 0, px, py));
- g2.draw(new Line2D.Double(0, px, 0, py));
- }
- }
- /* 预览指定的页面 */
- public void viewPage(int pos)
- {
- int newPage = currentPage + pos;
- // 指定页面在实际的范围内
- if (0 <= newPage && newPage < preview.getPagesCount(printStr))
- {
- currentPage = newPage; // 将指定页面赋值为当前页
- repaint();
- }
- }
这样,在按下"Next"按钮时,只需要调用 canvas.viewPage(1);而在按下"Preview"按钮时,只需要调用 canvas.viewPage(-1) 即可实现预览的前后翻页。
3.3 打印图形
3.3.1 应用场景
在实际应用中,我们还需要打印图形。譬如,我们有时需要将一个 Java Applet 的完整界面或一个应用程序窗体及其所包含的全部组件都打印出来,又应该如何实现呢?
3.3.2 解决方法
基本思路如下:在 Java 的 Component 类及其派生类中都提供了 print 和 printAll 方法,只要设置好属性就可以直接调用这两个方法,从而实现对组件及图形的打印。
- /* 打印指定的窗体及其包含的组件 */
- 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();// 结束打印作业
- }
- }
- }
3.4 打印文件
3.4.1 应用场景
在很多实际应用情况下,我们可能都需要打印用户指定的某一个文件。该文件可能是图形文件,如 GIF、JPEG 等等;也可能是文本文件,如 TXT、Java 文件等等;还可能是复杂的 PDF、DOC 文件等等。那么对于这样的打印需求,我们又应该如何实现呢?
3.4.2 解决方法
基本思路:在 JDK 1.4 以前的版本,要实现这样的打印功能将非常麻烦和复杂,甚至是难以想象的。但幸运的是,jdk1.4 的打印服务 API 提供了一整套的打印文件流的类和方法。利用它们,我们可以非常方便快捷地实现各式各样不同类型文件的打印功能。下面给出一个通用的处理方法。
- /* 打印指定的文件 */
- 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();
- // 设置打印格式,因为未确定文件类型,这里选择 AUTOSENSE
- DocFlavor flavor = DocFlavor.INPUT_STREAM.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();
- }
- }
- }
- }
在上面的示例中,因尚未确定文件的类型,所以将指定文件的打印格式定义为 DocFlavor.INPUT_STREAM.AUTOSENSE。事实上,如果在进行打印之前,就已确定地知道文件的格式,如为 GIF,就应定义为 DocFlavor.INPUT_STREAM.GIF ;如为 PDF,就应该定义为 DocFlavor.INPUT_STREAM.PDF;如为纯 ASCII 文件,就可以定义为 DocFlavor.INPUT_STREAM.TEXT_HTML_US_ASCII。等等。jdk1.4 的 javax.print.DocFlavor 提供了极为丰富的文件流类型,你可以根据具体的应用需求进行合适的选择。具体的 API 参考文档可见本文的参考资料 3。
完整例程源码
PrintTest.java
- package com.cn.gaopeng;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import java.util.Properties;
- import java.awt.font.FontRenderContext;
- import java.awt.print.*;
- import javax.print.*;
- import javax.print.attribute.*;
- import java.io.*;
- public class PrintTest extends JFrame
- implements ActionListener, Printable
- {
- 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 JLabel tipLabel = new JLabel("");
- 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();
- }
- 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;
- }
- private void drawCurrentPageText(Graphics2D g2, PageFormat pf, int page)
- {
- Font f = area.getFont();
- String s = getDrawText(printStr)[page];
- String drawText;
- float ascent = 16;
- int k, i = f.getSize(), lines = 0;
- while(s.length() > 0 && lines < 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 = "";
- }
- }
- }
- 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++;
- }
- }
- 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;
- 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;
- 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);
- }
- }
PrintPreviewDialog.java
- package com.cn.gaopeng;
- import java.awt.event.*;
- import java.awt.*;
- import java.awt.print.*;
- import javax.swing.*;
- import java.awt.geom.*;
- public class PrintPreviewDialog extends JDialog
- implements ActionListener
- {
- private JButton nextButton = new JButton("Next");
- private JButton previousButton = new JButton("Previous");
- private JButton closeButton = new JButton("Close");
- private JPanel buttonPanel = new JPanel();
- private PreviewCanvas canvas;
- public PrintPreviewDialog(Frame parent, String title, boolean modal, PrintTest pt, String str)
- {
- super(parent, title, modal);
- canvas = new PreviewCanvas(pt, str);
- setLayout();
- }
- private void setLayout()
- {
- this.getContentPane().setLayout(new BorderLayout());
- this.getContentPane().add(canvas, BorderLayout.CENTER);
- nextButton.setMnemonic('N');
- nextButton.addActionListener(this);
- buttonPanel.add(nextButton);
- previousButton.setMnemonic('N');
- previousButton.addActionListener(this);
- buttonPanel.add(previousButton);
- closeButton.setMnemonic('N');
- closeButton.addActionListener(this);
- buttonPanel.add(closeButton);
- this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
- this.setBounds((int)((SystemProperties.SCREEN_WIDTH - 400) / 2), (int)((SystemProperties.SCREEN_HEIGHT - 400) / 2), 400, 400);
- }
- public void actionPerformed(ActionEvent evt)
- {
- Object src = evt.getSource();
- if (src == nextButton)
- nextAction();
- else if (src == previousButton)
- previousAction();
- else if (src == closeButton)
- closeAction();
- }
- private void closeAction()
- {
- this.setVisible(false);
- this.dispose();
- }
- private void nextAction()
- {
- canvas.viewPage(1);
- }
- private void previousAction()
- {
- canvas.viewPage(-1);
- }
- class PreviewCanvas extends JPanel
- {
- private String printStr;
- private int currentPage = 0;
- private PrintTest preview;
- public PreviewCanvas(PrintTest pt, String str)
- {
- printStr = str;
- preview = pt;
- }
- public void paintComponent(Graphics g)
- {
- super.paintComponent(g);
- Graphics2D g2 = (Graphics2D)g;
- PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
- double xoff;
- double yoff;
- double scale;
- double px = pf.getWidth();
- double py = pf.getHeight();
- double sx = getWidth() - 1;
- double sy = getHeight() - 1;
- if (px / py < sx / sy)
- {
- scale = sy / py;
- xoff = 0.5 * (sx - scale * px);
- yoff = 0;
- }
- else
- {
- scale = sx / px;
- xoff = 0;
- yoff = 0.5 * (sy - scale * py);
- }
- g2.translate((float)xoff, (float)yoff);
- g2.scale((float)scale, (float)scale);
- Rectangle2D page = new Rectangle2D.Double(0, 0, px, py);
- g2.setPaint(Color.white);
- g2.fill(page);
- g2.setPaint(Color.black);
- g2.draw(page);
- try
- {
- preview.print(g2, pf, currentPage);
- }
- catch(PrinterException pe)
- {
- g2.draw(new Line2D.Double(0, 0, px, py));
- g2.draw(new Line2D.Double(0, px, 0, py));
- }
- }
- public void viewPage(int pos)
- {
- int newPage = currentPage + pos;
- if (0 <= newPage && newPage < preview.getPagesCount(printStr))
- {
- currentPage = newPage;
- repaint();
- }
- }
- }
- }
SystemProperties.java
- package com.cn.gaopeng;
- import java.awt.Dimension;
- import java.awt.Font;
- import java.awt.GraphicsEnvironment;
- import java.awt.Toolkit;
- public final class SystemProperties {
- public static final double SCREEN_WIDTH = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
- public static final double SCREEN_HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
- public static final String USER_DIR = System.getProperty("user.dir");
- public static final String USER_HOME = System.getProperty("user.home");
- public static final String USER_NAME = System.getProperty("user.name");
- public static final String FILE_SEPARATOR = System.getProperty("file.separator");
- public static final String LINE_SEPARATOR = System.getProperty("line.separator");
- public static final String PATH_SEPARATOR = System.getProperty("path.separator");
- public static final String JAVA_HOME = System.getProperty("java.home");
- public static final String JAVA_VENDOR = System.getProperty("java.vendor");
- public static final String JAVA_VENDOR_URL = System.getProperty("java.vendor.url");
- public static final String JAVA_VERSION = System.getProperty("java.version");
- public static final String JAVA_CLASS_PATH = System.getProperty("java.class.path");
- public static final String JAVA_CLASS_VERSION = System.getProperty("java.class.version");
- public static final String OS_NAME = System.getProperty("os.name");
- public static final String OS_ARCH = System.getProperty("os.arch");
- public static final String OS_VERSION = System.getProperty("os.version");
- public static final String[] FONT_NAME_LIST = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
- public static final Font[] FONT_LIST = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
- }
- PrintTest.java 包含了本文所描述的所有打印功能的实现源代码。相应的打印文本功能通过 Print Text 和 PrintText2(jdk1.4 中新的实现)按钮调用;打印文件通过 Print File 按钮调用;打印图形通过 Print Frame 按钮调用;而 Print Preview 则进行打印预览。
- PrintPreviewDialog.java 包含打印预览源代码,你可以通过 PrintTest 窗体中的 Print Preview 按钮来调用。
参考资料
- 《 Java2 核心技术 卷Ⅱ:高级特性》 机械工业出版社
- Java 打印服务参考文档: http://java.sun.com/j2se/1.4/docs/guide/jps/
- jdk1.4 API 参考文档: http://java.sun.com/j2se/1.4/docs/api/
Java 打印程序设计实例的更多相关文章
- 20162317袁逸灏 第八周实验报告:实验二 Java面向对象程序设计
20162317袁逸灏 第八周实验报告:实验二 Java面向对象程序设计 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O.L.I.D原则 ...
- 20155303 实验二 Java面向对象程序设计
20155303 实验二 Java面向对象程序设计 目录 一.单元测试和TDD 任务一:实现百分制成绩转成"优.良.中.及格.不及格"五级制成绩的功能 任务二:以TDD的方式研究学 ...
- java基础学习03(java基础程序设计)
java基础程序设计 一.完成的目标 1. 掌握java中的数据类型划分 2. 8种基本数据类型的使用及数据类型转换 3. 位运算.运算符.表达式 4. 判断.循环语句的使用 5. break和con ...
- 实验二 Java面向对象程序设计
实验二 Java面向对象程序设计 实验内容 1. 初步掌握单元测试和TDD 2. 理解并掌握面向对象三要素:封装.继承.多态 3. 初步掌握UML建模 4. 熟悉S.O.L.I.D原则 5. 了解设计 ...
- JAVA上百实例源码以及开源项目
简介 笔者当初为了学习JAVA,收集了很多经典源码,源码难易程度分为初级.中级.高级等,详情看源码列表,需要的可以直接下载! 这些源码反映了那时那景笔者对未来的盲目,对代码的热情.执着,对IT的憧憬. ...
- 20145213《Java程序设计》实验二Java面向对象程序设计实验报告
20145213<Java程序设计>实验二Java面向对象程序设计实验报告 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装,继承,多态 初步掌握UML建模 熟悉S.O. ...
- 20145206《Java程序设计》实验二Java面向对象程序设计实验报告
20145206<Java程序设计>实验二Java面向对象程序设计实验报告 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O. ...
- 20145223《Java程序程序设计》第3周学习总结
20145223 <Java程序设计>第3周学习总结 教材学习内容总结 第四章内容 1.类与对象 如何定义一个包含有几个值域(Field成员)就是需要我们定义一个类(Class),书上给的 ...
- 20145113 实验二 Java面向对象程序设计
20145113 实验二 Java面向对象程序设计 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O.L.I.D原则 了解设计模式 1.初 ...
随机推荐
- JEECG中的validform验证ajaxurl的使用方法
validform验证是一种非常方便的,实用的验证方式 对于需要验证后台数据的,validform是一个非常明智的选择 validform的ajaxurl属性能够完美的实现:当输入完成某一输入框,就会 ...
- 微信小程序尝鲜一个月现状分析
概述 曾记得在微信小程序还没有上线的时候,大家都是翘首以待.希望在张小龙,在企鹅的带领下,走出差别于原生开发的还有一条移动开发的道路,我也是一直关注着.知道1月9号,微信小程序最终对外开放了,作为第一 ...
- Python学习笔记_05:使用Flask+MySQL实现用户登陆注册以及增删查改操作
前言:本文代码参考自两篇英文博客,具体来源点击文末代码链接中文档说明. (PS:代码运行Python版本为2.7.14) 运行效果: 首页: 注册页面: 登陆界面: 管理员登陆后界面: 添加.删除.修 ...
- Semaphore的使用
Semaphore也是一个线程同步的辅助类,可以维护当前访问自身的线程个数,并提供了同步机制.使用Semaphore可以控制同时访问资源的线程个数,例如,实现一个文件允许的并发访问数. Semapho ...
- android使用百度地图SDK获取定位信息
本文使用Android Studio开发. 获取定位信息相对简单.我们仅仅须要例如以下几步: 第一步,注冊百度账号,在百度地图开放平台新建应用.生成API_KEY.这些就不细说了,请前往这里:titl ...
- flink 入门
http://ifeve.com/flink-quick-start/ http://vinoyang.com/2016/05/02/flink-concepts/ http://wuchong.me ...
- 【shell】shell基础脚本合集
1.向脚本传递参数 #!/bin/bash #功能:打印文件名与输入参数 #作者:OLIVER echo $0 #打印文件名 echo $1 #打印输入参数 执行结果: 2.在脚本中使用参数 #!/b ...
- 微信小程序支付源码,后台服务端代码
作者:尹华南,来自原文地址 微信小程序支付绕坑指南 步骤 A:小程序向服务端发送商品详情.金额.openid B:服务端向微信统一下单 C:服务器收到返回信息二次签名发回给小程序 D:小程序发起支付 ...
- DLL中不能调用CoInitialize和CoInitializeEx
在项目中为了用API访问Wmi Object来实现命令wmic的功能,所以得使用COM库,使用COM库之前得初始化一些东西. m_hr = CoInitializeEx(, COINIT_APARTM ...
- ubuntu_thunder
Thunder 出自Ubuntu中文 File:Http://forum.ubuntu.org.cn/download/file.php?id=123020&mode=view/wine-th ...