java使用renderer将pdf按页转换为图片

时间:2022-09-06 07:41:40

项目中遇到了需要把用户上传的word,execl,ppt每页截图保存。需要先用到jacob把资源转换为pdf,在通过pdf-renderer把每页截图下来。

首先下载相关jar包:下载地址

java" id="highlighter_17301">
?
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
import java.awt.image;
import java.awt.rectangle;
import java.awt.image.bufferedimage;
import java.io.file;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.randomaccessfile;
import java.lang.reflect.method;
import java.nio.mappedbytebuffer;
import java.nio.channels.filechannel;
import java.security.accesscontroller;
import java.security.privilegedaction;
//如果com.sun.image找不到,就是eclipse默认把这些受访问限制的api设成了error。只要把windows-preferences-java-complicer-errors/warnings里面的deprecated and restricted api中的forbidden references(access rules)选为warning就可以编译通过
import com.sun.image.codec.jpeg.jpegcodec;
import com.sun.image.codec.jpeg.jpegencodeparam;
import com.sun.image.codec.jpeg.jpegimageencoder;
import com.sun.pdfview.pdffile;
import com.sun.pdfview.pdfpage;
public class pdftoimage {
  
 public static void main(string[] args) {
 string instructiopath="e:/临时文件1.pdf";
 string picturepath = "e:/临时文件1/";
 changepdftoimg(instructiopath,picturepath);
 }
 
 
  public static int changepdftoimg(string instructiopath,string picturepath) {
    int countpage =0;
    try {
      //instructiopath ="d:/instructio/2015-05-16/android 4编程入门经典.pdf"
      //picturepath = "d:/instructio/picture/2015-05-16/";
       
      file file = new file(instructiopath);
      randomaccessfile raf = new randomaccessfile(file, "r");
      filechannel channel = raf.getchannel();
      mappedbytebuffer buf = channel.map(filechannel.mapmode.read_only,
          0, channel.size());
      pdffile pdffile = new pdffile(buf);
      //创建图片文件夹
      file dirfile = new file(picturepath);
        if(!dirfile.exists()){
           dirfile.mkdirs();
        }
      //获得图片页数
      countpage = pdffile.getnumpages();
      for (int i = 1; i <= pdffile.getnumpages(); i++) {
        pdfpage page = pdffile.getpage(i);
        rectangle rect = new rectangle(0, 0, ((int) page.getbbox()
            .getwidth()), ((int) page.getbbox().getheight()));
        int n = 2;
        /** 图片清晰度(n>0且n<7)【pdf放大参数】 */
        image img = page.getimage(rect.width * n, rect.height * n,
            rect, /** 放大pdf到n倍,创建图片。 */
            null, /** null for the imageobserver */
            true, /** fill background with white */
            true /** block until drawing is done */
        );
        bufferedimage tag = new bufferedimage(rect.width * n,
            rect.height * n, bufferedimage.type_int_rgb);
        tag.getgraphics().drawimage(img, 0, 0, rect.width * n,
            rect.height * n, null);
        /**
         * file imgfile = new file("d:\\work\\mybook\\filesnew\\img\\" +
         * i + ".jpg"); if(imgfile.exists()){
         * if(imgfile.createnewfile()) { system.out.println("创建图片:"+
         * "d:\\work\\mybook\\filesnew\\img\\" + i + ".jpg"); } else {
         * system.out.println("创建图片失败!"); } }
         */
        fileoutputstream out = new fileoutputstream(picturepath+"/" + i
            + ".png");
        /** 输出到文件流 */
        jpegimageencoder encoder = jpegcodec.createjpegencoder(out);
        jpegencodeparam param2 = encoder.getdefaultjpegencodeparam(tag);
        param2.setquality(1f, true);
        /** 1f~0.01f是提高生成的图片质量 */
        encoder.setjpegencodeparam(param2);
        encoder.encode(tag);
        /** jpeg编码 */
        out.close();
      }
      channel.close();
      raf.close();
      /*unmap(buf);*/  //pdf转化成图片后,释放mappedbytebuffer资源。调用unmap(buf);无效。
      /** 如果要在转图片之后删除pdf,就必须要这个关闭流和清空缓冲的方法 */
    } catch (filenotfoundexception e) {
      e.printstacktrace();
    } catch (ioexception e) {
      e.printstacktrace();
    }
    return countpage;
     
  }
 
  @suppresswarnings("unchecked")
  public static void unmap(final object buffer) {
    accesscontroller.doprivileged(new privilegedaction() {
      public object run() {
        try {
          method getcleanermethod = buffer.getclass().getmethod(
              "cleaner", new class[0]);
          getcleanermethod.setaccessible(true);
          sun.misc.cleaner cleaner = (sun.misc.cleaner) getcleanermethod
              .invoke(buffer, new object[0]);
          cleaner.clean();
        } catch (exception e) {
          e.printstacktrace();
        }
        return null;
      }
    });
  }
}

成功释放mappedbytebuffer资源

?
1
2
3
4
method m = filechannelimpl.class.getdeclaredmethod("unmap",
    mappedbytebuffer.class);
   m.setaccessible(true);
   m.invoke(filechannelimpl.class, buf);

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

原文链接:https://blog.csdn.net/papima/article/details/79078840