1. PDF To Image Convert with Apache PDFBox 2.0.x
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDResources; import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException; import org.apache.pdfbox.pdmodel.graphics.PDXObject; import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.pdfbox.tools.imageio.ImageIOUtil; public class PdfTools { PDDocument document; public PdfTools() { } public PdfTools(String fileName) throws InvalidPasswordException, IOException { load(fileName); } public void load(String fileName) throws InvalidPasswordException, IOException { document = PDDocument.load(new File(fileName)); } public void close() throws IOException { document.close(); } public void convertPagesToPng(File folder) throws IOException { if( folder.exists() == false ) { folder.mkdirs(); } PDFRenderer pdfRenderer = new PDFRenderer(document); for( int page = 0; page < document.getNumberOfPages(); page++ ) { BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB); ImageIOUtil.writeImage( bim, String.format( folder + "/image_%04d.png", page), 300); } } public void convertPagesToJpeg(File folder) throws IOException { if( folder.exists() == false ) { folder.mkdirs(); } PDFRenderer pdfRenderer = new PDFRenderer(document); for( int page = 0; page < document.getNumberOfPages(); page++ ) { BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB); ImageIOUtil.writeImage( bim, String.format( folder + "/image_%04d.jpg", page), 300); } } public static void main(String[] args) throws IOException { PdfTools pdfTools = new PdfTools("D:/Ebook/python.pdf"); pdfTools.convertPagesToPng(new File("D:/Temp/page_png")); pdfTools.convertPagesToJpeg(new File("D:/Temp/page_jpg")); } } |
댓글 없음:
댓글 쓰기