java实现img与pdf相互转换

来源:互联网 发布:win10写字板源码 编辑:程序博客网 时间:2024/05/12 18:55
  1. import java.awt.image.BufferedImage; 
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File; 
  4. import java.io.FileInputStream; 
  5. import java.io.FileOutputStream; 
  6. import java.io.InputStream; 
  7. import java.io.RandomAccessFile; 
  8. import java.nio.ByteBuffer; 
  9. import java.nio.channels.FileChannel; 
  10. import java.util.Map; 
  11. import java.util.Map.Entry; 
  12. import java.util.TreeMap; 
  13.  
  14. import com.Utils.ImgFileTool; 
  15. import com.lowagie.text.Document; 
  16. import com.lowagie.text.Image; 
  17. import com.lowagie.text.Rectangle; 
  18. import com.lowagie.text.pdf.PdfCopy; 
  19. import com.lowagie.text.pdf.PdfImportedPage; 
  20. import com.lowagie.text.pdf.PdfReader; 
  21. import com.lowagie.text.pdf.PdfWriter; 
  22. import com.sun.image.codec.jpeg.JPEGCodec; 
  23. import com.sun.image.codec.jpeg.JPEGImageEncoder; 
  24. import com.sun.pdfview.PDFFile; 
  25. import com.sun.pdfview.PDFPage; 
  26.  
  27. /**
  28. *
  29. * @author hubiao
  30. * @dateTime 2014-06-07
  31. *      本工具对实现对IMG与PDF相互转换。
  32. *      运行测试需要导入以下2个jar包
  33. *          itext-2.0.2.jar    
  34. *          PDFRenderer.jar
  35. *
  36. */ 
  37. @SuppressWarnings("unused"
  38. public class ImgPdfUtils { 
  39.     public staticvoid main(String[] args) throws Exception { 
  40.         //PDF包提取 pdf 
  41.         //pdfExtraction(); 
  42.          
  43.         //pdf转jpg 
  44.         //pdfToJpg("E:\\java\\资料pdf\\1.pdf","E:\\java\\资料pdf\\1.jpg",1); 
  45.          
  46.         //将多个jpg直接合并成pdf包 
  47.         //extractionPdf("F:\\temp\\Project\\数据\\dfdsfds\\巴黎公社活动家传略_img","F:\\temp\\Project\\数据\\dfdsfds\\巴黎公社活动家传略_img.pdf"); 
  48.          
  49.         //jpg转pdf 
  50.         //jpgToPdf(); 
  51.          
  52.         //文件排序 
  53.         //listOrder(); 
  54.          
  55.         ImgFileTool.imgMerageToPdf(new File("F:\\temp\\Project\\数据\\dfdsfds\\巴黎公社活动家传略_img").listFiles(),new File("F:\\temp\\Project\\数据\\dfdsfds\\","巴黎公社活动家传略.pdf")); 
  56.     } 
  57.      
  58.     private staticvoid listOrder() { 
  59.          
  60.         File[] listFiles = new File("F:\\temp\\Project\\数据\\dfdsfds\\巴黎公社活动家传略_img").listFiles(); 
  61.         TreeMap<Integer, File> tree = new TreeMap<Integer, File>(); 
  62.         for(File f : listFiles) 
  63.         { 
  64.             tree.put(Integer.parseInt(f.getName().replaceAll(".jpg$","")), f); 
  65.         } 
  66.         for(Entry<Integer, File> eif : tree.entrySet()) 
  67.         { 
  68.             System.out.println(eif.getKey()+"="+eif.getValue().toString()); 
  69.         } 
  70.     } 
  71.     /**
  72.      * @param list  图片集合
  73.      * @param file 保存路径
  74.      * @return  true,合并完成
  75.      *      如果文件名不是1.jpg,2.jpg,3.jpg,4.jpg这样的。则需要自己重写TreeMap的排序方式!
  76.      */ 
  77.     public staticboolean imgMerageToPdf(File[] list, File file)throws Exception { 
  78.         //1:对图片文件通过TreeMap以名称进行自然排序 
  79.         Map<Integer,File> mif = new TreeMap<Integer,File>(); 
  80.         for(File f : list) 
  81.             mif.put(Integer.parseInt(f.getName().replaceAll(".jpg$","")), f); 
  82.          
  83.         //2:获取第一个Img的宽、高做为PDF文档标准 
  84.         ByteArrayOutputStream baos = new ByteArrayOutputStream(2048*3); 
  85.         InputStream is = new FileInputStream(mif.get(1)); 
  86.         for(int len;(len=is.read())!=-1;) 
  87.             baos.write(len); 
  88.          
  89.         baos.flush(); 
  90.         Image image = Image.getInstance(baos.toByteArray()); 
  91.         float width = image.width(); 
  92.         float height = image.height(); 
  93.         baos.close(); 
  94.          
  95.         //3:通过宽高 ,实例化PDF文档对象。 
  96.         Document document = new Document(new Rectangle(width,height)); 
  97.         PdfWriter pdfWr = PdfWriter.getInstance(document, new FileOutputStream(file)); 
  98.         document.open(); 
  99.          
  100.         //4:获取每一个图片文件,转为IMG对象。装载到Document对象中 
  101.         for(Entry<Integer,File> eif : mif.entrySet()) 
  102.         { 
  103.             //4.1:读取到内存中 
  104.             baos = new ByteArrayOutputStream(2048*3); 
  105.             is = new FileInputStream(eif.getValue()); 
  106.             for(int len;(len=is.read())!=-1;) 
  107.                 baos.write(len); 
  108.             baos.flush(); 
  109.              
  110.             //4.2通过byte字节生成IMG对象 
  111.             image = Image.getInstance(baos.toByteArray()); 
  112.             Image.getInstance(baos.toByteArray()); 
  113.             image.setAbsolutePosition(0.0f,0.0f); 
  114.              
  115.             //4.3:添加到document中 
  116.             document.add(image); 
  117.             document.newPage(); 
  118.             baos.close(); 
  119.         } 
  120.          
  121.         //5:释放资源 
  122.         document.close(); 
  123.         pdfWr.close(); 
  124.          
  125.         return true
  126.     } 
  127.     /**
  128.      *
  129.      * @param source 源文件
  130.      * @param target 目标文件
  131.      * @param x 读取源文件中的第几页
  132.      */ 
  133.     private staticvoid pdfToJpg(String source,String target,int x)throws Exception { 
  134.         //创建从中读取和向其中写入(可选)的随机访问文件流,R表示对其只是访问模式 
  135.         RandomAccessFile rea = new RandomAccessFile(new File(source),"r"); 
  136.  
  137.         //将流读取到内存中,然后还映射一个PDF对象 
  138.         FileChannel channel = rea.getChannel(); 
  139.         ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY,0, channel.size()); 
  140.         PDFFile pdfFile = new PDFFile(buf); 
  141.         PDFPage page = pdfFile.getPage(x);   
  142.  
  143.         // get the width and height for the doc at the default zoom  
  144.         java.awt.Rectangle rect = new java.awt.Rectangle(0,0, (int) page.getBBox()   
  145.                 .getWidth(), (int) page.getBBox().getHeight());   
  146.  
  147.         // generate the image   
  148.         java.awt.Image img = page.getImage(rect.width, rect.height, // width & 
  149.                 rect, // clip rect 
  150.                 null, // null for the ImageObserver 
  151.                 true, // fill background with white 
  152.                 true // block until drawing is done 
  153.                 );   
  154.  
  155.         BufferedImage tag = new BufferedImage(rect.width, rect.height,   
  156.                 BufferedImage.TYPE_INT_RGB);   
  157.          
  158.         tag.getGraphics().drawImage(img, 0,0, rect.width, rect.height,   
  159.                 null);   
  160.         FileOutputStream out = new FileOutputStream(target);// 输出到文件流   
  161.         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
  162.         encoder.encode(tag); // JPEG编码   
  163.         out.close();         
  164.     } 
  165.     /**
  166.      * @param source  源PDF文件路径
  167.      * @param target  保存PDF文件路径
  168.      * @param pageNum  提取PDF中第pageNum页
  169.      * @throws Exception 
  170.      */ 
  171.     private staticvoid pdfExtraction(String source,String target,int pageNum)throws Exception{ 
  172.         //1:创建PDF读取对象 
  173.         PdfReader pr = new PdfReader(source); 
  174.         System.out.println("this document "+pr.getNumberOfPages()+" page"); 
  175.          
  176.         //2:将第page页转为提取,创建document对象 
  177.         Document doc = new Document(pr.getPageSize(pageNum)); 
  178.          
  179.         //3:通过PdfCopy转其单独存储 
  180.         PdfCopy copy = new PdfCopy(doc,new FileOutputStream(new File(target))); 
  181.         doc.open(); 
  182.         doc.newPage(); 
  183.          
  184.         //4:获取第1页,装载到document中。 
  185.         PdfImportedPage page = copy.getImportedPage(pr,pageNum); 
  186.         copy.addPage(page);  
  187.          
  188.         //5:释放资源 
  189.         copy.close(); 
  190.         doc.close(); 
  191.         pr.close(); 
  192.     } 
  193.     /**
  194.      * @param pdfFile 源PDF文件
  195.      * @param imgFile   图片文件
  196.      */ 
  197.     private staticvoid jpgToPdf(File pdfFile,File imgFile) throws Exception { 
  198.         //文件转img 
  199.         InputStream is = new FileInputStream(pdfFile); 
  200.         ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
  201.         for(int i;(i=is.read())!=-1;) 
  202.         { 
  203.             baos.write(i); 
  204.         } 
  205.         baos.flush(); 
  206.          
  207.         //取得图像的宽和高。 
  208.         Image img = Image.getInstance(baos.toByteArray()); 
  209.         float width = img.width(); 
  210.         float height = img.height(); 
  211.         img.setAbsolutePosition(0.0F,0.0F);//取消偏移 
  212.         System.out.println("width = "+width+"\theight"+height); 
  213.          
  214.         //img转pdf 
  215.         Document doc = new Document(new Rectangle(width,height)); 
  216.         PdfWriter pw = PdfWriter.getInstance(doc,new FileOutputStream(imgFile)); 
  217.         doc.open(); 
  218.         doc.add(img); 
  219.          
  220.         //释放资源 
  221.         System.out.println(doc.newPage()); 
  222.         pw.flush(); 
  223.         baos.close(); 
  224.         doc.close(); 
  225.         pw.close(); 
  226.     } 
  227.      
0 0
原创粉丝点击