项目中要使用PDF的缩略图,使用java几个开源项目来对pdf转换为图片的工作。
参照了文章:http://javasogo.iteye.com/blog/1169234
对比这几款开源项目PDFRenderer、pdfbox、jpedal 的做法:
1.PDFRenderer: 确实效率最高,但是缺少字体支持对大多数中文pdf处理不了(很奇怪为什么项目组还没做默认字体支持)
2.pdfbox:字体基本都可以转换,但容易内存溢出(我搞了几十M文件就不行了)
3.jpedal:效率不错。不过我这里好几个中文pdf文件就是生成缩略图不对,我还向项目组提bug了
没有办法,在目前我遇到字体解决不了情况,我寻找到了ICEPDF,这个项目也有商业和开源的。我用了开源的ICEPDF-4.2.2 (最新有4.3了),它其实用了jpedal的字体支持库,确能支持我手上的中文pdf,而且效率不错(测试没遇到内存溢出)。使用比较方便,这里把代码贴在这里:
public static final String FILETYPE_JPG = "jpg";
public static final String SUFF_IMAGE = "." + FILETYPE_JPG;
/**
* 将指定pdf文件的首页转换为指定路径的缩略图
*@param filepath 原文件路径,例如d:/test.pdf
*@param imagepath 图片生成路径,例如 d:/test-1.jpg
*@param zoom 缩略图显示倍数,1表示不缩放,0.3则缩小到30%
*/
public static void tranfer(String filepath, String imagepath, float zoom)
throws PDFException, PDFSecurityException, IOException {
// ICEpdf document class
Document document = null;
float rotation = 0f;
document = new Document();
document.setFile(filepath);
// maxPages = document.getPageTree().getNumberOfPages();
BufferedImage img = (BufferedImage) document.getPageImage(0,
GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation,
zoom);
Iterator iter = ImageIO.getImageWritersBySuffix(FILETYPE_JPG);
ImageWriter writer = (ImageWriter) iter.next();
File outFile = new File(imagepath);
FileOutputStream out = new FileOutputStream(outFile);
ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
writer.setOutput(outImage);
writer.write(new IIOImage(img, null, null));
}