1 import java.awt.Image; 2 import java.awt.Rectangle; 3 import java.awt.image.BufferedImage; 4 import java.io.File; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 import java.io.RandomAccessFile; 8 import java.nio.ByteBuffer; 9 import java.nio.channels.FileChannel; 10 11 import javax.swing.SwingUtilities; 12 13 import com.sun.image.codec.jpeg.JPEGCodec; 14 import com.sun.image.codec.jpeg.JPEGImageEncoder; 15 import com.sun.pdfview.PDFFile; 16 import com.sun.pdfview.PDFPage; 17 18 /** 19 * @description: <br/> 20 * @date: 2016年2月19日 上午9:43:25 <br/> 21 * @author <br/> 22 * 23 * 24 */ 25 public class PdfToImgTest { 26 /**设置图片宽高的放大比例*/ 27 private static final int PICTURE_MULTIPLE = 5; 28 29 @SuppressWarnings("resource") 30 public static void setup() throws IOException { 31 File file = new File("E://pdf//Java数据结构和算法.pdf"); 32 RandomAccessFile raf = new RandomAccessFile(file, "r"); 33 FileChannel channel = raf.getChannel(); 34 ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); 35 PDFFile pdffile = new PDFFile(buf); 36 System.out.println("页数: " + pdffile.getNumPages()); 37 38 for (int i = 1; i <= pdffile.getNumPages(); i++) { 39 // 将文件分页画到图像 40 PDFPage page = pdffile.getPage(i); 41 // 获取默认缩放的文件的宽度和高度 42 Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight()); 43 int width = rect.width * PICTURE_MULTIPLE; 44 int height = rect.height * PICTURE_MULTIPLE; 45 // 生成图像 46 Image img = page.getImage(width, height, rect, null, true, true); 47 BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 48 tag.getGraphics().drawImage(img, 0, 0, width, height, null); 49 // 输出到文件流 50 FileOutputStream out = new FileOutputStream("E://picture//1//" + i + ".jpg"); 51 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 52 // JPEG编码 53 encoder.encode(tag); 54 out.close(); 55 } 56 } 57 58 public static void main(final String[] args) { 59 SwingUtilities.invokeLater(new Runnable() { 60 public void run() { 61 try { 62 PdfToImgTest.setup(); 63 } catch (IOException ex) { 64 ex.printStackTrace(); 65 } 66 } 67 }); 68 } 69 }
这是在网上找到的一段代码,经过修改后mark一下,方便以后需要的时候使用。
这段代码需要一个额外的jar包:PDFRenderer.jar