吐槽弄了半天, iteye 的编辑器今天是有问题啊, 死活弄不好,插入不了代码,每次插入都显示到顶部,好烦
没心思好好写博客了, 直接看代码吧:
1、 引入相关的jar
<!-- PDF 转 图片 -->
<dependency>
<groupId>com.sun.pdfview</groupId>
<artifactId>pdfrenderer</artifactId>
<version>0.9.1-patched</version>
</dependency>
2、 直接运行代码
private static void PdfToJpg() throws Exception {
File file = new File("D:\\upload\\xxx.pdf"); // PDF路径
String getPdfFilePath = "D:\\upload\\img"; // 生成图片路径
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);
System.out.println("页数: " + pdffile.getNumPages());
int pageNum = pdffile.getNumPages();
for (int i = 1; i <= pageNum; i++) {
// draw the first page to an image
PDFPage page = pdffile.getPage(i);
int width = (int) page.getBBox().getWidth();
int height = (int) page.getBBox().getHeight();
System.out.println ("width:" + width);
System.out.println ("height:" + height);
// get the width and height for the doc at the default zoom
Rectangle rect = new Rectangle(0, 0, width, height);
int n = 2; //图片清晰度(n>0且n<7) pdf放大参数
// 放大pdf到n倍,创建图片
int imgW = width * n;
int imgH = height * n;
// generate the image
Image img = page.getImage(imgW, imgH, // 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(imgW, imgH,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img, 0, 0, imgW, imgH,null);
FileOutputStream out = new FileOutputStream(getPdfFilePath + File.separator + i + ".jpg"); // 输出到文件流
System.out.println("成功保存图片到 : " +getPdfFilePath+ File.separator + i + ".jpg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
// 设置图片质量
/*JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam (tag);
param.setQuality (1f, true); //1f~0.01f是提高生成的图片质量
encoder.setJPEGEncodeParam (param);*/
encoder.encode(tag); // JPEG编码
out.close();
}
}