java pdf转换jpg

/**
* 把PDF所有页转换为JPG, 并返回所有图片的路劲集合
* @param inputFilePath
* 图片路径,具体到文件名
* @param outputFilePath
* 输出目录, 不需要文件名
* @return
* @throws IOException
*/
public static List<String> Pdf2Jpg(String inputFilePath,
String outputFilePath) throws IOException {
List<String> outputFilePathList = new ArrayList<String>();
// load a pdf from a byte buffer
File file = new File(inputFilePath);
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());

for (int i = 1; i <= pdffile.getNumPages(); i++) {
// draw the first 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);
String outputFilePath2 = outputFilePath + System.currentTimeMillis() + ".jpg";

FileOutputStream out = new FileOutputStream(outputFilePath2); // 输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // JPEG编码
out.close();
outputFilePathList.add(outputFilePath2);

}

return outputFilePathList;
}

posted @ 2016-06-15 21:46  N神3  阅读(611)  评论(0编辑  收藏  举报