import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.log4j.Logger;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import sun.nio.ch.FileChannelImpl;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class Pdf2ImgUtil {
private static Logger logger = Logger.getLogger(Pdf2ImgUtil.class.getName());
public static int pdf2Img(String pdfPath,String imgName,String imgPath, float scale) throws Exception {
File file = new File(pdfPath);
if(!file.exists()){
String msg = "文件:"+file.getAbsolutePath()+"不存在!";
logger.error(msg);
throw new RuntimeException(msg);
}
new File(imgPath).mkdirs();
long t = System.currentTimeMillis();
RandomAccessFile raf = null;
sun.nio.ch.FileChannelImpl channel = null;
ByteBuffer buf = null;
try{
raf = new RandomAccessFile(file , "r");
channel = (FileChannelImpl) raf.getChannel();
buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
int pageNums = pdffile.getNumPages();
for(int i = 1;i<=pageNums;i++){
PDFPage page = pdffile.getPage(i);
if(page == null){
return 0;
}
Rectangle rect = new Rectangle(
0,
0,
(int)page.getBBox().getWidth(),
(int)page.getBBox().getHeight()
);
int width = (int) (rect.width *scale);
int height = (int) (rect.height *scale);
Image img = page.getImage(
width,
height,
rect,
null,
true,
true
);
BufferedImage tag = new BufferedImage(
width,
height,
BufferedImage.TYPE_INT_BGR
);
tag.getGraphics().drawImage(img, 0, 0, width, height, null);
FileOutputStream out = new FileOutputStream(imgPath+ "\\"+ imgName + i + ".png");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag);
param.setQuality(1f, true);
encoder.setJPEGEncodeParam(param);
encoder.encode(tag);
out.close();
}
buf.clear();
System.out.println("pdf2Img:"+pdfPath+" time:"+(System.currentTimeMillis()-t));
return pageNums;
}catch(IOException e){
String msg = "文档转换出错:"+e.getMessage();
logger.error(msg, e);
throw e;
}finally{
if(channel != null){
try {
channel.close();
} catch (IOException e) {
logger.error("pdf2Img finally ", e);
}
}
if(raf != null){
try {
raf.close();
} catch (IOException e) {
logger.error("pdf2Img finally ", e);
}
}
Method method;
try {
//释放文件,不然文件会被占用
method = FileChannelImpl.class.getDeclaredMethod("unmap", MappedByteBuffer.class);
method.setAccessible(true);
method.invoke(FileChannelImpl.class, buf);
} catch (NoSuchMethodException e) {
logger.error("pdf2Img finally ", e);
} catch (SecurityException e) {
logger.error("pdf2Img finally ", e);
} catch (IllegalAccessException e) {
logger.error("pdf2Img finally ", e);
} catch (IllegalArgumentException e) {
logger.error("pdf2Img finally ", e);
} catch (InvocationTargetException e) {
logger.error("pdf2Img finally ", e);
}
}
}
public static int pdf2ImgZip(String pdfPath,String imgName,String imgPath, float scale) throws Exception {
File file = new File(pdfPath);
if(!file.exists()){
String msg = "文件:"+file.getAbsolutePath()+"不存在!";
logger.error(msg);
throw new RuntimeException(msg);
}
new File(imgPath).mkdirs();
long t = System.currentTimeMillis();
RandomAccessFile raf = null;
sun.nio.ch.FileChannelImpl channel = null;
ByteBuffer buf = null;
String temp = "image2zip.zip";
ZipOutputStream zipOS = null;
try{
raf = new RandomAccessFile(file , "r");
channel = (FileChannelImpl) raf.getChannel();
buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
zipOS = new ZipOutputStream(new FileOutputStream(temp));
PDFFile pdffile = new PDFFile(buf);
int pageNums = pdffile.getNumPages();
for(int i = 1;i<=pageNums;i++){
PDFPage page = pdffile.getPage(i);
if(page == null){
return 0;
}
Rectangle rect = new Rectangle(
0,
0,
(int)page.getBBox().getWidth(),
(int)page.getBBox().getHeight()
);
int width = (int) (rect.width *scale);
int height = (int) (rect.height *scale);
Image img = page.getImage(
width,
height,
rect,
null,
true,
true
);
BufferedImage tag = new BufferedImage(
width,
height,
BufferedImage.TYPE_INT_BGR
);
tag.getGraphics().drawImage(img, 0, 0, width, height, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag);
param.setQuality(1f, true);
encoder.setJPEGEncodeParam(param);
encoder.encode(tag);
//
ZipEntry entry = new ZipEntry((i) +".png");
zipOS.putNextEntry(entry);
zipOS.write(out.toByteArray());
zipOS.flush();
zipOS.closeEntry();//Closes the current ZIP entry and positions the stream for writing the next entry
//
out.close();
raf.close();
}
zipOS.close();
buf.clear();
System.out.println("pdf2ImgZip:"+pdfPath+" time:"+(System.currentTimeMillis()-t));
return pageNums;
}catch(Exception e){
String msg = "文档转换出错:"+e.getMessage();
logger.error(msg, e);
throw e;
}finally{
try {
if(zipOS!=null)zipOS.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Method method;
try {
//释放文件,不然文件会被占用
method = FileChannelImpl.class.getDeclaredMethod("unmap", MappedByteBuffer.class);
method.setAccessible(true);
method.invoke(FileChannelImpl.class, buf);
} catch (NoSuchMethodException e) {
logger.error("pdf2ImgZip finally ", e);
} catch (SecurityException e) {
logger.error("pdf2ImgZip finally ", e);
} catch (IllegalAccessException e) {
logger.error("pdf2ImgZip finally ", e);
} catch (IllegalArgumentException e) {
logger.error("pdf2ImgZip finally ", e);
} catch (InvocationTargetException e) {
logger.error("pdf2ImgZip finally ", e);
}
if(channel != null){
try {
channel.close();
} catch (IOException e) {
logger.error("pdf2Img finally ", e);
}
}
if(raf != null){
try {
raf.close();
} catch (IOException e) {
logger.error("pdf2ImgZip finally ", e);
}
}
}
}
public static void main(String[] args) {
String filePath = "C:\\Users\\Administrator\\Desktop\\新建 Microsoft Word 文档.pdf";
String targetDir = "C:\\Users\\Administrator\\Desktop\\新建文件夹 (5)";
try {
Pdf2ImgUtil.pdf2ImgZip(filePath, "", targetDir, 2);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("e");
}
}