packagecom.dddpeter.app;importorg.apache.pdfbox.multipdf.Splitter;importorg.apache.pdfbox.pdmodel.PDDocument;importorg.apache.pdfbox.rendering.PDFRenderer;importjavax.imageio.ImageIO;importjavax.imageio.stream.ImageOutputStream;importjava.awt.image.BufferedImage;import java.io.*;importjava.util.List;importjava.util.ListIterator;public classPDFUtils {public static String splitPdf(intpageNum, String source, String dest) {
File indexFile= newFile(source);
File outFile= newFile(dest);
PDDocument document= null;try{
document=PDDocument.load(indexFile);//document.getNumberOfPages();
Splitter splitter = newSplitter();
splitter.setStartPage(pageNum);
splitter.setEndPage(pageNum);
List pages =splitter.split(document);
ListIterator iterator =pages.listIterator();while(iterator.hasNext()) {
PDDocument pd=iterator.next();if(outFile.exists()) {
outFile.delete();
}
pd.save(outFile);
pd.close();if(outFile.exists()) {returnoutFile.getPath();
}
}
document.close();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}return null;
}public static voidpdfFileToImage(File pdffile,String targetPath){try{
FileInputStream instream= newFileInputStream(pdffile);
InputStream byteInputStream=null;try{
PDDocument doc=PDDocument.load(instream);
PDFRenderer renderer= newPDFRenderer(doc);int pageCount =doc.getNumberOfPages();if (pageCount > 0) {
BufferedImage image= renderer.renderImage(0, 4.0f);
image.flush();
ByteArrayOutputStream bs= newByteArrayOutputStream();
ImageOutputStream imOut;
imOut=ImageIO.createImageOutputStream(bs);
ImageIO.write(image,"png", imOut);
byteInputStream= newByteArrayInputStream(bs.toByteArray());
byteInputStream.close();
}
doc.close();
}catch(IOException e) {
e.printStackTrace();
}
File uploadFile= newFile(targetPath);
FileOutputStream fops;
fops= newFileOutputStream(uploadFile);
fops.write(readInputStream(byteInputStream));
fops.flush();
fops.close();
}catch(Exception e) {
e.printStackTrace();
}
}public static byte[] readInputStream(InputStream inStream) throwsException {
ByteArrayOutputStream outStream= newByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer,0, len);
}
inStream.close();returnoutStream.toByteArray();
}public static voidmain(String[] args) {
String path= splitPdf(4,"D:\\data\\11.pdf","D:\\data\\out11.pdf");
File file=newFile(path);//上传的是png格式的图片结尾
String targetfile="D:\\data\\out11.png";
pdfFileToImage(file,targetfile);
}
}