最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java使用PDFRenderer實現預覽PDF功能

 更新時間:2018年12月19日 11:48:37   作者:OkidoGreen  
這篇文章主要為大家詳細介紹了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;
 }
 }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • Spring:spring-webmvc和spring-web有哪些區(qū)別

    Spring:spring-webmvc和spring-web有哪些區(qū)別

    這篇文章主要介紹了Spring:spring-webmvc和spring-web有哪些區(qū)別,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • 基于Spring AOP proxyTargetClass的行為表現總結

    基于Spring AOP proxyTargetClass的行為表現總結

    這篇文章主要介紹了Spring AOP proxyTargetClass的行為表現總結,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • 在Java的Struts中判斷是否調用AJAX及用攔截器對其優(yōu)化

    在Java的Struts中判斷是否調用AJAX及用攔截器對其優(yōu)化

    這篇文章主要介紹了在Java的Struts中判斷是否調用AJAX及用攔截器對其優(yōu)化的方法,Struts框架是Java的SSH三大web開發(fā)框架之一,需要的朋友可以參考下
    2016-01-01
  • SpringBoot整合Log4j2實現自定義日志打印失效的原因及解決

    SpringBoot整合Log4j2實現自定義日志打印失效的原因及解決

    本文給大家介紹了關于SpringBoot項目整合Log4j2實現自定義日志打印失效原因及解決辦法,主要的原因是因為SpringBoot的logback包的存在,文中通過圖文給大家了詳細解決方法,需要的朋友可以參考下
    2024-01-01
  • Java 數據結構與算法系列精講之排序算法

    Java 數據結構與算法系列精講之排序算法

    排序算法是《數據結構與算法》中最基本的算法之一。排序算法可以分為內部排序和外部排序,內部排序是數據記錄在內存中進行排序,而外部排序是因排序的數據很大,一次不能容納全部的排序記錄,在排序過程中需要訪問外存
    2022-02-02
  • 對Jpa中Entity關系映射中mappedBy的全面理解

    對Jpa中Entity關系映射中mappedBy的全面理解

    這篇文章主要介紹了對Jpa中Entity關系映射中mappedBy的全面理解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Java訪問Hadoop分布式文件系統(tǒng)HDFS的配置說明

    Java訪問Hadoop分布式文件系統(tǒng)HDFS的配置說明

    Hadoop的能提供高吞吐量的數據訪問,是集群式服務器的上的數據操作利器,這里就來為大家分享Java訪問Hadoop分布式文件系統(tǒng)HDFS的配置說明:
    2016-06-06
  • SpringBoot的@GetMapping路徑匹配規(guī)則、國際化詳細教程

    SpringBoot的@GetMapping路徑匹配規(guī)則、國際化詳細教程

    這篇文章主要介紹了SpringBoot的@GetMapping路徑匹配規(guī)則、國際化,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2023-11-11
  • Java利用ffmpeg實現視頻MP4轉m3u8

    Java利用ffmpeg實現視頻MP4轉m3u8

    本文綜合了下網上教程,從ffmpeg工具轉碼,ffmpeg視頻播放,java語言操控ffmpeg轉碼,轉碼后視頻上傳阿里云oss,四個方面完整記錄下這個流程,需要的朋友可以參考下
    2024-02-02
  • spring boot Rabbit高級教程(最新推薦)

    spring boot Rabbit高級教程(最新推薦)

    RabbitMQ的消息過期是基于追溯方式來實現的,也就是說當一個消息的TTL到期以后不一定會被移除或投遞到死信交換機,而是在消息恰好處于隊首時才會被處理,本篇文章給大家介紹spring boot Rabbit高級教程,感興趣的朋友一起看看吧
    2023-10-10

最新評論

华安县| 永胜县| 潞城市| 泸溪县| 金寨县| 常宁市| 邓州市| 常宁市| 玛沁县| 昌黎县| 伊宁县| 普格县| 青州市| 陵水| 滦平县| 佛坪县| 湟源县| 永嘉县| 军事| 昭通市| 双峰县| 达孜县| 侯马市| 武宁县| 长顺县| 肃北| 九江县| 林甸县| 汶川县| 夹江县| 察雅县| 双峰县| 克山县| 苗栗县| 定安县| 调兵山市| 娄烦县| 泉州市| 额济纳旗| 潼南县| 松原市|