欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java使用PDFRenderer实现预览PDF功能

程序员文章站 2024-03-02 18:52:28
本文实例为大家分享了java使用pdfrenderer实现预览pdf功能,供大家参考,具体内容如下 需要一个jar pdfrenderer-0.9.0.jar...

本文实例为大家分享了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.fileinputstream;
import java.io.filenamefilter;
import java.io.fileoutputstream;
import java.io.inputstream;
import java.io.outputstream;
import java.io.randomaccessfile;
import java.nio.bytebuffer;
import java.nio.channels.filechannel;
import java.util.arrays;
import java.util.comparator;
import javax.imageio.*;
 
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
 
import org.apache.struts2.convention.annotation.action;
import org.apache.struts2.convention.annotation.namespace;
import org.apache.struts2.convention.annotation.parentpackage;
import org.apache.struts2.convention.annotation.result;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.beans.factory.annotation.qualifier;
import org.springframework.context.annotation.scope;
import org.springframework.stereotype.component;
 
import com.sun.image.codec.jpeg.jpegcodec;
 
import com.sun.image.codec.jpeg.jpegimageencoder;
import com.sun.pdfview.pdffile;
import com.sun.pdfview.pdfpage;
import com.wonders.stpt.attach.model.vo.uploadfile;
import com.wonders.stpt.attach.service.fjshservice;
import com.wonders.stpt.usermsg.action.abstractparamaction;
 
 
 
@suppresswarnings("serial")
@parentpackage("struts-default")
@namespace(value="/attach")
@component("attachvieweraction")
@scope("prototype")
public class attachvieweraction extends abstractparamaction{
 
 private fjshservice fjshservice;
 private final int maxpage = 30; 
 
 public fjshservice getfjshservice() {
 return fjshservice;
 }
 
 @autowired(required=false)
 public void setfjshservice(@qualifier("fjshservice")fjshservice fjshservice) {
 this.fjshservice = fjshservice;
 }
 
 
 /**
 * pdf文档在线以图片格式预览.
 * 
 */
 @action(value="/pdfpreview",results={@result(name="pdf",location="/attachpreview/pdfviewer.jsp")})
 public string pdfpreview() {
 //按fileid查找出该文件的路径以及文件名.
 //该部分代码copy自附件上传组件
 
 httpservletrequest request = servletrequest;
 httpservletresponse response = servletresponse; 
 string fileid = request.getparameter("fileid");
 if("".equals(fileid) || null == fileid) {
  servletrequest.setattribute("state", "f");
  return "pdf";
 }
 
 uploadfile upfile = this.fjshservice.loadfilebyid(fileid);
 if(upfile == null) {
  servletrequest.setattribute("state", "f");
  return "pdf";
 }
 string path = upfile.getpath();   // 文件所在磁盘路径.
 string filename = upfile.getfileallname(); // 真实文件名.
 string savefilename = upfile.getsavefilename(); // 磁盘上的文件名.
 string version = upfile.getversion();
 if ("old".equals(request.getparameter("ver"))){
  if (version != null){
  savefilename = savefilename.replace(".dat","_v"+version+".dat");
  }
 }
 
 //当前应用绝对路径
 string apppath = request.getsession().getservletcontext().getrealpath ("");
   string imagesavepath = apppath + "\\preview_images\\";
   
 //按照文件路径读取pdf文档,并将其按页转换为图片
 
 string filepath = path + savefilename ; 
 if(filepath == null || "".equals(filepath)) {
  servletrequest.setattribute("state", "f");
  return "pdf";
 }else {
  pdffile pdffile = this.getpdffile(filepath);
  if(this.pdf2images(pdffile,imagesavepath,string.valueof(upfile.getid()))) { //如果转换成功
  return "pdf";
  }else {
  servletrequest.setattribute("state", "f");
  return "pdf";
  }   
 }  
 }
 
 /**
 * 图片文件在线预览
 * 
 */
 @action(value="/imagepreview",results={@result(name="image",location="/attachpreview/imageviewer.jsp")})
 public string imagepreview() {
 //按fileid查找出该文件的路径以及文件名.
 //该部分代码copy自附件上传组件
 
 httpservletrequest request = servletrequest;
 httpservletresponse response = servletresponse; 
 string fileid = request.getparameter("fileid");
 if("".equals(fileid) || null == fileid) {
  servletrequest.setattribute("state", "f");
  return "image";
 }
 
 uploadfile upfile = this.fjshservice.loadfilebyid(fileid);
 if(upfile == null) {
  servletrequest.setattribute("state", "f");
  return "image";
 }
 string path = upfile.getpath();   // 文件所在磁盘路径.
 string filename = upfile.getfileallname(); // 真实文件名.
 string savefilename = upfile.getsavefilename(); // 磁盘上的文件名.
 string version = upfile.getversion();
 if ("old".equals(request.getparameter("ver"))){
  if (version != null){
  savefilename = savefilename.replace(".dat","_v"+version+".dat");
  }
 }
 
 //当前应用绝对路径
 string apppath = request.getsession().getservletcontext().getrealpath ("");
   string imagesavepath = apppath + "\\preview_images\\";
   
 //按照文件路径读取文件
 string filepath = path + savefilename ;
 if(filepath == null || "".equals(filepath)) {
  servletrequest.setattribute("state", "f");
  return "image";
 }else {
  //如果成功读取文件
  string imagename = string.valueof(upfile.getid());
  string extname = upfile.getfileextname();
  if(getimagefile(filepath,imagesavepath,imagename,extname)) {
  return "image";
  }else {
  servletrequest.setattribute("state", "f");
  return "image";
  } 
 } 
 }
 
 /**
 * image文件读取. 
 * @param filepath -- 待读取文件的路径.
 * @param imagesavepath -- 图片保存路径.
 * @param imagename -- 图片文件保存后的文件名称(包括后缀).
 * @return boolean instance.
 */
 private boolean getimagefile(string filepath,string imagesavepath,string dirname,string extname) { 
 string path = imagesavepath + dirname + "\\";
 file file = new file(path);
 if(!file.exists()){ //判断以文件名命名的文件夹是否存在.
  file.mkdirs();
 }
 
 try {
  inputstream is = new fileinputstream(filepath);  
  string imagepath = path + dirname + "." + extname;
  fileoutputstream os = new fileoutputstream(imagepath); // 输出到文件流.
  byte[] buffer = new byte[1024];
  int n = 0;
  while ((n = is.read(buffer, 0, 1024)) > 0) {
  os.write(buffer, 0, n);
  }
  os.close();
  is.close();  
 } catch (exception ex) {
  ex.printstacktrace();
  return false;
 } 
 
 servletrequest.setattribute("state", "s");
 servletrequest.setattribute("dirname", dirname);
 servletrequest.setattribute("imagename", dirname + "." + extname);
 return true;
 }
 
 /**
 * pdf文档读取. 
 * @param filepath -- 待读取pdf文件的路径.
 * @return null 或者 pdffile instance.
 */
 private pdffile getpdffile(string filepath) {
 try {
  //load a pdf file from byte buffer.
  file file = new file(filepath);
  randomaccessfile raf = new randomaccessfile(file, "r");
  filechannel channel = raf.getchannel();
  bytebuffer buf = channel.map(filechannel.mapmode.read_only, 0,
   channel.size());
  pdffile pdffile = new pdffile(buf);
 
  return pdffile;
 } catch (exception ex) {
  ex.printstacktrace();
 }
 return null;
 }
 
 /**
 * pdf文档按页转换为图片.
 * @param pdffile -- pdffile instance
 * @param imagesavepath -- 图片保存路径.
 * @param filename -- 保存图片文件夹名称.
 */ 
 private boolean pdf2images(pdffile pdffile,string imagesavepath,string filename) {
 if(pdffile == null ) { //待转换文档不存在,返回false.
  return false;
 }
 
 //将转换后图片存放于path路径下
 
 string path = imagesavepath + filename + "\\";
 file filepath = new file(path);
 if(!filepath.exists()){ //判断以文件名命名的文件夹是否存在.
  filepath.mkdirs();
 }
 
 //取得当前文件夹下的所有jpg格式的文件名.
 string[] imagenames = filepath.list(new imagefilter()); 
 if(imagenames.length == 0) { //当前文件夹下没有文件.
  //将pdf文档按页转为图片.
  string imagepath = "";
  try {
  //对转换页数进行限制,最多只转换前maxpage页.
  int pages = pdffile.getnumpages();
  if(pages > maxpage){
   pages = maxpage;
  }
  
  for (int i = 1; i <= pages; i++) {
   // draw the page to an image
   pdfpage page = pdffile.getpage(i);
   // get the width and height for the doc at the default zoom
   rectangle rect = new rectangle(0, 
        0, 
        (int) page.getbbox().getwidth(), 
        (int) page.getbbox().getheight());
   // generate the image
   image img = page.getimage(rect.width, rect.height, // width & height
       rect, // clip rect
       null, // null for the imageobserver
       true, // fill background with white
       true // block until drawing is done
       );
      
   bufferedimage tag = new bufferedimage(rect.width, 
        rect.height,
        bufferedimage.type_int_rgb);
   
   tag.getgraphics().drawimage(img, 
      0,
      0,
      rect.width,
      rect.height,
      null);
   
   
   imagepath = path + i + ".jpg";
   fileoutputstream out = new fileoutputstream(imagepath); // 输出到文件流.
   jpegimageencoder encoder = jpegcodec.createjpegencoder(out);
   encoder.encode(tag);  // jpeg编码.
   out.close();
  }  
  }catch (exception ex) {
  ex.printstacktrace();
  return false;
  }
 }
 
 //取得当前文件夹下的所有jpg格式的文件名.
 imagenames = filepath.list(new imagefilter());
 //对文件名排序.
 arrays.sort(imagenames,new filenamecomparator());
 
 servletrequest.setattribute("state", "s");
 servletrequest.setattribute("filename", filename);
 servletrequest.setattribute("imagenames", imagenames);
 
 return true;
 }
 
 //图片后缀名过滤类
 
 //图片jpg过滤器类
 class imagefilter implements filenamefilter {
  public boolean isimagefile(string filename){
   if(filename.tolowercase().endswith("jpg")) {
   return true;
   }else {
   return false;
   }  
  }
  
  public imagefilter() {}
  
  public boolean accept(file dir,string name){
  return isimagefile(name);
  }
 }
 
 //文件名称比较类
 
 class filenamecomparator implements comparator {
 public final int compare(object first, object second) {
   string[] fir = ((string)first).split("\\.");
   string[] sec = ((string)second).split("\\.");
   
   int firstpage = integer.parseint(fir[0]);
   int secondpage = integer.parseint(sec[0]);
   int diff = firstpage - secondpage;
   if (diff > 0)
   return 1;
   if (diff < 0)
   return -1;
   else
   return 0;
 }
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。