3.1 打印文本

3.1.1 应用场景

假设我们需要打印一个窗体的某个文本编辑域(可能只有几行,也可能包含多页)的内容,并且每页最多打印 54 行,如何实现呢?

3.1.2 解决方法

基本思路如下:首先我们需要实现 Printable 接口,然后按照每页最多 54 行的格式计算共需要打印多少页,当打印文本的按钮被点击时,执行相应的打印动作。打印文本的具体操作可通过 Graphics2D 的 drawString 方法来实现。

1、实现 Printable 接口

  1. /*Graphic 指明打印的图形环境;PageFormat 指明打印页格式(页面大小以点为计量单位,
  2. 点为 1 英寸的 1/72,1 英寸为 25.4 毫米。A4 纸大致为 595 × 842 点);page 指明页号 */
  3. public int print(Graphics g, PageFormat pf, int page) throws PrinterException
  4. {
  5. Graphics2D g2 = (Graphics2D)g;
  6. g2.setPaint(Color.black); // 设置打印颜色为黑色
  7. if (page >= PAGES) // 当打印页号大于需要打印的总页数时,打印工作结束
  8. return Printable.NO_SUCH_PAGE;
  9. g2.translate(pf.getImageableX(), pf.getImageableY());// 转换坐标,确定打印边界
  10. drawCurrentPageText(g2, pf, page); // 打印当前页文本
  11. return Printable.PAGE_EXISTS; // 存在打印页时,继续打印工作
  12. }
  13. /* 打印指定页号的具体文本内容 */
  14. private void drawCurrentPageText(Graphics2D g2, PageFormat pf, int page)
  15. {
  16. String s = getDrawText(printStr)[page];// 获取当前页的待打印文本内容
  17. // 获取默认字体及相应的尺寸
  18. FontRenderContext context = g2.getFontRenderContext();
  19. Font f = area.getFont();
  20. String drawText;
  21. float ascent = 16; // 给定字符点阵
  22. int k, i = f.getSize(), lines = 0;
  23. while(s.length() > 0 && lines < 54) // 每页限定在 54 行以内
  24. {
  25. k = s.indexOf('\n'); // 获取每一个回车符的位置
  26. if (k != -1) // 存在回车符
  27. {
  28. lines += 1; // 计算行数
  29. drawText = s.substring(0, k); // 获取每一行文本
  30. g2.drawString(drawText, 0, ascent); // 具体打印每一行文本,同时走纸移位
  31. if (s.substring(k + 1).length() > 0)
  32. {
  33. s = s.substring(k + 1); // 截取尚未打印的文本
  34. ascent += i;
  35. }
  36. }
  37. else // 不存在回车符
  38. {
  39. lines += 1; // 计算行数
  40. drawText = s; // 获取每一行文本
  41. g2.drawString(drawText, 0, ascent); // 具体打印每一行文本,同时走纸移位
  42. s = ""; // 文本已结束
  43. }
  44. }
  45. }
  46. /* 将打印目标文本按页存放为字符串数组 */
  47. public String[] getDrawText(String s)
  48. {
  49. String[] drawText = new String[PAGES];// 根据页数初始化数组
  50. for (int i = 0; i < PAGES; i++)
  51. drawText[i] = ""; // 数组元素初始化为空字符串
  52.  
  53. int k, suffix = 0, lines = 0;
  54. while(s.length() > 0)
  55. {
  56. if(lines < 54) // 不够一页时
  57. {
  58. k = s.indexOf('\n');
  59. if (k != -1) // 存在回车符
  60. {
  61. lines += 1; // 行数累加
  62. // 计算该页的具体文本内容,存放到相应下标的数组元素
  63. drawText[suffix] = drawText[suffix] + s.substring(0, k + 1);
  64. if (s.substring(k + 1).length() > 0)
  65. s = s.substring(k + 1);
  66. }
  67. else
  68. {
  69. lines += 1; // 行数累加
  70. // 将文本内容存放到相应的数组元素
  71. drawText[suffix] = drawText[suffix] + s;
  72. s = "";
  73. }
  74. }
  75. else // 已满一页时
  76. {
  77. lines = 0; // 行数统计清零
  78. suffix++; // 数组下标加 1
  79. }
  80. }
  81. return drawText;
  82. }

2、计算需要打印的总页数

  1. public int getPagesCount(String curStr)
  2. {
  3. int page = 0;
  4. int position, count = 0;
  5. String str = curStr;
  6. while(str.length() > 0) // 文本尚未计算完毕
  7. {
  8. position = str.indexOf('\n'); // 计算回车符的位置
  9. count += 1; // 统计行数
  10. if (position != -1)
  11. str = str.substring(position + 1); // 截取尚未计算的文本
  12. else
  13. str = ""; // 文本已计算完毕
  14. }
  15. if (count > 0)
  16. page = count / 54 + 1; // 以总行数除以 54 获取总页数
  17. return page; // 返回需打印的总页数
  18. }

3.1、以 jdk1.4 以前的版本实现打印动作按钮监听,并完成具体的打印操作

  1. private void printTextAction()
  2. {
  3. printStr = area.getText().trim(); // 获取需要打印的目标文本
  4. if (printStr != null && printStr.length() > 0) // 当打印内容不为空时
  5. {
  6. PAGES = getPagesCount(printStr); // 获取打印总页数
  7. PrinterJob myPrtJob = PrinterJob.getPrinterJob(); // 获取默认打印作业
  8. PageFormat pageFormat = myPrtJob.defaultPage(); // 获取默认打印页面格式
  9. myPrtJob.setPrintable(this, pageFormat); // 设置打印工作
  10. if (myPrtJob.printDialog()) // 显示打印对话框
  11. {
  12. try
  13. {
  14. myPrtJob.print(); // 进行每一页的具体打印操作
  15. }
  16. catch(PrinterException pe)
  17. {
  18. pe.printStackTrace();
  19. }
  20. }
  21. }
  22. else
  23. {
  24. // 如果打印内容为空时,提示用户打印将取消
  25. JOptionPane.showConfirmDialog
  26. (null, "Sorry, Printer Job is Empty, Print Cancelled!", "Empty",
  27. JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
  28. }
  29. }

3.2、以 jdk1.4 新版本提供的 API 实现打印动作按钮监听,并完成具体的打印操作

  1. private void printText2Action()
  2. {
  3. printFlag = 0; // 打印标志清零
  4. printStr = area.getText().trim();// 获取需要打印的目标文本
  5. if (printStr != null && printStr.length() > 0) // 当打印内容不为空时
  6. {
  7. PAGES = getPagesCount(printStr); // 获取打印总页数
  8. // 指定打印输出格式
  9. DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
  10. // 定位默认的打印服务
  11. PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
  12. // 创建打印作业
  13. DocPrintJob job = printService.createPrintJob();
  14. // 设置打印属性
  15. PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
  16. DocAttributeSet das = new HashDocAttributeSet();
  17. // 指定打印内容
  18. Doc doc = new SimpleDoc(this, flavor, das);
  19. // 不显示打印对话框,直接进行打印工作
  20. try
  21. {
  22. job.print(doc, pras); // 进行每一页的具体打印操作
  23. }
  24. catch(PrintException pe)
  25. {
  26. pe.printStackTrace();
  27. }
  28. }
  29. else
  30. {
  31. // 如果打印内容为空时,提示用户打印将取消
  32. JOptionPane.showConfirmDialog(null, "Sorry, Printer Job is Empty, Print Cancelled!",
  33. "Empty", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
  34. }
  35. }

3.2 打印预览

3.2.1 应用场景

大多数商业应用都需要提供打印预览机制,它可以让我们在屏幕上看到页面,这样就不会因为不喜欢的打印结果而浪费纸张。 假设我们在打印上一节所说的文本之前,需要先进行打印预览。那么该怎么实现呢?

界面实现图示如下:(Next 预览下一页,Preview 预览前一页,Close 则关闭预览)

3.2.2 解决方法

基本思路:虽然 Java2 平台的打印 API 并不提供标准的打印预览对话框,但是自己来进行设计也并不复杂。正常情况下,print 方法将页面环境绘制到一个打印机图形环境上,从而实现打印。而事实上,print 方法并不能真正产生打印页面,它只是将待打印内容绘制到图形环境上。所以,我们可以忽略掉屏幕图形环境,经过适当的缩放比例,使整个打印页容纳在一个屏幕矩形里,从而实现精确的打印预览。

在打印预览的设计实现中,主要需要解决两个问题。第一,如何将打印内容按合适的比例绘制到屏幕;第二,如何实现前后翻页。下面我给出这两个问题的具体实现方法,完整的实现请参看附件中的 PrintPreviewDialog.java 文件。

  1. /* 将待打印内容按比例绘制到屏幕 */
  2. public void paintComponent(Graphics g)
  3. {
  4. super.paintComponent(g);
  5. Graphics2D g2 = (Graphics2D)g;
  6. PageFormat pf = PrinterJob.getPrinterJob().defaultPage(); // 获取页面格式
  7. double xoff; // 在屏幕上页面初始位置的水平偏移
  8. double yoff; // 在屏幕上页面初始位置的垂直偏移
  9. double scale; // 在屏幕上适合页面的比例
  10. double px = pf.getWidth(); // 页面宽度
  11. double py = pf.getHeight(); // 页面高度
  12. double sx = getWidth() - 1;
  13. double sy = getHeight() - 1;
  14. if (px / py < sx / sy)
  15. {
  16. scale = sy / py; // 计算比例
  17. xoff = 0.5 * (sx - scale * px); // 水平偏移量
  18. yoff = 0;
  19. }
  20. else
  21. {
  22. scale = sx / px; // 计算比例
  23. xoff = 0;
  24. yoff = 0.5 * (sy - scale * py); // 垂直偏移量
  25. }
  26. g2.translate((float)xoff, (float)yoff); // 转换坐标
  27. g2.scale((float)scale, (float)scale);
  28. Rectangle2D page = new Rectangle2D.Double(0, 0, px, py); // 绘制页面矩形
  29. g2.setPaint(Color.white); // 设置页面背景为白色
  30. g2.fill(page);
  31. g2.setPaint(Color.black);// 设置页面文字为黑色
  32. g2.draw(page);
  33. try
  34. {
  35. preview.print(g2, pf, currentPage); // 显示指定的预览页面
  36. }
  37. catch(PrinterException pe)
  38. {
  39. g2.draw(new Line2D.Double(0, 0, px, py));
  40. g2.draw(new Line2D.Double(0, px, 0, py));
  41. }
  42. }
  43. /* 预览指定的页面 */
  44. public void viewPage(int pos)
  45. {
  46. int newPage = currentPage + pos;
  47. // 指定页面在实际的范围内
  48. if (0 <= newPage && newPage < preview.getPagesCount(printStr))
  49. {
  50. currentPage = newPage; // 将指定页面赋值为当前页
  51. repaint();
  52. }
  53. }

这样,在按下"Next"按钮时,只需要调用 canvas.viewPage(1);而在按下"Preview"按钮时,只需要调用 canvas.viewPage(-1) 即可实现预览的前后翻页。

3.3 打印图形

3.3.1 应用场景

在实际应用中,我们还需要打印图形。譬如,我们有时需要将一个 Java Applet 的完整界面或一个应用程序窗体及其所包含的全部组件都打印出来,又应该如何实现呢?

3.3.2 解决方法

基本思路如下:在 Java 的 Component 类及其派生类中都提供了 print 和 printAll 方法,只要设置好属性就可以直接调用这两个方法,从而实现对组件及图形的打印。

  1. /* 打印指定的窗体及其包含的组件 */
  2. private void printFrameAction()
  3. {
  4. Toolkit kit = Toolkit.getDefaultToolkit(); // 获取工具箱
  5. Properties props = new Properties();
  6. props.put("awt.print.printer", "durango");// 设置打印属性
  7. props.put("awt.print.numCopies", "2");
  8. if(kit != null)
  9. {
  10. // 获取工具箱自带的打印对象
  11. PrintJob printJob = kit.getPrintJob(this, "Print Frame", props);
  12. if(printJob != null)
  13. {
  14. Graphics pg = printJob.getGraphics();// 获取打印对象的图形环境
  15. if(pg != null)
  16. {
  17. try
  18. {
  19. this.printAll(pg);// 打印该窗体及其所有的组件
  20. }
  21. finally
  22. {
  23. pg.dispose();// 注销图形环境
  24. }
  25. }
  26. printJob.end();// 结束打印作业
  27. }
  28. }
  29. }

3.4 打印文件

3.4.1 应用场景

在很多实际应用情况下,我们可能都需要打印用户指定的某一个文件。该文件可能是图形文件,如 GIF、JPEG 等等;也可能是文本文件,如 TXT、Java 文件等等;还可能是复杂的 PDF、DOC 文件等等。那么对于这样的打印需求,我们又应该如何实现呢?

3.4.2 解决方法

基本思路:在 JDK 1.4 以前的版本,要实现这样的打印功能将非常麻烦和复杂,甚至是难以想象的。但幸运的是,jdk1.4 的打印服务 API 提供了一整套的打印文件流的类和方法。利用它们,我们可以非常方便快捷地实现各式各样不同类型文件的打印功能。下面给出一个通用的处理方法。

  1. /* 打印指定的文件 */
  2. private void printFileAction()
  3. {
  4. // 构造一个文件选择器,默认为当前目录
  5. JFileChooser fileChooser = new JFileChooser(SystemProperties.USER_DIR);
  6. int state = fileChooser.showOpenDialog(this);// 弹出文件选择对话框
  7. if (state == fileChooser.APPROVE_OPTION)// 如果用户选定了文件
  8. {
  9. File file = fileChooser.getSelectedFile();// 获取选择的文件
  10. // 构建打印请求属性集
  11. PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
  12. // 设置打印格式,因为未确定文件类型,这里选择 AUTOSENSE
  13. DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
  14. // 查找所有的可用打印服务
  15. PrintService printService[] =
  16. PrintServiceLookup.lookupPrintServices(flavor, pras);
  17. // 定位默认的打印服务
  18. PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
  19. // 显示打印对话框
  20. PrintService service = ServiceUI.printDialog(null, 200, 200, printService
  21. , defaultService, flavor, pras);
  22. if (service != null)
  23. {
  24. try
  25. {
  26. DocPrintJob job = service.createPrintJob();// 创建打印作业
  27. FileInputStream fis = new FileInputStream(file);// 构造待打印的文件流
  28. DocAttributeSet das = new HashDocAttributeSet();
  29. Doc doc = new SimpleDoc(fis, flavor, das);// 建立打印文件格式
  30. job.print(doc, pras);// 进行文件的打印
  31. }
  32. catch(Exception e)
  33. {
  34. e.printStackTrace();
  35. }
  36. }
  37. }
  38. }

在上面的示例中,因尚未确定文件的类型,所以将指定文件的打印格式定义为 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

  1. package com.cn.gaopeng;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.swing.*;
  6. import java.util.Properties;
  7. import java.awt.font.FontRenderContext;
  8. import java.awt.print.*;
  9. import javax.print.*;
  10. import javax.print.attribute.*;
  11. import java.io.*;
  12.  
  13. public class PrintTest extends JFrame
  14. implements ActionListener, Printable
  15. {
  16. private JButton printTextButton = new JButton("Print Text");
  17. private JButton previewButton = new JButton("Print Preview");
  18. private JButton printText2Button = new JButton("Print Text2");
  19. private JButton printFileButton = new JButton("Print File");
  20. private JButton printFrameButton = new JButton("Print Frame");
  21. private JButton exitButton = new JButton("Exit");
  22. private JLabel tipLabel = new JLabel("");
  23. private JTextArea area = new JTextArea();
  24. private JScrollPane scroll = new JScrollPane(area);
  25. private JPanel buttonPanel = new JPanel();
  26.  
  27. private int PAGES = 0;
  28. private String printStr;
  29.  
  30. public PrintTest()
  31. {
  32. this.setTitle("Print Test");
  33. this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  34. this.setBounds((int)((SystemProperties.SCREEN_WIDTH - 800) / 2), (int)((SystemProperties.SCREEN_HEIGHT - 600) / 2), 800, 600);
  35. initLayout();
  36. }
  37.  
  38. private void initLayout()
  39. {
  40. this.getContentPane().setLayout(new BorderLayout());
  41. this.getContentPane().add(scroll, BorderLayout.CENTER);
  42. printTextButton.setMnemonic('P');
  43. printTextButton.addActionListener(this);
  44. buttonPanel.add(printTextButton);
  45. previewButton.setMnemonic('v');
  46. previewButton.addActionListener(this);
  47. buttonPanel.add(previewButton);
  48. printText2Button.setMnemonic('e');
  49. printText2Button.addActionListener(this);
  50. buttonPanel.add(printText2Button);
  51. printFileButton.setMnemonic('i');
  52. printFileButton.addActionListener(this);
  53. buttonPanel.add(printFileButton);
  54. printFrameButton.setMnemonic('F');
  55. printFrameButton.addActionListener(this);
  56. buttonPanel.add(printFrameButton);
  57. exitButton.setMnemonic('x');
  58. exitButton.addActionListener(this);
  59. buttonPanel.add(exitButton);
  60. this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
  61. }
  62.  
  63. public void actionPerformed(ActionEvent evt)
  64. {
  65. Object src = evt.getSource();
  66. if (src == printTextButton)
  67. printTextAction();
  68. else if (src == previewButton)
  69. previewAction();
  70. else if (src == printText2Button)
  71. printText2Action();
  72. else if (src == printFileButton)
  73. printFileAction();
  74. else if (src == printFrameButton)
  75. printFrameAction();
  76. else if (src == exitButton)
  77. exitApp();
  78. }
  79.  
  80. public int print(Graphics g, PageFormat pf, int page) throws PrinterException
  81. {
  82. Graphics2D g2 = (Graphics2D)g;
  83. g2.setPaint(Color.black);
  84. if (page >= PAGES)
  85. return Printable.NO_SUCH_PAGE;
  86. g2.translate(pf.getImageableX(), pf.getImageableY());
  87. drawCurrentPageText(g2, pf, page);
  88. return Printable.PAGE_EXISTS;
  89. }
  90.  
  91. private void drawCurrentPageText(Graphics2D g2, PageFormat pf, int page)
  92. {
  93. Font f = area.getFont();
  94. String s = getDrawText(printStr)[page];
  95. String drawText;
  96. float ascent = 16;
  97. int k, i = f.getSize(), lines = 0;
  98. while(s.length() > 0 && lines < 54)
  99. {
  100. k = s.indexOf('\n');
  101. if (k != -1)
  102. {
  103. lines += 1;
  104. drawText = s.substring(0, k);
  105. g2.drawString(drawText, 0, ascent);
  106. if (s.substring(k + 1).length() > 0)
  107. {
  108. s = s.substring(k + 1);
  109. ascent += i;
  110. }
  111. }
  112. else
  113. {
  114. lines += 1;
  115. drawText = s;
  116. g2.drawString(drawText, 0, ascent);
  117. s = "";
  118. }
  119. }
  120. }
  121.  
  122. public String[] getDrawText(String s)
  123. {
  124. String[] drawText = new String[PAGES];
  125. for (int i = 0; i < PAGES; i++)
  126. drawText[i] = "";
  127.  
  128. int k, suffix = 0, lines = 0;
  129. while(s.length() > 0)
  130. {
  131. if(lines < 54)
  132. {
  133. k = s.indexOf('\n');
  134. if (k != -1)
  135. {
  136. lines += 1;
  137. drawText[suffix] = drawText[suffix] + s.substring(0, k + 1);
  138. if (s.substring(k + 1).length() > 0)
  139. s = s.substring(k + 1);
  140. }
  141. else
  142. {
  143. lines += 1;
  144. drawText[suffix] = drawText[suffix] + s;
  145. s = "";
  146. }
  147. }
  148. else
  149. {
  150. lines = 0;
  151. suffix++;
  152. }
  153. }
  154. return drawText;
  155. }
  156.  
  157. public int getPagesCount(String curStr)
  158. {
  159. int page = 0;
  160. int position, count = 0;
  161. String str = curStr;
  162. while(str.length() > 0)
  163. {
  164. position = str.indexOf('\n');
  165. count += 1;
  166. if (position != -1)
  167. str = str.substring(position + 1);
  168. else
  169. str = "";
  170. }
  171.  
  172. if (count > 0)
  173. page = count / 54 + 1;
  174.  
  175. return page;
  176. }
  177.  
  178. private void printTextAction()
  179. {
  180. printStr = area.getText().trim();
  181. if (printStr != null && printStr.length() > 0)
  182. {
  183. PAGES = getPagesCount(printStr);
  184. PrinterJob myPrtJob = PrinterJob.getPrinterJob();
  185. PageFormat pageFormat = myPrtJob.defaultPage();
  186. myPrtJob.setPrintable(this, pageFormat);
  187. if (myPrtJob.printDialog())
  188. {
  189. try
  190. {
  191. myPrtJob.print();
  192. }
  193. catch(PrinterException pe)
  194. {
  195. pe.printStackTrace();
  196. }
  197. }
  198. }
  199. else
  200. {
  201. JOptionPane.showConfirmDialog(null, "Sorry, Printer Job is Empty, Print Cancelled!", "Empty"
  202. , JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
  203. }
  204. }
  205.  
  206. private void previewAction()
  207. {
  208. printStr = area.getText().trim();
  209. PAGES = getPagesCount(printStr);
  210. (new PrintPreviewDialog(this, "Print Preview", true, this, printStr)).setVisible(true);
  211. }
  212.  
  213. private void printText2Action()
  214. {
  215. printStr = area.getText().trim();
  216. if (printStr != null && printStr.length() > 0)
  217. {
  218. PAGES = getPagesCount(printStr);
  219. DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
  220. PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
  221. DocPrintJob job = printService.createPrintJob();
  222. PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
  223. DocAttributeSet das = new HashDocAttributeSet();
  224. Doc doc = new SimpleDoc(this, flavor, das);
  225.  
  226. try
  227. {
  228. job.print(doc, pras);
  229. }
  230. catch(PrintException pe)
  231. {
  232. pe.printStackTrace();
  233. }
  234. }
  235. else
  236. {
  237. JOptionPane.showConfirmDialog(null, "Sorry, Printer Job is Empty, Print Cancelled!", "Empty"
  238. , JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
  239. }
  240. }
  241.  
  242. private void printFileAction()
  243. {
  244. JFileChooser fileChooser = new JFileChooser(SystemProperties.USER_DIR);
  245. int state = fileChooser.showOpenDialog(this);
  246. if (state == fileChooser.APPROVE_OPTION)
  247. {
  248. File file = fileChooser.getSelectedFile();
  249. PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
  250. DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
  251. PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
  252. PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
  253. PrintService service = ServiceUI.printDialog(null, 200, 200, printService
  254. , defaultService, flavor, pras);
  255. if (service != null)
  256. {
  257. try
  258. {
  259. DocPrintJob job = service.createPrintJob();
  260. FileInputStream fis = new FileInputStream(file);
  261. DocAttributeSet das = new HashDocAttributeSet();
  262. Doc doc = new SimpleDoc(fis, flavor, das);
  263. job.print(doc, pras);
  264. }
  265. catch(Exception e)
  266. {
  267. e.printStackTrace();
  268. }
  269. }
  270. }
  271. }
  272.  
  273. private void printFrameAction()
  274. {
  275. Toolkit kit = Toolkit.getDefaultToolkit();
  276. Properties props = new Properties();
  277. props.put("awt.print.printer", "durango");
  278. props.put("awt.print.numCopies", "2");
  279. if(kit != null)
  280. {
  281. PrintJob printJob = kit.getPrintJob(this, "Print Frame", props);
  282. if(printJob != null)
  283. {
  284. Graphics pg = printJob.getGraphics();
  285. if(pg != null)
  286. {
  287. try
  288. {
  289. this.printAll(pg);
  290. }
  291. finally
  292. {
  293. pg.dispose();
  294. }
  295. }
  296. printJob.end();
  297. }
  298. }
  299. }
  300.  
  301. private void exitApp()
  302. {
  303. this.setVisible(false);
  304. this.dispose();
  305. System.exit(0);
  306. }
  307.  
  308. public static void main(String[] args)
  309. {
  310. (new PrintTest()).setVisible(true);
  311. }
  312. }

PrintPreviewDialog.java

  1. package com.cn.gaopeng;
  2.  
  3. import java.awt.event.*;
  4. import java.awt.*;
  5. import java.awt.print.*;
  6. import javax.swing.*;
  7. import java.awt.geom.*;
  8.  
  9. public class PrintPreviewDialog extends JDialog
  10. implements ActionListener
  11. {
  12. private JButton nextButton = new JButton("Next");
  13. private JButton previousButton = new JButton("Previous");
  14. private JButton closeButton = new JButton("Close");
  15. private JPanel buttonPanel = new JPanel();
  16. private PreviewCanvas canvas;
  17.  
  18. public PrintPreviewDialog(Frame parent, String title, boolean modal, PrintTest pt, String str)
  19. {
  20. super(parent, title, modal);
  21. canvas = new PreviewCanvas(pt, str);
  22. setLayout();
  23. }
  24.  
  25. private void setLayout()
  26. {
  27. this.getContentPane().setLayout(new BorderLayout());
  28. this.getContentPane().add(canvas, BorderLayout.CENTER);
  29.  
  30. nextButton.setMnemonic('N');
  31. nextButton.addActionListener(this);
  32. buttonPanel.add(nextButton);
  33. previousButton.setMnemonic('N');
  34. previousButton.addActionListener(this);
  35. buttonPanel.add(previousButton);
  36. closeButton.setMnemonic('N');
  37. closeButton.addActionListener(this);
  38. buttonPanel.add(closeButton);
  39. this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
  40. this.setBounds((int)((SystemProperties.SCREEN_WIDTH - 400) / 2), (int)((SystemProperties.SCREEN_HEIGHT - 400) / 2), 400, 400);
  41. }
  42.  
  43. public void actionPerformed(ActionEvent evt)
  44. {
  45. Object src = evt.getSource();
  46. if (src == nextButton)
  47. nextAction();
  48. else if (src == previousButton)
  49. previousAction();
  50. else if (src == closeButton)
  51. closeAction();
  52. }
  53.  
  54. private void closeAction()
  55. {
  56. this.setVisible(false);
  57. this.dispose();
  58. }
  59.  
  60. private void nextAction()
  61. {
  62. canvas.viewPage(1);
  63. }
  64.  
  65. private void previousAction()
  66. {
  67. canvas.viewPage(-1);
  68. }
  69.  
  70. class PreviewCanvas extends JPanel
  71. {
  72. private String printStr;
  73. private int currentPage = 0;
  74. private PrintTest preview;
  75.  
  76. public PreviewCanvas(PrintTest pt, String str)
  77. {
  78. printStr = str;
  79. preview = pt;
  80. }
  81.  
  82. public void paintComponent(Graphics g)
  83. {
  84. super.paintComponent(g);
  85. Graphics2D g2 = (Graphics2D)g;
  86. PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
  87.  
  88. double xoff;
  89. double yoff;
  90. double scale;
  91. double px = pf.getWidth();
  92. double py = pf.getHeight();
  93. double sx = getWidth() - 1;
  94. double sy = getHeight() - 1;
  95. if (px / py < sx / sy)
  96. {
  97. scale = sy / py;
  98. xoff = 0.5 * (sx - scale * px);
  99. yoff = 0;
  100. }
  101. else
  102. {
  103. scale = sx / px;
  104. xoff = 0;
  105. yoff = 0.5 * (sy - scale * py);
  106. }
  107. g2.translate((float)xoff, (float)yoff);
  108. g2.scale((float)scale, (float)scale);
  109.  
  110. Rectangle2D page = new Rectangle2D.Double(0, 0, px, py);
  111. g2.setPaint(Color.white);
  112. g2.fill(page);
  113. g2.setPaint(Color.black);
  114. g2.draw(page);
  115.  
  116. try
  117. {
  118. preview.print(g2, pf, currentPage);
  119. }
  120. catch(PrinterException pe)
  121. {
  122. g2.draw(new Line2D.Double(0, 0, px, py));
  123. g2.draw(new Line2D.Double(0, px, 0, py));
  124. }
  125. }
  126.  
  127. public void viewPage(int pos)
  128. {
  129. int newPage = currentPage + pos;
  130. if (0 <= newPage && newPage < preview.getPagesCount(printStr))
  131. {
  132. currentPage = newPage;
  133. repaint();
  134. }
  135. }
  136. }
  137. }

SystemProperties.java

  1. package com.cn.gaopeng;
  2.  
  3. import java.awt.Dimension;
  4. import java.awt.Font;
  5. import java.awt.GraphicsEnvironment;
  6. import java.awt.Toolkit;
  7.  
  8. public final class SystemProperties {
  9. public static final double SCREEN_WIDTH = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
  10. public static final double SCREEN_HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
  11. public static final String USER_DIR = System.getProperty("user.dir");
  12. public static final String USER_HOME = System.getProperty("user.home");
  13. public static final String USER_NAME = System.getProperty("user.name");
  14. public static final String FILE_SEPARATOR = System.getProperty("file.separator");
  15. public static final String LINE_SEPARATOR = System.getProperty("line.separator");
  16. public static final String PATH_SEPARATOR = System.getProperty("path.separator");
  17. public static final String JAVA_HOME = System.getProperty("java.home");
  18. public static final String JAVA_VENDOR = System.getProperty("java.vendor");
  19. public static final String JAVA_VENDOR_URL = System.getProperty("java.vendor.url");
  20. public static final String JAVA_VERSION = System.getProperty("java.version");
  21. public static final String JAVA_CLASS_PATH = System.getProperty("java.class.path");
  22. public static final String JAVA_CLASS_VERSION = System.getProperty("java.class.version");
  23. public static final String OS_NAME = System.getProperty("os.name");
  24. public static final String OS_ARCH = System.getProperty("os.arch");
  25. public static final String OS_VERSION = System.getProperty("os.version");
  26. public static final String[] FONT_NAME_LIST = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
  27. public static final Font[] FONT_LIST = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
  28. }
  1. PrintTest.java 包含了本文所描述的所有打印功能的实现源代码。相应的打印文本功能通过 Print Text 和 PrintText2(jdk1.4 中新的实现)按钮调用;打印文件通过 Print File 按钮调用;打印图形通过 Print Frame 按钮调用;而 Print Preview 则进行打印预览。
  2. PrintPreviewDialog.java 包含打印预览源代码,你可以通过 PrintTest 窗体中的 Print Preview 按钮来调用。

参考资料

  1. 《 Java2 核心技术 卷Ⅱ:高级特性》 机械工业出版社
  2. Java 打印服务参考文档: http://java.sun.com/j2se/1.4/docs/guide/jps/
  3. jdk1.4 API 参考文档: http://java.sun.com/j2se/1.4/docs/api/

Java 打印程序设计实例的更多相关文章

  1. 20162317袁逸灏 第八周实验报告:实验二 Java面向对象程序设计

    20162317袁逸灏 第八周实验报告:实验二 Java面向对象程序设计 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O.L.I.D原则 ...

  2. 20155303 实验二 Java面向对象程序设计

    20155303 实验二 Java面向对象程序设计 目录 一.单元测试和TDD 任务一:实现百分制成绩转成"优.良.中.及格.不及格"五级制成绩的功能 任务二:以TDD的方式研究学 ...

  3. java基础学习03(java基础程序设计)

    java基础程序设计 一.完成的目标 1. 掌握java中的数据类型划分 2. 8种基本数据类型的使用及数据类型转换 3. 位运算.运算符.表达式 4. 判断.循环语句的使用 5. break和con ...

  4. 实验二 Java面向对象程序设计

    实验二 Java面向对象程序设计 实验内容 1. 初步掌握单元测试和TDD 2. 理解并掌握面向对象三要素:封装.继承.多态 3. 初步掌握UML建模 4. 熟悉S.O.L.I.D原则 5. 了解设计 ...

  5. JAVA上百实例源码以及开源项目

    简介 笔者当初为了学习JAVA,收集了很多经典源码,源码难易程度分为初级.中级.高级等,详情看源码列表,需要的可以直接下载! 这些源码反映了那时那景笔者对未来的盲目,对代码的热情.执着,对IT的憧憬. ...

  6. 20145213《Java程序设计》实验二Java面向对象程序设计实验报告

    20145213<Java程序设计>实验二Java面向对象程序设计实验报告 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装,继承,多态 初步掌握UML建模 熟悉S.O. ...

  7. 20145206《Java程序设计》实验二Java面向对象程序设计实验报告

    20145206<Java程序设计>实验二Java面向对象程序设计实验报告 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O. ...

  8. 20145223《Java程序程序设计》第3周学习总结

    20145223 <Java程序设计>第3周学习总结 教材学习内容总结 第四章内容 1.类与对象 如何定义一个包含有几个值域(Field成员)就是需要我们定义一个类(Class),书上给的 ...

  9. 20145113 实验二 Java面向对象程序设计

    20145113 实验二 Java面向对象程序设计 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O.L.I.D原则 了解设计模式 1.初 ...

随机推荐

  1. JEECG中的validform验证ajaxurl的使用方法

    validform验证是一种非常方便的,实用的验证方式 对于需要验证后台数据的,validform是一个非常明智的选择 validform的ajaxurl属性能够完美的实现:当输入完成某一输入框,就会 ...

  2. 微信小程序尝鲜一个月现状分析

    概述 曾记得在微信小程序还没有上线的时候,大家都是翘首以待.希望在张小龙,在企鹅的带领下,走出差别于原生开发的还有一条移动开发的道路,我也是一直关注着.知道1月9号,微信小程序最终对外开放了,作为第一 ...

  3. Python学习笔记_05:使用Flask+MySQL实现用户登陆注册以及增删查改操作

    前言:本文代码参考自两篇英文博客,具体来源点击文末代码链接中文档说明. (PS:代码运行Python版本为2.7.14) 运行效果: 首页: 注册页面: 登陆界面: 管理员登陆后界面: 添加.删除.修 ...

  4. Semaphore的使用

    Semaphore也是一个线程同步的辅助类,可以维护当前访问自身的线程个数,并提供了同步机制.使用Semaphore可以控制同时访问资源的线程个数,例如,实现一个文件允许的并发访问数. Semapho ...

  5. android使用百度地图SDK获取定位信息

    本文使用Android Studio开发. 获取定位信息相对简单.我们仅仅须要例如以下几步: 第一步,注冊百度账号,在百度地图开放平台新建应用.生成API_KEY.这些就不细说了,请前往这里:titl ...

  6. flink 入门

    http://ifeve.com/flink-quick-start/ http://vinoyang.com/2016/05/02/flink-concepts/ http://wuchong.me ...

  7. 【shell】shell基础脚本合集

    1.向脚本传递参数 #!/bin/bash #功能:打印文件名与输入参数 #作者:OLIVER echo $0 #打印文件名 echo $1 #打印输入参数 执行结果: 2.在脚本中使用参数 #!/b ...

  8. 微信小程序支付源码,后台服务端代码

    作者:尹华南,来自原文地址 微信小程序支付绕坑指南 步骤 A:小程序向服务端发送商品详情.金额.openid B:服务端向微信统一下单 C:服务器收到返回信息二次签名发回给小程序 D:小程序发起支付 ...

  9. DLL中不能调用CoInitialize和CoInitializeEx

    在项目中为了用API访问Wmi Object来实现命令wmic的功能,所以得使用COM库,使用COM库之前得初始化一些东西. m_hr = CoInitializeEx(, COINIT_APARTM ...

  10. ubuntu_thunder

    Thunder 出自Ubuntu中文 File:Http://forum.ubuntu.org.cn/download/file.php?id=123020&mode=view/wine-th ...