使用的是pdfbox-2.0.2.jar
自己写的工具类(纯属记录,无技术含量):
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
public class PDFToImgUtil {
/**
* 获取PDF总页数
* @throws IOException
*/
public static int getPDFNum(String fileUrl) throws IOException {
PDDocument pdDocument = null;
int pages = 0;
try {
pdDocument = getPDDocument(fileUrl);
pages = pdDocument.getNumberOfPages();
} catch (Exception e) {
e.printStackTrace();
StringUtils.println(e.getMessage());
} finally {
if (pdDocument != null) {
pdDocument.close();
}
}
return pages;
}
//pdf全转图片
public static void PDFToImg(String url) throws FileNotFoundException, IOException {
int pages = getPDFNum(url);
for(int i=0;i<pages;i++) {
PDFToImgIndex(new FileOutputStream(new File("D:\\pdf\\pdf"+i+".jpg")), url, i, "jpg");
}
}
//pdf只转第一页
public static String PDFToImgOne(String pdfurl,String imgpath) {
String CimgPath=imgpath+System.currentTimeMillis()+".jpg";
try {
int pages = getPDFNum(pdfurl);
if(pages>=1) {
PDFToImgIndex(new FileOutputStream(new File(CimgPath)), pdfurl, 0, "jpg");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
StringUtils.println("FileNotFoundException=="+e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
StringUtils.println("IOException"+e.getMessage());
}
return CimgPath;
}
/**
* PDF转图片 根据页码一页一页转
* @throws IOException
* imgType:转换后的图片类型 jpg,png
*/
public static void PDFToImgIndex(OutputStream sos,String fileUrl,int pageIndex,String imgType) throws IOException {
PDDocument pdDocument = null;
/* dpi越大转换后越清晰,相对转换速度越慢 */
int dpi = 300;
try {
pdDocument = getPDDocument(fileUrl);
PDFRenderer renderer = new PDFRenderer(pdDocument);
int pages = pdDocument.getNumberOfPages();
if (pageIndex <= pages) {
BufferedImage image = renderer.renderImageWithDPI(pageIndex, dpi);
ImageIO.write(image, imgType, sos);
}
} catch (Exception e) {
e.printStackTrace();
StringUtils.println(e.getMessage());
} finally {
if (pdDocument != null) {
pdDocument.close();
}
}
}
private static PDDocument getPDDocument(String fileUrl) throws IOException {
File file = new File(fileUrl);
FileInputStream inputStream = new FileInputStream(file);
return PDDocument.load(inputStream);
}
}