需求:公司现在有个将PDF文件转换成.tif格式的图片,然后利用FTP上传到服务器。
所需jar:PDFRenderer-0.9.1.jar
下面代码是将PDF文件转换成.tif格式
class="java">package com.xu.test; import java.awt.Image; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import com.sun.image.codec.jpeg.JPEGImageEncoder; import com.sun.pdfview.PDFFile; import com.sun.pdfview.PDFPage; public class PDFchangToImage { public static void main(String[] args) { PDFchangToImage.changePdfToImg(); } public static void changePdfToImg() { try { File file = new File("D:\\LT000091209.pdf"); RandomAccessFile raf = new RandomAccessFile(file, "r"); FileChannel channel = raf.getChannel(); MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY,0, channel.size()); PDFFile pdffile = new PDFFile(buf); //加载pdf文件 for (int i = 1; i <= pdffile.getNumPages(); i++) { PDFPage page = pdffile.getPage(i); //获取PDF第几页 Rectangle rect = new Rectangle(70, -20, ((int) 320),((int) page.getBBox().getHeight())); int w = 3; //设置图片的宽放大多少倍 int h = 3; //设置图片的高放大多少倍 Image img = page.getImage(rect.width * w, rect.height * h, rect, null, // null for the ImageObserver true, // fill background with white true // block until drawing is done ); BufferedImage tag = new BufferedImage(rect.width * w,rect.height * h, BufferedImage.TYPE_BYTE_GRAY); tag.getGraphics().drawImage(img, 0, 0, rect.width * w,rect.height * h, null); FileOutputStream out = new FileOutputStream("D:\\" + i+ ".tif"); // 输出到文件流 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag); param.setQuality(1f, false);// 1f是提高生成的图片质量 0-1之间 encoder.setJPEGEncodeParam(param); encoder.encode(tag); // JPEG编码 out.flush(); out.close(); } channel.close(); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
?