本文共 2516 字,大约阅读时间需要 8 分钟。
前面已经把html转成pdf,但是用户可以下载图片格式的文件,所以我们必须把pdf转成图片格式,代码如下
package com.jit.platform.basics.util.pdf;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.File;import java.util.ArrayList;import java.util.List;import javax.imageio.ImageIO;import org.jpedal.PdfDecoder;class ImgPp{ BufferedImage img; int width ; int height; public BufferedImage getImg() { return img; } public void setImg(BufferedImage img) { this.img = img; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } }public class PdfToImg { public static ListtoImgList(String pdfPath,String imgPath,String imgName) throws Exception{ PdfDecoder decode_pdf = new PdfDecoder(true); decode_pdf.openPdfFile(pdfPath); //file int start = 1, end = decode_pdf.getPageCount(); List list = new ArrayList (); for(int i=start;i list = new ArrayList (); int width = 0; int totalHeight = 0; for(int i=start;i list,int totalHeight,int width,String imgPath,String imgName) throws Exception { //构造一个类型为预定义图像类型之一的 BufferedImage。 宽度为第一只的宽度,高度为各个图片高度之和 BufferedImage tag = new BufferedImage(width, totalHeight, BufferedImage.TYPE_INT_RGB); //绘制合成图像 Graphics g = tag.createGraphics(); int tempHeight = 0; for (int i = 0; i < list.size(); i++) { ImgPp imgPp = list.get(i); g.drawImage(imgPp.getImg(), 0, tempHeight, width, imgPp.getHeight(), null); tempHeight+=imgPp.getHeight(); } // 释放此图形的上下文以及它使用的所有系统资源。 g.dispose(); // Save as new image ImageIO.write(tag, "png", new File(imgPath + imgName)); return imgName; } public static void main(String[] args) { String pdfPath = "D:\\many page.pdf"; String imgPath = "D:\\"; String imgName = "pdfbox_image"; try { String imgOne = toImgOne(pdfPath,imgPath,imgName); System.out.println("imgOne"+imgOne); /*List img2 = toImgList(pdfPath,imgPath,imgName); File[] fileArray = new File[img2.size()]; for (int i = 0; i < img2.size(); i++) { //System.out.println(img2.get(i)); File file = new File(img2.get(i)); fileArray[i] = file; } BatchDownloadAction.makeZip(imgPath,imgName , fileArray);*/ } catch (Exception e1) { e1.printStackTrace(); } } }
项目中遇到了用户还可以下载图片格式的文件,所以我们就需要把pdf转成图片,下面是我们完成的代码。
转载地址:http://gipez.baihongyu.com/