• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • MsSql
  • Mysql
  • oracle
  • MariaDB
  • DB2
  • SQLite
  • PostgreSQL
  • MongoDB
  • Redis
  • Access
  • 数据库其它
  • sybase
  • HBase
您的位置:首页 > 数据库 >MsSql > Java打印和打印预览机制实例代码

Java打印和打印预览机制实例代码

作者: 字体:[增加 减小] 来源:互联网 时间:2017-05-11

通过本文主要向大家介绍了java上传图片预览,java实现打印预览,java实现word在线预览,java实现文档在线预览,java word在线预览等相关知识,希望本文的分享对您有所帮助

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

/**
 * 使用了原始的分页方式去渲染JTextArea,提供了打印预览机制。
 * <p>
 * 事实上,我们还可以通过其他方式打印JTextArea:
 * <ol>
 * <li>{@code Component.print(Graphics g);} or
 * {@code Component.printAll(Graphics g);}</li>
 * <li>{@code Component.paint(Graphics g);} or
 * {@code Component.paintAll(Graphics g);} whose rending may be slightly
 * different to the previous method (for example, <code>JFrame</code>)</li>
 * <li>{@code JTable.print();} or {@code JTextComponent.print();} provide
 * especially powerful and convenient printing mechanism</li>
 * </ol>
 *
 * @author Gaowen
 */
public class PrintUIComponent extends JPanel implements ActionListener,
  Printable {
 private static final long serialVersionUID = 4797002827940419724L;
 private static JFrame frame;
 private JTextArea textAreaToPrint;
 private PrinterJob job;
 private int[] pageBreaks;// array of page break line positions
 private String[] textLines;
 private Header header;

 public PrintUIComponent() {
  super(new BorderLayout());
  textAreaToPrint = new JTextArea(50, 20);
  for (int i = 1; i <= 50; i++) {
   textAreaToPrint.append("Line " + i + "\n");
  }
  JScrollPane scrollPane = new JScrollPane(textAreaToPrint);
  scrollPane.setPreferredSize(new Dimension(250, 200));
  add(scrollPane, BorderLayout.CENTER);
  JButton printButton = new JButton("Print This TextArea");
  printButton.setName("printButton");
  printButton.addActionListener(this);
  JButton printPreviewButton = new JButton("Print Preview");
  printPreviewButton.setName("printPreviewButton");
  printPreviewButton.addActionListener(this);
  JPanel buttonGroup = new JPanel(new GridLayout(2, 1));
  buttonGroup.add(printButton);
  buttonGroup.add(printPreviewButton);
  add(buttonGroup, BorderLayout.SOUTH);

  /* Initialize PrinterJob */
  initPrinterJob();
 }

 public static void main(String[] args) {
  SwingUtilities.invokeLater(new Runnable() {
   @Override
   public void run() {
    createAndShowGUI();
   }
  });
 }

 private static void createAndShowGUI() {
  frame = new JFrame("Print UI Example");
  frame.setContentPane(new PrintUIComponent());
  frame.pack();
  frame.setLocationRelativeTo(null);
  frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  frame.setVisible(true);
 }

 private void initTextLines() {
  Document doc = textAreaToPrint.getDocument();
  try {
   String text = doc.getText(0, doc.getLength());
   textLines = text.split("\n");
  } catch (BadLocationException e) {
   e.printStackTrace();
  }
 }

 private void initPrinterJob() {
  job = PrinterJob.getPrinterJob();
  job.setJobName("Print TextArea");// 出现在系统打印任务列表
  job.setPrintable(this);
 }

 @Override
 public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
   throws PrinterException {
  /*
   * It is safe to use a copy of this graphics as this will not involve
   * changes to it.
   */
  Graphics2D g2 = (Graphics2D) graphics.create();

  /* Calculate "pageBreaks" */
  Font font = new Font("Serif", Font.PLAIN, 12);
  FontMetrics metrics = g2.getFontMetrics(font);
  int lineHeight = metrics.getHeight();
  if (pageBreaks == null) {
   initTextLines();
   int linesPerPage = (int) (pageFormat.getImageableHeight() / lineHeight);
   int numBreaks = (textLines.length - 1) / linesPerPage;
   pageBreaks = new int[numBreaks];
   for (int b = 0; b < numBreaks; b++) {
    pageBreaks[b] = (b + 1) * linesPerPage;
   }
  }

  /* Condition to exit printing */
  if (pageIndex > pageBreaks.length) {
   return NO_SUCH_PAGE;
  }

  /* (0,0) is outside the imageable area, translate to avoid clipping */
  g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

  /* Draw each line that is on this page */
  int y = 0;
  int start = (pageIndex == 0) ? 0 : pageBreaks[pageIndex - 1];
  int end = (pageIndex == pageBreaks.length) ? textLines.length
    : pageBreaks[pageIndex];
  for (int line = start; line < end; line++) {
   y += lineHeight;
   g2.drawString(textLines[line], 0, y);
  }

  /* dispose of the graphics copy */
  g2.dispose();

  /* Tell the caller that this page is part of the printed document */
  return PAGE_EXISTS;
 }

 @Override
 public void actionPerformed(ActionEvent e) {
  Object actionEventSource = e.getSource();
  if (actionEventSource instanceof JButton) {
   JButton button = (JButton) actionEventSource;
   if (button.getName().equals("printButton")) {
    pageBreaks = null;// reset pagination
    boolean ok = job.printDialog();
    if (ok) {
     try {
      job.print();
     } catch (PrinterException ex) {
      /* The job did not successfully complete */
      ex.printStackTrace();
     }
    }
   } else if (button.getName().equals("printPreviewButton")) {
    pageBreaks = null;// reset pagination
    createAndShowPreviewDialog();
   }
&nbs

分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • Java打印和打印预览机制实例代码

相关文章

  • 2017-05-11SQL Server2008中删除重复记录的方法分享
  • 2017-05-11sql server 2008 数据库管理系统使用SQL语句创建登录用户步骤详解
  • 2017-05-11SQL Server 2008R2编写脚本时智能提示功能丢失的处理方法
  • 2017-05-11玩转-SQL2005数据库行列转换
  • 2017-05-11sqlserver2008查看表记录或者修改存储过程出现目录名无效错误解决方法
  • 2017-08-07SQL Server DATEPART() 函数
  • 2017-05-11SQL Server 2008及更高版本数据库恢复方法之日志尾部备份
  • 2017-05-11SQLServer 数据集合的交、并、差集运算
  • 2017-05-11AD域中成员服务器SQL 2008 Server安装配置图文教程
  • 2017-05-11SqlServer2005 自动备份并存储另一电脑上的存储过程函数

文章分类

  • MsSql
  • Mysql
  • oracle
  • MariaDB
  • DB2
  • SQLite
  • PostgreSQL
  • MongoDB
  • Redis
  • Access
  • 数据库其它
  • sybase
  • HBase

最近更新的内容

    • SQL Server 移动系统数据库
    • mssql2005数据库镜像搭建教程
    • SQL2005Express中导入ACCESS数据库的两种方法
    • oracle转 SQLServer
    • Sql Server 2008完全卸载方法(其他版本类似)第1/2页
    • java之File对象对文件的操作常用的几个方法(推荐)
    • SQL查询日志 查看数据库历史查询记录的方法
    • 关于SQLServer2005的学习笔记 XML的处理
    • sysservers 中找不到服务器,请执行 sp_addlinkedserver 将该服务器添加到sysserver
    • mssql 监控磁盘空间告警实现方法

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有