PDF转图片

 

<dependency>
	<groupId>org.apache.pdfbox</groupId>
	<artifactId>pdfbox</artifactId>
	<version>1.8.6</version>
</dependency>

 

先转换成多张图片,然后合并成一张。

 

package org.apache.pdf;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

public class PDF2Image {
	public static void main(String[] args) {
		File pdf = new File("20140809200001.pdf");
		String imgType = "jpg";
		int pageCount = covertPdf2Image(pdf, imgType);
		mergeImg(pdf.getName(),imgType,pageCount);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static int covertPdf2Image(File pdf, String imgType) {
		try {
			PDDocument doc = PDDocument.load(pdf);
			int pageCount = doc.getNumberOfPages();
			System.out.println(pageCount);
			List<PDPage> pages = doc.getDocumentCatalog().getAllPages();
			String imgPrefix = pdf.getName().split("\\.")[0];
			for (int index = 0; index < pages.size(); index++) {
				BufferedImage image = pages.get(index).convertToImage();
				Iterator iter = ImageIO.getImageWritersBySuffix(imgType);
				ImageWriter writer = (ImageWriter) iter.next();
				File outFile = new File(imgPrefix + "_" + (index+1) + "." + imgType);
				FileOutputStream out = new FileOutputStream(outFile);
				ImageOutputStream outImage = ImageIO
						.createImageOutputStream(out);
				writer.setOutput(outImage);
				writer.write(new IIOImage(image, null, null));
			}
			return pages.size();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return -1;
	}

	public static void mergeImg(String imgPrefix, String imgType, int pages) {
		try {
			File tmpImg = new File(imgPrefix.split("\\.")[0]+"_1."+imgType);
			BufferedImage bufTemp = ImageIO.read(tmpImg);
			BufferedImage imageResult = new BufferedImage(bufTemp.getWidth(),
					bufTemp.getHeight() * 8, BufferedImage.TYPE_INT_RGB);
			for (int i = 1; i <= pages; i++) {
				File img = new File(imgPrefix.split("\\.")[0]+"_"+i+"."+imgType);
				BufferedImage bufImg = ImageIO.read(img);
				int width = bufImg.getWidth();
				int height = bufImg.getHeight();
				int[] imageArray = new int[width * height];
				imageArray = bufImg.getRGB(0, 0, width, height, imageArray, 0,width);
				imageResult.setRGB(0, (i - 1) * height, width, height, imageArray, 0, width);
				img.delete();
			}
			File outFile = new File("out.jpg");
			ImageIO.write(imageResult, "jpg", outFile);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

你可能感兴趣的:(pdf)