(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 files = new ArrayList();
	        List deleteFiles = new ArrayList();
	        
	        
	        for(int i=0;i
/**
	 * 将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 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();
		}
	}



你可能感兴趣的:(JavaEE)