PDF与IMAGE互相转化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Flykos/article/details/72843758

所需jar包

1、http://download.csdn.net/detail/flykos/9858599

2、http://download.csdn.net/detail/flykos/9858294


java实现PDF与IMAGE互相转化代码

package jpg2pdf;

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

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

import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;

public class PdfImgUtil {

	/**
	 * IMAGE转PDF
	 * @param imagePath 图片路径
	 * @param pdfPath pdf路径
	 */
	public static void Image2pdf(String imagePath, String pdfPath) {
		try {
			BufferedImage img = ImageIO.read(new File(imagePath));
			FileOutputStream fos = new FileOutputStream(pdfPath);
			com.lowagie.text.Document doc = new com.lowagie.text.Document(null, 0, 0, 0, 0);
			doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
			Image image = Image.getInstance(imagePath);
			PdfWriter.getInstance(doc, fos);
			doc.open();
			doc.add(image);
			doc.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * PDF转IMAGE
	 * @param filepath pdf路径
	 * @param imagepath 图片路径
	 * @param zoom 
	 * @throws Exception
	 */
	public static void Pdf2Image(String filepath, String imagepath, float zoom) {
		try {
			Document document = null;
			float rotation = 0f;
			document = new Document();
			document.setFile(filepath);
			BufferedImage img = (BufferedImage) document.getPageImage(0,
					GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX,
					rotation, zoom);
			/**
			 * 迭代器的遍历
			 */
			Iterator iter = ImageIO.getImageWritersBySuffix("jpg");
			ImageWriter writer = (ImageWriter) iter.next();
			File outFile = new File(imagepath);// + document.getNumberOfPages() + "." + "jpg"
			FileOutputStream out = new FileOutputStream(outFile);
			ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
			writer.setOutput(outImage);
			writer.write(new IIOImage(img, null, null));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		// Image2pdf("E:\\test.jpg", "E:\\test.pdf");
		// Pdf2Image("E:\\test.pdf", "E:\\test.png", 1);
	}

}

猜你喜欢

转载自blog.csdn.net/Flykos/article/details/72843758