public class FileUtil {
public static void main(String[] args) {
try {
System.out.println(System.currentTimeMillis());
File file = new File("E:/work/多业务线合同/服务合同--中工国际20160720.pdf");
// File file = new File("E:/work/多业务线合同/华夏科技执照.pdf");
// File file =new File("E:/study/Book--PDF/13_Struts.pdf");
InputStream input = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = input.read(b)) != -1) {
bos.write(b, 0, n);
}
input.close();
bos.close();
byte[] buffer = bos.toByteArray();
pdf2Image(buffer,20);
input.close();
System.out.println(System.currentTimeMillis());
} catch (IOException e) {
e.printStackTrace();
}
}
// 使用pdfbox 完成pdf文档转换成图片
public static List<byte[]> pdf2Image(byte[] buff,int canUploadImgcount) {
List<byte[]> byteList = new ArrayList<byte[]>();
try {
PDDocument doc = PDDocument.load(new ByteArrayInputStream(buff));
int pageCount = doc.getNumberOfPages();
System.out.println(pageCount);
if(pageCount>canUploadImgcount){
return null;
}
for (int i = 0; i <pageCount; i++) {
BufferedImage image = new PDFRenderer(doc).renderImageWithDPI(i,200,ImageType.RGB);
// ImageIO.write(image, "jpg", new File("E:/pdftest/pdfbox3" + i + ".jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
ImageIO.write(image, "jpg",outImage);
byteList.add(out.toByteArray());
outImage.close();
out.close();
}
doc.close();
System.out.println("over");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return byteList;
}
public static byte[] tif2JPG(byte[] srcFileByte){
try {
InputStream bais = new ByteArrayInputStream(srcFileByte);
ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", bais, null);
RenderedImage ri = decoder.decodeAsRenderedImage();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(ri, "JPEG", outputStream);
return outputStream.toByteArray();
}catch (Exception e) {
}
return null;
}
}