您的位置:首页 > 编程语言 > Java开发

java pdf转换jpg

2016-06-16 18:03 417 查看
/**
* 把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;

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java pdf转换jpg