需要的依赖与代码实现
下载 jar 直接引入本地
<dependency> <groupId>com.sun.media</groupId> <artifactId>jai_codec</artifactId> <version>1.1-mr</version> <scope>system</scope> <systemPath>${project.basedir}/lib/jai-codec-1.1.3.jar</systemPath> </dependency> <dependency> <groupId>javax.media</groupId> <artifactId>jai_core</artifactId> <version>1.1-mr</version> <scope>system</scope> <systemPath>${project.basedir}/lib/jai_core-1.1.3.jar</systemPath> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.0-RC2</version> </dependency>
package com.webdemo.controllers; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import javax.media.jai.JAI; import javax.media.jai.PlanarImage; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; import com.sun.media.jai.codec.ImageCodec; import com.sun.media.jai.codec.ImageEncoder; import com.sun.media.jai.codec.TIFFEncodeParam; public class Pdf2TiffUtil { public static void main(String[] args) throws Exception { InputStream in = new FileInputStream(new File("F://123.pdf")); OutputStream out = new FileOutputStream("F://123.tiff"); pdfToTiff(in, out); } /** 图片格式 */ public static final String IMG_FORMAT = "tiff"; /** 打印精度设置 */ public static final int DPI = 220; // 图片的像素 /** * 从输入流读取pdf,转化为tiff后写入输出流.<br/> * * @param is 输入流,提供pfg内容. * @param os 输出流. */ static { System.setProperty("com.sun.media.jai.disableMediaLib", "true"); } public static void pdfToTiff(InputStream is, OutputStream os) { PDDocument doc = null; try { doc = PDDocument.load(is); int pageCount = doc.getNumberOfPages(); PDFRenderer renderer = new PDFRenderer(doc); // 根据PDDocument对象创建pdf渲染器 List<PlanarImage> piList = new ArrayList<PlanarImage>(pageCount - 1); for (int i = 0 + 1; i < pageCount; i++) { BufferedImage image = renderer.renderImageWithDPI(i, DPI, ImageType.RGB); PlanarImage pimg = JAI.create("mosaic", image); piList.add(pimg); } TIFFEncodeParam param = new TIFFEncodeParam();// 创建tiff编码参数类 param.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);// 压缩参数 param.setExtraImages(piList.iterator());// 设置图片的迭代器 BufferedImage fimg = renderer.renderImageWithDPI(0, DPI, ImageType.RGB); PlanarImage fpi = JAI.create("mosaic", fimg); // 通过JAI的create()方法实例化jai的图片对象 ImageEncoder enc = ImageCodec.createImageEncoder(IMG_FORMAT, os, param); enc.encode(fpi);// 指定第一个进行编码的jai图片对象,并将输出写入到与此 } catch (IOException e) { e.printStackTrace(); } finally { try { if (doc != null) doc.close(); } catch (IOException e) { e.printStackTrace(); } } } }
标签:java,media,TIFF,jai,param,import,PDF,com From: https://www.cnblogs.com/xiaojietian/p/17355664.html