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

代码如下:

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

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

private void createAndShowPreviewDialog() {
  JDialog previewDialog = new JDialog(frame, "Print Preview Dialog", true);
  JPanel contentPane = new JPanel(new BorderLayout());
  PreviewArea previewArea = new PreviewArea();
  previewArea.addMouseListener(new PreviewAreaMouseAdapter(previewArea));
  JScrollPane scrollPane = new JScrollPane(previewArea);
  contentPane.add(scrollPane, BorderLayout.CENTER);
  header = new Header(previewArea);
  contentPane.add(header, BorderLayout.NORTH);
  previewDialog.setContentPane(contentPane);
  previewDialog.setSize(600, 600);
  previewDialog
    .setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
  previewDialog.setVisible(true);
 }

private class Header extends Component {
  private static final long serialVersionUID = -1741188309769027249L;
  private PreviewArea previewArea;
  private boolean paintable;

private Header(PreviewArea previewArea) {
   this.previewArea = previewArea;
  }

private void setPaintable(boolean paintable) {
   this.paintable = paintable;
  }

@Override
  public void paint(Graphics g) {
   if (paintable) {
    g.setColor(Color.GRAY);
    g.drawString(
      String.valueOf(previewArea.getPageIndex() + 1)
        + "/"
        + String.valueOf(pageBreaks.length + 1)
        + " pages (Click left mouse button to preview next page; right to previous)",
      10, 15);
   }
  }

@Override
  public Dimension getPreferredSize() {
   return new Dimension(super.getPreferredSize().width, 20);
  }
 }

private class PreviewArea extends Component {
  private static final long serialVersionUID = -6384174997251439843L;
  private PageFormat pageFormat;
  private int pageIndex;
  private int w;
  private int h;
  private final int marginX = 10;
  private final int marginY = 20;

private PreviewArea() {
   pageFormat = job.pageDialog(job.defaultPage());
   pageIndex = 0;
   w = (int) pageFormat.getWidth();
   h = (int) pageFormat.getHeight();
  }

private int getPageIndex() {
   return pageIndex;
  }

private void setPageIndex(int pageIndex) {
   this.pageIndex = pageIndex;
  }

@Override
  public Dimension getPreferredSize() {
   return new Dimension(w + 2 * marginX, h + 2 * marginY);
  }

@Override
  public void paint(Graphics g) {
   Graphics2D g2 = (Graphics2D) g.create();
   g2.translate(marginX, marginY);
   g2.drawRect(0, 0, w, h);
   int ix = (int) (pageFormat.getImageableX() - 1);
   int iy = (int) (pageFormat.getImageableY() - 1);
   int iw = (int) (pageFormat.getImageableWidth() + 1);
   int ih = (int) (pageFormat.getImageableHeight() + 1);
   g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_ROUND,
     BasicStroke.JOIN_ROUND, 10f, new float[] { 5, 5 }, 0f));
   g2.drawRect(ix, iy, iw, ih);
   try {
    PrintUIComponent.this.print(g2, pageFormat, pageIndex);
   } catch (PrinterException e) {
    e.printStackTrace();
   }
   g2.dispose();
   header.setPaintable(true);
   header.repaint();
  }
 }

private class PreviewAreaMouseAdapter extends MouseAdapter {
  private PreviewArea previewArea;

private PreviewAreaMouseAdapter(PreviewArea previewArea) {
   this.previewArea = previewArea;
  }

@Override
  public void mouseClicked(MouseEvent e) {
   int currentIndex = previewArea.getPageIndex();
   if (e.getButton() == MouseEvent.BUTTON1) {
    /* next page */
    if (currentIndex < pageBreaks.length) {
     previewArea.setPageIndex(currentIndex + 1);
     previewArea.repaint();
    }
   } else if (e.getButton() == MouseEvent.BUTTON3) {
    /* previous page */
    if (currentIndex > 0) {
     previewArea.setPageIndex(currentIndex - 1);
     previewArea.repaint();
    }
   }
  }
 }
}

(0)

相关推荐

  • Java如何实现图片裁剪预览功能

    在项目中,我们需要做些类似头像上传,图片裁剪的功能,ok看下面文章! 需要插件:jQuery Jcrop 后端代码: package org.csg.upload; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Itera

  • java实现附件预览(openoffice+swftools+flexpaper)实例

    本文主要介绍了java实现附件预览,需要用到openoffice.SWFTools.FlexPaper,具体步骤如下: 1.概述 主要原理 1.通过第三方工具openoffice,将word.excel.ppt.txt等文件转换为pdf文件 2.通过swfTools将pdf文件转换成swf格式的文件 3.通过FlexPaper文档组件在页面上进行展示 2.安装包下载 1.openoffice是Apache下的一个开放免费的文字处理软件 下载地址:Apache oppenoffice 官网下载 版

  • uploadify java实现多文件上传和预览

    本文实例为大家分享了java文件上传和预览实现代码,供大家参考,具体内容如下 1.下载uploadify插件 2.index.html <!DOCTYPE html> <html lang="en"> <head> <@head/> <script src="<@path/>/js/uploadify-v3.1/jquery.uploadify-3.1.js"></script> &

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

    复制代码 代码如下: import java.awt.BasicStroke;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Component;import java.awt.Dimension;import java.awt.Font;import java.awt.FontMetrics;import java.awt.Graphics;import java.awt.Graphics2D;import

  • Ajax上传图片及上传前先预览功能实例代码

    手头上有几个小项目用到了easyUI,一开始决定使用easyUI就注定了项目整体上前后端分离,基本上所有的请求都采用Ajax来完成.在文件上传的时候用到了Ajax上传文件,以及图片在上传之前的预览效果,解决了这两个小问题,和小伙伴们分享下. 上传之前的预览 方式一 先来说说图片上传之前的预览问题.这里主要采用了HTML5中的FileReader对象来实现,关于FileReader对象,如果小伙伴们不了解,可以查看这篇文章HTML5学习之FileReader接口.我们来看看实现方式: <!DOCT

  • input file上传 图片预览功能实例代码

    input file上传图片预览其实很简单,只是没做过的感觉很神奇,今天我就扒下她神秘的面纱,其实原理真的很简单,下面通过一段代码大家都明白了. 具体代码如下所示: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="jquery.js"></script>

  • Java反射机制实例代码分享

    本文旨在对Java反射机制有一个全面的介绍,希望通过本文,大家会对Java反射的相关内容有一个全面的了解. 阅读本文之前,大家可先行参阅<重新理解Java泛型>. 前言 Java反射机制是一个非常强大的功能,在很多大型项目比如Spring, Mybatis都可以看见反射的身影.通过反射机制我们可以在运行期间获取对象的类型信息,利用这一特性我们可以实现工厂模式和代理模式等设计模式,同时也可以解决Java泛型擦除等令人苦恼的问题.本文我们就从实际应用的角度出发,来应用一下Java的反射机制. 反射

  • java使用PDFRenderer实现预览PDF功能

    本文实例为大家分享了java使用PDFRenderer实现预览PDF功能,供大家参考,具体内容如下 需要一个jar PDFRenderer-0.9.0.jar package com.wonders.stpt.attach.action; import java.awt.Image; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInp

  • 微信小程序wx.previewImage预览图片实例详解

    一.小知识 二.例子 1.wxml <span style="font-family:Comic Sans MS;font-size:18px;color:#333333;"><view class="container"> <view wx:for="{{imgalist}}" wx:for-item="image" class="previewimg"> <im

  • Vue实现图片预览效果实例(放大、缩小、拖拽)

    前言 这张图是显示的图片放大的一个预览情况,这里是参考预览操作实现的一个背景为黑色的部分,上层的图片可实现滚轮放大或者点击上部的放大镜图标进行放大,代码是基于Ant Design Vue框架的基础上 这里先分解部分,后面有全部代码 1.需要有黑色背景用于预览背景: 这里的背景要占满整个屏幕(这里的一般是参考其他插件预览的样式进行模拟设计的),样式在后方代码内 2.展示图片并且把图片展示到背景板最中间. 3.最重要的下方的两部分: 滚轮放大缩小图片: bbimg() { let e = e ||

  • Java实现PDF在线预览功能(四种方式)

    目录 Java实现PDF在线预览 Java快捷实现PDF在线预览 Java实现PDF在线预览 @RequestMapping("/preview1") public void er(HttpServletResponse response){ File file = new File("G:\\桌面\\Thymeleaf3.0中文翻译文档@www.java1234.com.pdf"); if (file.exists()){ byte[] data = null;

  • java Swing基础教程之图形化实例代码

    java  Swing基础教程之图形化实例代码 与多线程.泛型等不同,Swing主要在于使用. 下面主要放代码和注释,少说话. (一)基本框架 package Swing; import java.awt.*; import javax.swing.*; /** * * @author QuinnNorris * 基本框架 */ public class FrameTest { /** * @param args */ public static void main(String[] args)

  • java文件的重命名与移动操作实例代码

    文件的重命名与移动操作 有时候为了对文件进行统一访问与管理,需要把文件进行重命名,并移动到新的文件夹,如何实现呢? 一枚简单的java小程序即可实现: part_1:需求:我需要把<(E:\BaiduYun\传智播客_张孝祥_Java多线程与并发库高级应用视频教程下载)>文件夹下的所有子文件夹下的视频文件重命名,并移动到新的位置<(E:\BaiduYun\张孝祥_Java多线程与并发库)>; part_2:目录结构如下: E:\BaiduYun E:\BaiduYun\传智播客_张

随机推荐