将pdf文件转长jpg图片:
相关文件:tika-app-1.1.jar
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
@SuppressWarnings(value = { "restriction", "unchecked" })
public class Pdf2Jpg {
public static void createJpg(String pdfFile, String jpgfile)
throws Exception {
PDDocument document = null;
FileOutputStream output = null;
try {
// 打开pdf文件,获取所有页面
document = PDDocument.load(pdfFile);
List<PDPage> pages = document.getDocumentCatalog().getAllPages();
// 统计各页宽度和高度
List<BufferedImage> listimgage = new ArrayList<BufferedImage>();
int width = 0;
int height = 0;
for (int i = 0; i < pages.size(); i++) {
PDPage page = pages.get(i);
BufferedImage image = page.convertToImage();
int newwidth = image.getWidth();
if (newwidth > width)
width = newwidth;
height += image.getHeight();
listimgage.add(image);
}
// 绘制合成图像
BufferedImage jpgimage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D grap = jpgimage.createGraphics();
int top = 0;
for (int i = 0; i < pages.size(); i++) {
BufferedImage image = listimgage.get(i);
int newwidth = image.getWidth();
int newheight = image.getHeight();
grap.drawImage(image, 0, top, newwidth, newheight, null);
top += image.getHeight();
}
// 释放图像资源
grap.dispose();
// 将绘制的图像生成至输出流
output = new FileOutputStream(jpgfile);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
encoder.encode(jpgimage);
} catch (Exception e) {
throw new Exception(e);
} finally {
if (document != null)
document.close();
// 关闭输出流
if (output != null)
output.close();
}
}
}