国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Java > 正文

java實現Img與PDF相互轉換

2024-07-14 08:40:33
字體:
來源:轉載
供稿:網友

本文實例為大家分享了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();   }    } 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 梁山县| 五台县| 汝城县| 玛沁县| 渭源县| 葫芦岛市| 聊城市| 泗阳县| 金塔县| 牙克石市| 玛多县| 邓州市| 盐源县| 揭西县| 荆门市| 桃江县| 洛浦县| 临湘市| 文登市| 潮州市| 大理市| 潍坊市| 沂水县| 陆丰市| 金寨县| 易门县| 乐都县| 得荣县| 普定县| 贵南县| 乌什县| 炉霍县| 郁南县| 凭祥市| 田东县| 河西区| 定远县| 安溪县| 章丘市| 定兴县| 库伦旗|