使用Java将Pdf转化成Img
使用Java将Pdf转化成Img
项目中要使用 pdf 转化为 Img,为此找了许多方法,
-
使用 IText7 库将 pdf 转化成 Img。但是需要花钱。
不过Itext 库中的其他 pdf 的操作方法是真的方便,好用。
-
就是以下代码,它的原理是读取pdf内容,使用 Graphics2D 将内容画出来,输出到png文件中(和之前画六维图的原理类似)。
代码
最终方法如下:(原文链接:https://stackoverflow.com/questions/4929813/convert-pdf-to-thumbnail-image-in-java)
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
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 Main {
public static void main(String[] args) throws IOException {
File pdfFile = new File("c:\\YOURPDF.pdf");
RandomAccessFile raf = new RandomAccessFile(pdfFile, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdf = new PDFFile(buf);
for (int i=0; i<pdf.getNumPages(); i++) {
createImage(pdf.getPage(i), "c:\\PICTURE_" + i + ".jpg");
}
}
public static void createImage(PDFPage page, String destination) throws IOException{
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(),
(int) page.getBBox().getHeight());
BufferedImage bufferedImage = new BufferedImage(rect.width, rect.height,
BufferedImage.TYPE_INT_RGB);
Image image = page.getImage(rect.width, rect.height, // width & height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
Graphics2D bufImageGraphics = bufferedImage.createGraphics();
bufImageGraphics.drawImage(image, 0, 0, null);
ImageIO.write(bufferedImage, "JPG", new File( destination ));
}
}