Java實現HTML轉JPG,TIFF等圖片格式和TIFF圖片合并功能解決方案。
上一篇文章說到了HTML轉PDF的實現方式,而就在那個需求的另外一個方面,項目要求要實現頁面轉圖片的需求,主要是JPG,TIFF,PNG等格式。弄得我有點囧,上次一直沒搞定。也沒找到合適的工具進行轉換。
前一小段時間,發現Apache的一個開源工具,可以把PDF轉成圖片,沒有直接從HTML轉圖片的jar包,就只能曲線救國了。
忘了介紹了。PDF轉圖片的包叫做apache pdfBox 右邊是:pdfbox的官網 pdfBox官網
下面直接貼代碼了:
public void convertToTiff(String pdfFilePath, String tiffFileName) throws Exception { PDDocument doc = PDDocument.load(pdfFilePath); int pageCount = doc.getPageCount(); List pages = doc.getDocumentCatalog().getAllPages(); List<File> files = new ArrayList<File>(); List<File> deleteFiles = new ArrayList<File>(); for(int i=0;i<pages.size();i++){ PDPage page = (PDPage)pages.get(i); BufferedImage image = page.convertToImage(BufferedImage.TYPE_BYTE_BINARY, 300); Iterator iter = ImageIO.getImageWritersBySuffix("jpg"); ImageWriter writer = (ImageWriter)iter.next(); File outFile = new File("C:/1"+i+".jpg"); FileOutputStream out = new FileOutputStream(outFile); ImageOutputStream outImage = ImageIO.createImageOutputStream(out); writer.setOutput(outImage); writer.write(new IIOImage(image,null,null)); this.jpg2tif("C:/1"+i+".jpg", "C:/1"+i+".tif"); files.add(new File("C:/1"+i+".tif")); deleteFiles.add(outFile); deleteFiles.add(new File("C:/1"+i+".tif")); outImage.close(); out.close(); writer.dispose(); } if(files != null){ this.tif2Marge(files, "C:/1.tif"); } }
/** * 將jpg格式轉化為tif格式。 * @param srcFile 需要裝換的源文件 * @param descFile 裝換后的轉存文件 * @throws Exception */ public void jpg2tif(String srcFile, String descFile) throws Exception { RenderedOp src = JAI.create("fileload", srcFile); OutputStream os = new FileOutputStream(descFile); TIFFEncodeParam param = new TIFFEncodeParam(); param.setCompression(TIFFEncodeParam.COMPRESSION_JPEG_TTN2); ImageEncoder encoder = ImageCodec.createImageEncoder("TIFF", os, param); encoder.encode(src); os.close(); } /** * 將若干tif文件合同為一個tif文件 * @param srcFile * @param descFile * @throws Exception */ public void tif2Marge(List<File> srcFile, String descFile) throws Exception { List pages = new ArrayList(srcFile.size() - 1); for (int i = 0; i < srcFile.size(); i++) { RenderedOp firstpage = JAI.create("fileload", srcFile.get(0).getCanonicalPath()); if(i != 0 ){ RenderedOp page = JAI.create("fileload", srcFile.get(i).getCanonicalPath()); pages.add(page); } OutputStream os = new FileOutputStream(descFile); TIFFEncodeParam param = new TIFFEncodeParam(); param.setCompression(TIFFEncodeParam.COMPRESSION_JPEG_TTN2); param.setExtraImages(pages.iterator()); ImageEncoder encoder = ImageCodec.createImageEncoder("TIFF", os, param); encoder.encode(firstpage); firstpage.dispose(); for (int j = 1; j < pages.size(); j++) { ((RenderedOp) pages.get(j)).dispose(); } os.close(); pages.clear(); } }轉自:http://blog.csdn.net/jasonchris/article/details/7729130
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!