关于_pdf转图片的问题
1 package com.duan; 2 3 import java.awt.Image; 4 import java.awt.Rectangle; 5 import java.awt.image.BufferedImage; 6 import java.io.*; 7 import java.nio.ByteBuffer; 8 import java.nio.channels.FileChannel; 9 10 import javax.swing.SwingUtilities; 11 12 import com.sun.image.codec.jpeg.JPEGCodec; 13 import com.sun.image.codec.jpeg.JPEGImageEncoder; 14 import com.sun.pdfview.PDFFile; 15 import com.sun.pdfview.PDFPage; 16 17 public class PdfToJpgTest { 18 public static void setup() throws IOException { 19 // load a pdf from a byte buffer 20 File file = new File("F:test.pdf"); 21 RandomAccessFile raf = new RandomAccessFile(file, "r"); 22 FileChannel channel = raf.getChannel(); 23 ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel 24 .size()); 25 PDFFile pdffile = new PDFFile(buf); 26 27 System.out.println("页数: " + pdffile.getNumPages()); 28 29 String getPdfFilePath = "F:"; 30 31 System.out.println("getPdfFilePath is :"+getPdfFilePath); 32 33 for (int i = 1; i <= pdffile.getNumPages(); i++) { 34 // draw the first page to an image 35 PDFPage page = pdffile.getPage(i); 36 37 // get the width and height for the doc at the default zoom 38 Rectangle rect = new Rectangle(0, 0, (int) page.getBBox() 39 .getWidth(), (int) page.getBBox().getHeight()); 40 41 // generate the image 42 Image img = page.getImage(rect.width, rect.height, // width & 43 // height 44 rect, // clip rect 45 null, // null for the ImageObserver 46 true, // fill background with white 47 true // block until drawing is done 48 ); 49 50 BufferedImage tag = new BufferedImage(rect.width, rect.height, 51 BufferedImage.TYPE_INT_RGB); 52 tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height, 53 null); 54 55 56 57 FileOutputStream out = new FileOutputStream( getPdfFilePath+"\\" + i + ".jpg"); // 输出到文件流 58 System.out.println("成功保存图片到 : " +getPdfFilePath+"\\" + i + ".jpg"); 59 60 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 61 encoder.encode(tag); // JPEG编码 62 63 out.close(); 64 } 65 66 // show the image in a frame 67 // JFrame frame = new JFrame("PDF Test"); 68 // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 69 // frame.add(new JLabel(new ImageIcon(img))); 70 // frame.pack(); 71 // frame.setVisible(true); 72 } 73 74 public static void main(final String[] args) { 75 SwingUtilities.invokeLater(new Runnable() { 76 public void run() { 77 try { 78 PdfToJpgTest.setup(); 79 } catch (IOException ex) { 80 ex.printStackTrace(); 81 } 82 } 83 }); 84 } 85 86 }
需要额外引入
参考网址 http://blog.sina.com.cn/s/blog_4ed66efa0100g06d.html