热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

java使用PDFRenderer实现预览PDF功能

这篇文章主要为大家详细介绍了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.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;
 }
 }
}

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


推荐阅读
  • Skywalking系列博客1安装单机版 Skywalking的快速安装方法
    本文介绍了如何快速安装单机版的Skywalking,包括下载、环境需求和端口检查等步骤。同时提供了百度盘下载地址和查询端口是否被占用的命令。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
  • 本文介绍了一些Java开发项目管理工具及其配置教程,包括团队协同工具worktil,版本管理工具GitLab,自动化构建工具Jenkins,项目管理工具Maven和Maven私服Nexus,以及Mybatis的安装和代码自动生成工具。提供了相关链接供读者参考。 ... [详细]
  • 本文由编程笔记#小编为大家整理,主要介绍了StartingzookeeperFAILEDTOSTART相关的知识,希望对你有一定的参考价值。下载路径:https://ar ... [详细]
  • 本文比较了eBPF和WebAssembly作为云原生VM的特点和应用领域。eBPF作为运行在Linux内核中的轻量级代码执行沙箱,适用于网络或安全相关的任务;而WebAssembly作为图灵完备的语言,在商业应用中具有优势。同时,介绍了WebAssembly在Linux内核中运行的尝试以及基于LLVM的云原生WebAssembly编译器WasmEdge Runtime的案例,展示了WebAssembly作为原生应用程序的潜力。 ... [详细]
  • 一、Hadoop来历Hadoop的思想来源于Google在做搜索引擎的时候出现一个很大的问题就是这么多网页我如何才能以最快的速度来搜索到,由于这个问题Google发明 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文介绍了在Win10上安装WinPythonHadoop的详细步骤,包括安装Python环境、安装JDK8、安装pyspark、安装Hadoop和Spark、设置环境变量、下载winutils.exe等。同时提醒注意Hadoop版本与pyspark版本的一致性,并建议重启电脑以确保安装成功。 ... [详细]
  • 本文介绍了在Mac上搭建php环境后无法使用localhost连接mysql的问题,并通过将localhost替换为127.0.0.1或本机IP解决了该问题。文章解释了localhost和127.0.0.1的区别,指出了使用socket方式连接导致连接失败的原因。此外,还提供了相关链接供读者深入了解。 ... [详细]
  • 本文介绍了关于apache、phpmyadmin、mysql、php、emacs、path等知识点,以及如何搭建php环境。文章提供了详细的安装步骤和所需软件列表,希望能帮助读者解决与LAMP相关的技术问题。 ... [详细]
  • Android系统移植与调试之如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
    本文介绍了如何修改Android设备状态条上音量加减键在横竖屏切换时的显示与隐藏。通过修改系统文件system_bar.xml实现了该功能,并分享了解决思路和经验。 ... [详细]
  • 标题: ... [详细]
  • 本文介绍了在Windows环境下如何配置php+apache环境,包括下载php7和apache2.4、安装vc2015运行时环境、启动php7和apache2.4等步骤。希望对需要搭建php7环境的读者有一定的参考价值。摘要长度为169字。 ... [详细]
  • 本文介绍了在Linux下安装和配置Kafka的方法,包括安装JDK、下载和解压Kafka、配置Kafka的参数,以及配置Kafka的日志目录、服务器IP和日志存放路径等。同时还提供了单机配置部署的方法和zookeeper地址和端口的配置。通过实操成功的案例,帮助读者快速完成Kafka的安装和配置。 ... [详细]
author-avatar
暗恋达志_227
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有