java实现Img与PDF相互转换

 更新时间:2018年05月02日 11:06:27   作者:田埂上的梦想  
这篇文章主要为大家详细介绍了java实现Img与PDF相互转换的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了java实现Img与PDF相互转换的具体代码,供大家参考,具体内容如下

不善于表达,就直接贴出代码吧。请大牛忽视我。

import java.awt.image.BufferedImage; 
import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.InputStream; 
import java.io.RandomAccessFile; 
import java.nio.ByteBuffer; 
import java.nio.channels.FileChannel; 
import java.util.Map; 
import java.util.Map.Entry; 
import java.util.TreeMap; 
 
import com.Utils.ImgFileTool; 
import com.lowagie.text.Document; 
import com.lowagie.text.Image; 
import com.lowagie.text.Rectangle; 
import com.lowagie.text.pdf.PdfCopy; 
import com.lowagie.text.pdf.PdfImportedPage; 
import com.lowagie.text.pdf.PdfReader; 
import com.lowagie.text.pdf.PdfWriter; 
import com.sun.image.codec.jpeg.JPEGCodec; 
import com.sun.image.codec.jpeg.JPEGImageEncoder; 
import com.sun.pdfview.PDFFile; 
import com.sun.pdfview.PDFPage; 
 
/** 
 * 
 * @author hubiao 
 * @dateTime 2014-06-07 
 *   本工具对实现对IMG与PDF相互转换。 
 *   运行测试需要导入以下2个jar包 
 *     itext-2.0.2.jar   
 *     PDFRenderer.jar 
 * 
 */ 
@SuppressWarnings("unused") 
public class ImgPdfUtils { 
  public static void main(String[] args) throws Exception { 
    //PDF包提取 pdf 
    //pdfExtraction(); 
     
    //pdf转jpg 
    //pdfToJpg("E:\\java\\资料pdf\\1.pdf","E:\\java\\资料pdf\\1.jpg",1); 
     
    //将多个jpg直接合并成pdf包 
    //extractionPdf("F:\\temp\\Project\\数据\\dfdsfds\\巴黎公社活动家传略_img","F:\\temp\\Project\\数据\\dfdsfds\\巴黎公社活动家传略_img.pdf"); 
     
    //jpg转pdf 
    //jpgToPdf(); 
     
    //文件排序 
    //listOrder(); 
     
    ImgFileTool.imgMerageToPdf(new File("F:\\temp\\Project\\数据\\dfdsfds\\巴黎公社活动家传略_img").listFiles(),new File("F:\\temp\\Project\\数据\\dfdsfds\\","巴黎公社活动家传略.pdf")); 
  } 
   
  private static void listOrder() { 
     
    File[] listFiles = new File("F:\\temp\\Project\\数据\\dfdsfds\\巴黎公社活动家传略_img").listFiles(); 
    TreeMap<Integer, File> tree = new TreeMap<Integer, File>(); 
    for(File f : listFiles) 
    { 
      tree.put(Integer.parseInt(f.getName().replaceAll(".jpg$", "")), f); 
    } 
    for(Entry<Integer, File> eif : tree.entrySet()) 
    { 
      System.out.println(eif.getKey()+"="+eif.getValue().toString()); 
    } 
  } 
  /** 
   * @param list 图片集合 
   * @param file 保存路径 
   * @return true,合并完成 
   *   如果文件名不是1.jpg,2.jpg,3.jpg,4.jpg这样的。则需要自己重写TreeMap的排序方式! 
   */ 
  public static boolean imgMerageToPdf(File[] list, File file)throws Exception { 
    //1:对图片文件通过TreeMap以名称进行自然排序 
    Map<Integer,File> mif = new TreeMap<Integer,File>(); 
    for(File f : list) 
      mif.put(Integer.parseInt(f.getName().replaceAll(".jpg$", "")), f); 
     
    //2:获取第一个Img的宽、高做为PDF文档标准 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(2048*3); 
    InputStream is = new FileInputStream(mif.get(1)); 
    for(int len;(len=is.read())!=-1;) 
      baos.write(len); 
     
    baos.flush(); 
    Image image = Image.getInstance(baos.toByteArray()); 
    float width = image.width(); 
    float height = image.height(); 
    baos.close(); 
     
    //3:通过宽高 ,实例化PDF文档对象。 
    Document document = new Document(new Rectangle(width,height)); 
    PdfWriter pdfWr = PdfWriter.getInstance(document, new FileOutputStream(file)); 
    document.open(); 
     
    //4:获取每一个图片文件,转为IMG对象。装载到Document对象中 
    for(Entry<Integer,File> eif : mif.entrySet()) 
    { 
      //4.1:读取到内存中 
      baos = new ByteArrayOutputStream(2048*3); 
      is = new FileInputStream(eif.getValue()); 
      for(int len;(len=is.read())!=-1;) 
        baos.write(len); 
      baos.flush(); 
       
      //4.2通过byte字节生成IMG对象 
      image = Image.getInstance(baos.toByteArray()); 
      Image.getInstance(baos.toByteArray()); 
      image.setAbsolutePosition(0.0f, 0.0f); 
       
      //4.3:添加到document中 
      document.add(image); 
      document.newPage(); 
      baos.close(); 
    } 
     
    //5:释放资源 
    document.close(); 
    pdfWr.close(); 
     
    return true; 
  } 
  /** 
   * 
   * @param source 源文件 
   * @param target 目标文件 
   * @param x 读取源文件中的第几页 
   */ 
  private static void pdfToJpg(String source,String target,int x) throws Exception { 
    //创建从中读取和向其中写入(可选)的随机访问文件流,R表示对其只是访问模式 
    RandomAccessFile rea = new RandomAccessFile(new File(source), "r"); 
 
    //将流读取到内存中,然后还映射一个PDF对象 
    FileChannel channel = rea.getChannel(); 
    ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY,0, channel.size()); 
    PDFFile pdfFile = new PDFFile(buf); 
    PDFPage page = pdfFile.getPage(x);  
 
    // get the width and height for the doc at the default zoom  
    java.awt.Rectangle rect = new java.awt.Rectangle(0, 0, (int) page.getBBox()  
        .getWidth(), (int) page.getBBox().getHeight());  
 
    // generate the image  
    java.awt.Image img = page.getImage(rect.width, rect.height, // width & 
        rect, // clip rect 
        null, // null for the ImageObserver 
        true, // fill background with white 
        true // block until drawing is done 
        );  
 
    BufferedImage tag = new BufferedImage(rect.width, rect.height,  
        BufferedImage.TYPE_INT_RGB);  
     
    tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height,  
        null);  
    FileOutputStream out = new FileOutputStream(target); // 输出到文件流  
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
    encoder.encode(tag); // JPEG编码  
    out.close();     
  } 
  /** 
   * @param source 源PDF文件路径 
   * @param target 保存PDF文件路径 
   * @param pageNum 提取PDF中第pageNum页 
   * @throws Exception  
   */ 
  private static void pdfExtraction(String source,String target,int pageNum) throws Exception{ 
    //1:创建PDF读取对象 
    PdfReader pr = new PdfReader(source); 
    System.out.println("this document "+pr.getNumberOfPages()+" page"); 
     
    //2:将第page页转为提取,创建document对象 
    Document doc = new Document(pr.getPageSize(pageNum)); 
     
    //3:通过PdfCopy转其单独存储 
    PdfCopy copy = new PdfCopy(doc, new FileOutputStream(new File(target))); 
    doc.open(); 
    doc.newPage(); 
     
    //4:获取第1页,装载到document中。 
    PdfImportedPage page = copy.getImportedPage(pr,pageNum); 
    copy.addPage(page);  
     
    //5:释放资源 
    copy.close(); 
    doc.close(); 
    pr.close(); 
  } 
  /** 
   * @param pdfFile 源PDF文件 
   * @param imgFile  图片文件 
   */ 
  private static void jpgToPdf(File pdfFile,File imgFile) throws Exception { 
    //文件转img 
    InputStream is = new FileInputStream(pdfFile); 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    for(int i;(i=is.read())!=-1;) 
    { 
      baos.write(i); 
    } 
    baos.flush(); 
     
    //取得图像的宽和高。 
    Image img = Image.getInstance(baos.toByteArray()); 
    float width = img.width(); 
    float height = img.height(); 
    img.setAbsolutePosition(0.0F, 0.0F);//取消偏移 
    System.out.println("width = "+width+"\theight"+height); 
     
    //img转pdf 
    Document doc = new Document(new Rectangle(width,height)); 
    PdfWriter pw = PdfWriter.getInstance(doc,new FileOutputStream(imgFile)); 
    doc.open(); 
    doc.add(img); 
     
    //释放资源 
    System.out.println(doc.newPage()); 
    pw.flush(); 
    baos.close(); 
    doc.close(); 
    pw.close(); 
  } 
   
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • springboot项目实现配置跨域

    springboot项目实现配置跨域

    这篇文章主要介绍了springboot项目实现配置跨域问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-09-09
  • 详解Java中StringBuffer类常用方法

    详解Java中StringBuffer类常用方法

    这篇文章主要为大家介绍了java中StringBuffer类常用方法
    2016-01-01
  • Java异常处理Guava Throwables类使用实例解析

    Java异常处理Guava Throwables类使用实例解析

    这篇文章主要为大家介绍了Java异常处理神器Guava Throwables类使用深入详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • Java实现自定义语言和表达式解析的解释器模式

    Java实现自定义语言和表达式解析的解释器模式

    Java解释器设计模式通过解析自定义语言和表达式,实现对复杂逻辑的处理,提高程序可扩展性和灵活性。它将语法解析和执行过程分离,通过抽象语法树和解释器实现对语言和表达式的解析和求值,避免了硬编码和复杂的条件判断,提高了程序的可读性和可维护性
    2023-04-04
  • Springboot项目快速实现过滤器功能

    Springboot项目快速实现过滤器功能

    上篇文章已经给大家介绍了Springboot项目如何快速实现Aop功能,这篇文章给大家介绍Springboot项目如何快速实现过滤器功能,感兴趣的小伙伴可以参考阅读
    2023-03-03
  • Mybatis传递多个参数进行SQL查询的用法

    Mybatis传递多个参数进行SQL查询的用法

    本文给大家介绍Mybatis传递多个参数进行SQL查询的用法的相关知识,本文还给大家介绍了mybatis通过Map传递多个参数和JavaBean传递多个参数,本文介绍的非常详细,具有参考借鉴价值,感兴趣的朋友一起学习吧
    2016-06-06
  • SpringMVC REST风格深入详细讲解

    SpringMVC REST风格深入详细讲解

    这篇文章主要介绍了SpringMVC REST风格,Rest全称为Representational State Transfer,翻译为表现形式状态转换,它是一种软件架构
    2022-10-10
  • 全网最全SpringBoot集成swagger的详细教程

    全网最全SpringBoot集成swagger的详细教程

    swagger是当下比较流行的实时接口文文档生成工具,swagger分为swagger2 和swagger3两个常用版本,二者区别不是很大,主要对于依赖和注解进行了优化,swagger2需要引入2个jar包,swagger3只需要一个,用起来没有什么大的区别,本文给大家详细介绍,感兴趣的朋友一起看看吧
    2022-08-08
  • Idea 解决 Could not autowire. No beans of ''xxxx'' type found 的错误提示

    Idea 解决 Could not autowire. No beans of ''xxxx'' type found

    这篇文章主要介绍了Idea 解决 Could not autowire. No beans of 'xxxx' type found 的错误提示,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-01-01
  • 详解Java编程中向量(Vector)的应用

    详解Java编程中向量(Vector)的应用

    这篇文章主要介绍了Java中的向量(Vector)的应用,Vector也是Java中比较常用的一个类,需要的朋友可以参考下
    2015-10-10

最新评论