java使用PDFRenderer实现预览PDF功能

时间:2022-11-17 17:13:35

本文实例为大家分享了java使用pdfrenderer实现预览pdf功能,供大家参考,具体内容如下

需要一个jar pdfrenderer-0.9.0.jar

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
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;
 }
 }
}

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

原文链接:https://blog.csdn.net/z69183787/article/details/12616099