Remarque : Cette exemple s'appuie sur la librairie iText-5.1.0
import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import javax.imageio.ImageIO; import com.sun.pdfview.PDFFile; import com.sun.pdfview.PDFPage;
public class pdf2image {
public static void main(String[] args) {
args = new String[2]; args[0] = "/home/xxx/Bureau/test.pdf"; args[1] = "/home/xxx/Bureau/pdf2image/"; if(args.length!=2) { System.err.println("Usage:Pdf2Image pdf imageFolder"); return; } File file = new File(args[0]); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); PDFFile pdffile = new PDFFile(buf); int num=pdffile.getNumPages(); PDFPage page = null; Rectangle2D r = null; Rectangle rect = null; int rotation = 0; BufferedImage img = null; for(int i=0;i<num;i++) { page = pdffile.getPage(i); r = page.getBBox(); rotation=page.getRotation(); if(rotation==90 || rotation==270) { rect=new Rectangle(0,0,(int)r.getHeight(),(int)r.getWidth()); } else { rect = new Rectangle(0,0,(int)r.getWidth(),(int)r.getHeight()); }
img = (BufferedImage)page.getImage( (int)r.getWidth(), (int)r.getHeight(), //width & height rect, // clip rect null // null for the ImageObserver );
ImageIO.write(img, "png", new File(args[1]+i+".png")); } } catch (FileNotFoundException e1) { System.err.println(e1.getLocalizedMessage()); } catch (IOException e) { System.err.println(e.getLocalizedMessage()); } } }
Aucun commentaire:
Enregistrer un commentaire