TIF转PDF格式以及相关压缩ZIP包(详细内容看代码)

来源:互联网 发布:moe软件官网 编辑:程序博客网 时间:2024/06/06 15:44
/* ****************************************************************************
 * Author..:humingfeng
 * ****************************************************************************
 * 
 * Purpose.:Utility class to convert PDF documents to TIF images
 *          
 * ****************************************************************************
 */

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.media.jai.JAI;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
import javax.media.jai.PlanarImage;
import javax.media.jai.RenderedOp;
import javax.media.jai.TileCache;


import org.apache.log4j.Logger;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.PDimension;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;


import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.TIFFDecodeParam;
import com.sun.media.jai.codec.TIFFDirectory;
import com.sun.media.jai.codec.TIFFEncodeParam;
import com.sun.media.jai.codecimpl.TIFFImageDecoder;


/**
 * Utility class to convert PDF documents to TIF images 
 * 
 * @author Pedro J Rivera
 * 
 */
public class TIFConvertPDF extends TIFConvert {
/**
*/
private static final int PDF_DPI = 72;
private static Logger log = Logger.getLogger(TIFConvertPDF.class);


/**
* Convert PDF to a TIF and save to file
* @param pdf
* @param tif
* @return
*/
protected static void convert(String pdf, String tif) 
throws PDFException, PDFSecurityException, IOException {
convert(pdf, tif, DEFAULT_DPI, DEFAULT_COLOR, COMPRESSION_CCITT_T_6, DEFAULT_COMPRESSION_QUALITY);
}

/**
* Convert PDF to a ZIP which include TIF
* @param pdfInputStream
* @return byte[]
*/
protected static byte[] convert(InputStream pdfInputStream) {
byte[] data = null;
try {
data = convert(pdfInputStream, DEFAULT_DPI, DEFAULT_COLOR, COMPRESSION_CCITT_T_6, DEFAULT_COMPRESSION_QUALITY);
} catch (Exception e) {
e.printStackTrace();
}
return data;
}

/**
* Convert PDF to a TIF and save to file
* @param pdf
* @param tif
* @param dpi
* @param color
* @param compression
* @param quality
* @return
*/
protected static void convert(String pdf, String tif, int dpi, int color, int compression, float quality) 
throws PDFException, PDFSecurityException, IOException {
convert(getImageFromPDF(pdf, dpi, color, compression), tif, dpi, compression, quality);
}

/**
* Convert PDF to a ZIP which include TIF
* @param pdf
* @param tif
* @param dpi
* @param color
* @param compression
* @param quality
* @return
*/
protected static byte[] convert(InputStream pdfInputStream, int dpi, int color, int compression, float quality) 
throws PDFException, PDFSecurityException, IOException {
// return convertToZip(getImageFromPDF(pdfInputStream, dpi, color, compression), dpi, compression, quality);
return convertToZip(pdfInputStream, dpi, color, compression, quality);
}


/**
* Convert byte array PDF to a TIF and save to file
* @param pdf
* @param tif
* @param dpi
* @param color
* @param compression
* @param quality
* @return
*/
protected static void convert(byte[] pdf, String tif, int dpi, int color, int compression, float quality) 
throws PDFException, PDFSecurityException, IOException {
convert(getImageFromPDF(pdf, dpi, color, compression), tif, dpi, compression, quality);
}

/**
* Convert PDF to a TIF byte array
* @param pdf
* @param dpi
* @param color
* @param compression
* @param quality
* @return
*/
protected static byte[] convert(String pdf, int dpi, int color, int compression, float quality) 
throws PDFException, PDFSecurityException, Exception {
return convert(getImageFromPDF(pdf, dpi, color, compression), dpi, compression, quality);
}

/**
* Convert byte array PDF to a TIF and return as byte array
* @param pdf
* @param dpi
* @param color
* @param compression
* @param quality
* @return
*/
protected static byte[] convert(byte[] pdf, int dpi, int color, int compression, float quality) 
throws PDFException, PDFSecurityException, Exception {
return convert(getImageFromPDF(pdf, dpi, color, compression), dpi, compression, quality);
}

/**
* Convert buffered image and return ZIP as a byte array
* @param image
* @param dpi
* @param compression
* @param quality
* @return byte[]
* @throws IOException
*/
@SuppressWarnings("unused")
private static byte[] convertToZip(BufferedImage[] image, int dpi, int compression, float quality) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(bos);
ZipEntry entry = null;
String strName;
byte[] data = null;
byte[] result = null;
for (int i = 0; i < image.length; i++) {
strName = String.format("%05d", i + 1);
data = convert(image[i], dpi, compression, quality);
if (data != null) {
entry = new ZipEntry(strName + ".tif");
entry.setSize(data.length);
zip.putNextEntry(entry);
zip.write(data);
zip.closeEntry();
}
}
zip.close();
result = bos.toByteArray();
bos.close();
return result;
}

private static boolean isStop = true;
@SuppressWarnings("unused")
private static Thread thread = new Thread(new Runnable() {

@Override
public void run() {
while (isStop) {
System.out.println(Runtime.getRuntime().totalMemory());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});

private static byte[] convertToZip(InputStream pdfInputStream, int dpi, int color, int compression, float quality) throws PDFException, PDFSecurityException, IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(bos);
ZipEntry entry = null;
String strName;
byte[] data = null;
byte[] result = null;

Document pdfFile = new Document();
pdfFile.setInputStream(pdfInputStream, "whatever");
float scale;
float rotation = 0f;
int width;
int height;
int numPgs = pdfFile.getNumberOfPages();
PDimension pd;
Graphics2D g;
BufferedImage image;

// thread.start();
for (int i = 0; i < numPgs; i++) {
scale  = (float)dpi / PDF_DPI; 
pd = pdfFile.getPageDimension(i, rotation, scale);
width  = (int)pd.getWidth();
height = (int)pd.getHeight();
image = getBufferedImage(color, compression, width, height);
g = image.createGraphics();
// if (i == 0) {
// thread.start();
// }
pdfFile.paintPage(i, g, GraphicsRenderingHints.PRINT, Page.BOUNDARY_TRIMBOX, rotation, scale);
// isStop = false;
            g.dispose();
            log.info("读取PDF第" + (i + 1) + "页");
            
            strName = String.format("%05d", i + 1);
            data = convert(image, dpi, compression, quality);
            if (data != null) {
entry = new ZipEntry(strName + ".tif");
entry.setSize(data.length);
zip.putNextEntry(entry);
zip.write(data);
zip.closeEntry();
}
}
// isStop = false;

pdfFile.dispose();
zip.close();
result = bos.toByteArray();
bos.close();
return result;
}

/**
* Render a PDF document from byte array into a buffered image
* @param pdf
* @param dpi
* @param color
* @param compression
* @return
*/
private static BufferedImage[] getImageFromPDF(byte[] pdf, int dpi, int color, int compression)
throws PDFException, PDFSecurityException, IOException {
Document pdfFile = new Document();
pdfFile.setByteArray(pdf, 0, pdf.length, System.getProperty("java.io.tmpdir"));
return getImageFromPDF(pdfFile, dpi, color, compression);
}

/**
* Render a PDF document into a buffered image
* @param pdfInputStream
* @param dpi
* @param color
* @param compression
* @return
* @throws IOException 
* @throws PDFSecurityException 
* @throws PDFException 
*/
@SuppressWarnings("unused")
private static BufferedImage[] getImageFromPDF(InputStream pdfInputStream, int dpi, int color, int compression) 
throws PDFException, PDFSecurityException, IOException {
Document pdfFile = new Document();
pdfFile.setInputStream(pdfInputStream, "whatever");
return getImageFromPDF(pdfFile, dpi, color, compression);
}

/**
* Render a PDF document into a buffered image
* @param pdf
* @param dpi
* @param color
* @param compression
* @return
* @throws IOException 
* @throws PDFSecurityException 
* @throws PDFException 
*/
private static BufferedImage[] getImageFromPDF(String pdf, int dpi, int color, int compression) 
throws PDFException, PDFSecurityException, IOException {  
Document pdfFile = new Document();
pdfFile.setFile(pdf);
return getImageFromPDF(pdfFile, dpi, color, compression);
}

/**
* Render a PDF document into a buffered image
* @param pdf
* @param dpi
* @param color
* @param compression
* @return
*/
private static BufferedImage[] getImageFromPDF(Document pdf, int dpi, int color, int compression) {
float scale;
float rotation = 0f;
int width;
int height;
int numPgs = pdf.getNumberOfPages();


BufferedImage[] image = new BufferedImage[numPgs];
PDimension pd;
Graphics2D g;

for (int i = 0; i < numPgs; i++) {
scale  = (float)dpi / PDF_DPI; 
pd = pdf.getPageDimension(i, rotation, scale);
width  = (int)pd.getWidth();
height = (int)pd.getHeight();
image[i] = getBufferedImage(color, compression, width, height);
g = image[i].createGraphics();
            pdf.paintPage(i, g, GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX, rotation, scale);
            g.dispose();
            log.info("读取PDF第" + (i + 1) + "页");
}


pdf.dispose();


return image;
}

public static void tifToPdf(String filename, String[] strImages) {
com.lowagie.text.Document document = new com.lowagie.text.Document();


try {
FileOutputStream rech = new FileOutputStream(filename);
PdfWriter writer = PdfWriter.getInstance(document, rech);
document.open();
PdfContentByte cb = writer.getDirectContent();
for (int i = 0; i < strImages.length; ++i) {
addImage(strImages[i], document, cb);
}
} catch (Exception e) {
e.printStackTrace();
}
document.close();
}

public static byte[] tifToPdfFile(String filePath) {
int BUFFER = 4096; //cache buffer
String strEntry;
com.lowagie.text.Document document = new com.lowagie.text.Document();
FileInputStream fis = null;
ZipInputStream zis = null;
ZipFile zfile = null;
ByteArrayOutputStream byteOutput = null;
byte[] pdfData = null;
Map<String, File> map = new HashMap<String, File>();
List<String> listNames = new ArrayList<String>();
Random random = new Random();

try {
BufferedOutputStream dest = null;
fis = new FileInputStream(filePath);
zis = new ZipInputStream(fis);
ZipEntry entry;
byteOutput = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, byteOutput);
document.open();
PdfContentByte cb = writer.getDirectContent();

while ((entry = zis.getNextEntry()) != null) {
int count;
byte data[] = new byte[BUFFER];
strEntry = entry.getName();
System.out.println("zip entry name:" + strEntry);
if (!strEntry.endsWith(".tif")) {
continue;
}

File entryFile = new File(random.nextInt() + System.currentTimeMillis() + strEntry);
FileOutputStream fos = new FileOutputStream(entryFile);
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
map.put(strEntry.substring(0,strEntry.indexOf(".")), entryFile);
listNames.add(strEntry.substring(0,strEntry.indexOf(".")));
}
Collections.sort(listNames);
for (int i = 0; i < listNames.size(); i++) {
File fileTemp = new File("temp" + random.nextInt() + System.currentTimeMillis() + ".tif");
TIFConvertImage.convert(map.get(listNames.get(i)), fileTemp);
map.get(listNames.get(i)).deleteOnExit();
addImage(fileTemp, document, cb);
fileTemp.deleteOnExit();
}


document.close();
if (byteOutput != null) {
pdfData = byteOutput.toByteArray();
}
} catch (Exception cwj) {
cwj.printStackTrace();
} finally {
try {
if (zis != null) {
zis.close();
}
if (zfile != null) {
zfile.close();
}
if (fis != null) {
fis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}


return pdfData;
}

@SuppressWarnings("unchecked")
public static byte[] tifToPdf(String filePath) throws Exception{
String strEntry;
com.lowagie.text.Document document = new com.lowagie.text.Document();
ZipFile zfile = null;
ByteArrayOutputStream byteOutput = null;
byte[] pdfData = null;

try {
zfile = new ZipFile(new File(filePath));
Enumeration e = zfile.entries();
ZipEntry entry;
byteOutput = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, byteOutput);
document.open();
PdfContentByte cb = writer.getDirectContent();

byte[] dataTemp;
while (e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
strEntry = entry.getName();
if (!strEntry.endsWith(".tif")) {
continue;
}
InputStream in = zfile.getInputStream(entry);
dataTemp = TIFConvertImage.convert(in);
InputStream inTemp = new ByteArrayInputStream(dataTemp);
addImage(inTemp, document, cb);
in.close();
inTemp.close();
}


document.close();
if (byteOutput != null) {
pdfData = byteOutput.toByteArray();
}
} catch (Exception cwj) {
cwj.printStackTrace();
throw cwj;
} finally {
try {
if (zfile != null) {
zfile.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}


return pdfData;
}

public static void tifToPdf(String filePath,String output) throws Exception{
String strEntry;
com.lowagie.text.Document document = new com.lowagie.text.Document();
ZipFile zfile = null;
ByteArrayOutputStream byteOutput = null;
byte[] pdfData = null;
FileOutputStream fos = null;

try {
zfile = new ZipFile(new File(filePath));
Enumeration e = zfile.entries();
ZipEntry entry;
byteOutput = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, byteOutput);
document.open();
PdfContentByte cb = writer.getDirectContent();

byte[] dataTemp;
while (e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
strEntry = entry.getName();
if (!strEntry.endsWith(".tif")) {
continue;
}
InputStream in = zfile.getInputStream(entry);
dataTemp = TIFConvertImage.convert(in);
InputStream inTemp = new ByteArrayInputStream(dataTemp);
addImage(inTemp, document, cb);
in.close();
inTemp.close();
}


document.close();
if (byteOutput != null) {
pdfData = byteOutput.toByteArray();
fos = new FileOutputStream(output);
fos.write(pdfData);
fos.close();
}
} catch (Exception cwj) {
cwj.printStackTrace();
throw cwj;
} finally {
try {
if (zfile != null) {
zfile.close();
}
if (null != fos) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

@SuppressWarnings("unchecked")
public static void addImage(InputStream in, com.lowagie.text.Document document, PdfContentByte cb) throws Exception {
TileCache cache = JAI.getDefaultInstance().getTileCache();
long size = 1024 * 1024 * 1024L; // 32 megabytes
cache.setMemoryCapacity(size);


SeekableStream stream = SeekableStream.wrapInputStream(in, true);
stream.seek(0);
TIFFDirectory dir = new TIFFDirectory(stream, 0);
String[] names = ImageCodec.getDecoderNames(stream);
ImageDecoder dec = ImageCodec
.createImageDecoder(names[0], stream, null);
int total = dec.getNumPages();


for (int k = 0; k < total; ++k) {
RenderedImage ri = dec.decodeAsRenderedImage(k);
Raster ra = ri.getData();


BufferedImage bi = new BufferedImage(ri.getColorModel(),
Raster.createWritableRaster(ri.getSampleModel(),
ra.getDataBuffer(), null), false, new Hashtable());
Image img = Image.getInstance(bi, null, true);
long h = 0;
long w = 0;
long IFDOffset = dir.getIFDOffset();
while (IFDOffset != 0L) {
dir = new TIFFDirectory(stream, IFDOffset, 0);
IFDOffset = dir.getNextIFDOffset();
h = dir.getFieldAsLong(TIFFImageDecoder.TIFF_IMAGE_LENGTH);
w = dir.getFieldAsLong(TIFFImageDecoder.TIFF_IMAGE_WIDTH);
}
float percent = 100;
int pos = 0;
if (w > 895)
percent = ((595 + 18) * 100 / w);
if (h > 842)
pos = (int) (842 - h * percent / 100);
else
pos = (int) (842 - h);
System.out.println(percent);
System.out.println(pos);
img.scalePercent(percent);
img.setAbsolutePosition(0, pos);
System.out.println("Image: " + k);


cb.addImage(img);
document.newPage();
}
stream.close();
}

@SuppressWarnings("unchecked")
private static void addImage(File tiffFile, com.lowagie.text.Document document, PdfContentByte cb) throws Exception {
TileCache cache = JAI.getDefaultInstance().getTileCache();
long size = 1024 * 1024 * 1024L; // 32 megabytes
cache.setMemoryCapacity(size);


SeekableStream stream = new FileSeekableStream(tiffFile);
// SeekableStream.wrapInputStream(r, true);
// stream.seek(0);
TIFFDirectory dir = new TIFFDirectory(stream, 0);
String[] names = ImageCodec.getDecoderNames(stream);
ImageDecoder dec = ImageCodec
.createImageDecoder(names[0], stream, null);
int total = dec.getNumPages();


for (int k = 0; k < total; ++k) {
RenderedImage ri = dec.decodeAsRenderedImage(k);
Raster ra = ri.getData();


BufferedImage bi = new BufferedImage(ri.getColorModel(),
Raster.createWritableRaster(ri.getSampleModel(),
ra.getDataBuffer(), null), false, new Hashtable());
Image img = Image.getInstance(bi, null, true);
long h = 0;
long w = 0;
long IFDOffset = dir.getIFDOffset();
while (IFDOffset != 0L) {
dir = new TIFFDirectory(stream, IFDOffset, 0);
IFDOffset = dir.getNextIFDOffset();
h = dir.getFieldAsLong(TIFFImageDecoder.TIFF_IMAGE_LENGTH);
w = dir.getFieldAsLong(TIFFImageDecoder.TIFF_IMAGE_WIDTH);
}
float percent = 100;
int pos = 0;
if (w > 895)
percent = ((595 + 18) * 100 / w);
if (h > 842)
pos = (int) (842 - h * percent / 100);
else
pos = (int) (842 - h);
System.out.println(percent);
System.out.println(pos);
img.scalePercent(percent);
img.setAbsolutePosition(0, pos);
System.out.println("Image: " + k);


cb.addImage(img);
document.newPage();
}
stream.close();
tiffFile.deleteOnExit();
}

@SuppressWarnings("unchecked")
public static void addImage(String strImageName, com.lowagie.text.Document document, PdfContentByte cb) throws Exception {
TileCache cache = JAI.getDefaultInstance().getTileCache();
long size = 1024 * 1024 * 1024L; // 32 megabytes
cache.setMemoryCapacity(size);


File file = new File(strImageName);
SeekableStream stream = new FileSeekableStream(file);
TIFFDirectory dir = new TIFFDirectory(stream, 0);
String[] names = ImageCodec.getDecoderNames(stream);
ImageDecoder dec = ImageCodec
.createImageDecoder(names[0], stream, null);
int total = dec.getNumPages();
ImageInputStream in = null;
in = ImageIO.createImageInputStream(file);


for (int k = 0; k < total; ++k) {
RenderedImage ri = dec.decodeAsRenderedImage(k);
Raster ra = ri.getData();
BufferedImage bi = new BufferedImage(ri.getColorModel(),
Raster.createWritableRaster(ri.getSampleModel(),
ra.getDataBuffer(), null), false, new Hashtable());
Image img = Image.getInstance(bi, null, true);
long h = 0;
long w = 0;
long IFDOffset = dir.getIFDOffset();
while (IFDOffset != 0L) {
dir = new TIFFDirectory(stream, IFDOffset, 0);
IFDOffset = dir.getNextIFDOffset();
h = dir.getFieldAsLong(TIFFImageDecoder.TIFF_IMAGE_LENGTH);
w = dir.getFieldAsLong(TIFFImageDecoder.TIFF_IMAGE_WIDTH);
}
float percent = 100;
int pos = 0;
if (w > 895)
percent = ((595 + 18) * 100 / w);
if (h > 842)
pos = (int) (842 - h * percent / 100);
else
pos = (int) (842 - h);
System.out.println(percent);
System.out.println(pos);
img.scalePercent(percent);
img.setAbsolutePosition(0, pos);
System.out.println("Image: " + k);


cb.addImage(img);
document.newPage();
}
stream.close();
if (in != null) {
in.close();
}
file.deleteOnExit();
}


public static  long saveFile(byte[] tifCopy, String fileNamesWithoutSuffix,
String ext) throws Exception {
FileOutputStream fos = null;
long size = 0;
try {
String file = fileNamesWithoutSuffix + ext;
fos = new FileOutputStream(file);
fos.write(tifCopy);
fos.close();
} catch (Exception e) {
throw e;
} finally {
try {
if (null != fos) {
fos.close();
}
} catch (IOException e) {
throw e;
}
}
return size;
}

public static void main(String[] args) throws Exception {




// byte[] pdfBytes = tifToPdf("C:/work/gwssi/PATPIC_201130489956X.zip") ;
// saveFile(pdfBytes, "C:/work/gwssi/PATPIC_201130489956X",".pdf");
// System.out.println(pdfBytes.length);

// File f = new File("C:/work/1.pdf");
// File fo = new File("C:/work/2.pdf");
// FileInputStream s = new FileInputStream(f);
// FileOutputStream o = new FileOutputStream(fo);
// byte[] buff = new byte[1024];
// int len = 0; 
// while ((len = s.read(buff)) != -1) { 
// o.write(buff, 0, len); 
//
// s.close(); 
// o.close(); 

mergeZipToPdf("C:/Users/dell/Desktop/EXEC20150514000019.zip","C:/Users/dell/Desktop/EXEC20150514000019.pdf",0,13);
}

/**
* @param files 需要合成的zip格式文件
* @param outputPdf 合成后pdf的保存路径
* @param startPage zip压缩包内合成选择的开始tif文件
* @param endPage zip压缩包内合成选择的结束tif文件
* @throws Exception
*/
public static void mergeZipToPdf(String inputZip,String outputPdf,int startPage,int endPage) throws Exception {
ZipFile zfile = null;
ByteArrayOutputStream byteOutput = null;
FileOutputStream fos = null;
byte[] dataTemp;
try {
com.lowagie.text.Document document = new com.lowagie.text.Document();
byteOutput = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, byteOutput);
document.open();
PdfContentByte cb = writer.getDirectContent();
zfile = new ZipFile(new File(inputZip));
for(int i=startPage; i<=endPage; i++){
ZipEntry entry = zfile.getEntry((i)+".tif");
if(entry==null) entry = zfile.getEntry((i)+"_fy.tif");
if(entry==null) entry = zfile.getEntry((i)+".TIF");
if(entry==null) entry = zfile.getEntry((i)+"_FY.TIF");
if(entry==null) entry = zfile.getEntry(String.format("%06d",(i))+".tif");
if(entry==null) entry = zfile.getEntry(String.format("%06d",(i))+"_fy.tif");
if(entry==null) entry = zfile.getEntry(String.format("%06d",(i))+".TIF");
if(entry==null) entry = zfile.getEntry(String.format("%06d",(i))+"_FY.TIF");

InputStream in = zfile.getInputStream(entry);
dataTemp = TIFConvertImage.convert(in);
InputStream inTemp = new ByteArrayInputStream(dataTemp);
addImage(inTemp, document, cb);
in.close();
inTemp.close();
}
document.close();
if (byteOutput != null) {
fos = new FileOutputStream(outputPdf);
fos.write(byteOutput.toByteArray());
fos.close();
}

} catch (Exception e2) {
e2.printStackTrace();
} finally{
if(fos!=null)fos.close();
if(byteOutput!=null)byteOutput.close();
if(zfile!=null)zfile.close();
}
}



/**
* @param files
*            需要合成的zip格式文件
* @param output
*            合成后tif的保存路径
* @param startPage
*            zip压缩包内合成选择的开始tif文件
* @param endPage
*            zip压缩包内合成选择的结束tif文件
* @throws Exception
*/
public static Map<String, Long> mergeZipToTif(String inputZip,String outputTif, int startPage, int endPage, int orStart) throws Exception {
Map<String,Long> m = new HashMap<String,Long>();
long attchSize = 0l;
long attchPages = 0l;
ZipFile zfile = null;
// OutputStream output = null;
// InputStream in = null;
if(!(outputTif.endsWith(".tif")||outputTif.endsWith(".tiff"))) throw new Exception("not a tiff for output!");
if(startPage>endPage)  {
m.put("attchSize", attchSize);
m.put("attchPages", new Long(endPage-startPage+1));
return m;
}

String ouputTemp = outputTif.substring(0,outputTif.lastIndexOf(".tif"));
File dc = new File(ouputTemp);
if(!dc.exists()) dc.mkdirs();
List<InputStream> ins = new ArrayList<InputStream>();
try {
zfile = new ZipFile(new File(inputZip));
int fileSize = zfile.size();
if(endPage!=0) {
fileSize = endPage-startPage+1;
}

int middleEndPage=0;
if(orStart==1&&endPage==0){
middleEndPage=1;
}

for(int i=startPage; i<=(endPage==0?(middleEndPage==1?0:(fileSize-1)):endPage); i++){

ZipEntry entry = zfile.getEntry((i+1)+".tif");
if(entry==null) entry = zfile.getEntry((i+1)+"_fy.tif");
if(entry==null) entry = zfile.getEntry((i+1)+".TIF");
if(entry==null) entry = zfile.getEntry((i+1)+"_FY.TIF");
if(entry==null) entry = zfile.getEntry(String.format("%06d",(i+1))+".tif");
if(entry==null) entry = zfile.getEntry(String.format("%06d",(i+1))+"_fy.tif");
if(entry==null) entry = zfile.getEntry(String.format("%06d",(i+1))+".TIF");
if(entry==null) entry = zfile.getEntry(String.format("%06d",(i+1))+"_FY.TIF");
if(entry==null) entry = zfile.getEntry(String.format("%05d",(i+1))+".tif");
if(entry==null) entry = zfile.getEntry(String.format("%05d",(i+1))+"_fy.tif");
if(entry==null) entry = zfile.getEntry(String.format("%04d",(i+1))+".TIF");
if(entry==null) entry = zfile.getEntry(String.format("%05d",(i+1))+".TIF");
if(entry==null) entry = zfile.getEntry(String.format("%05d",(i+1))+"_FY.TIF");

if(entry!=null){
ins.add(zfile.getInputStream(entry));
}
}


attchPages = ins.size();
System.out.println("attchPages:"+attchPages);
//检查文件大小是否存在OKB
if(attchPages == 0){
return null;
}

if(ins!=null&&ins.size()>0&&attchPages<1001) {
//检查ZIP内容
boolean checkFlag = true;
for(InputStream itemFile:ins){
long itemFileLength = itemFile.available();
if(itemFileLength==0L){
checkFlag = false;
break;
}
}


if(checkFlag){
attchSize = merge(ins,outputTif);
}

attchPages = ins.size();
}


} catch (Exception e2) {
e2.printStackTrace();
log.debug("attch error: ",e2);
} /*finally{
if(output!=null)output.close();
if(in!=null)in.close();
if(zfile!=null)zfile.close();
}*/


finally{
for(InputStream in:ins){
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

if(zfile!=null){
try {
zfile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}



// File[] f = dc.listFiles();
// for(int i=0;i<f.length;i++){
// f[i].delete();
// }
// dc.delete();

m.put("attchSize", attchSize);
m.put("attchPages", attchPages);
return m;
}


/**
* @param files
*            需要合成的tif
* @param output
*            合成后tif的保存路径
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static int merge(List<InputStream> ins, String output) throws Exception {
BufferedImage[] bufferedImage = new BufferedImage[ins.size()];
for (int i = 0; i < ins.size(); i++) {
// InputStream in = new FileInputStream(files[i]);
bufferedImage[i] = ImageIO.read(ins.get(i));
}

OutputStream ss = new FileOutputStream(output);
byte[] b = TIFFUtil.converts(bufferedImage, 72, TIFFEncodeParam.COMPRESSION_GROUP4, 300);
ss.write(b);
ss.close();
return b.length;
}

/**
* @param files 需要合成的tif
* @param output 合成后zip的保存路径
* @throws IOException 
* @throws Exception
*/
public static long mergeTiffToZip(String tifPath, String output)
throws Exception {
File file = new File(tifPath);
SeekableStream s = null;
TIFFDecodeParam param = null;
RenderedImage op = null;
FileOutputStream baos = null;
ZipOutputStream zipOut = null;
long size = 0l;
try {
s = new FileSeekableStream(file);
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
int numofpages = dec.getNumPages();
baos = new FileOutputStream(new File(output));
zipOut = new ZipOutputStream(baos);
for (int i = 0; i < numofpages; i++) {
op = new NullOpImage(dec.decodeAsRenderedImage(i), null, null,
OpImage.OP_COMPUTE_BOUND);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(op, "tif", bos);
byte[] imageBytes = bos.toByteArray();
size = size+imageBytes.length;
bos.close();
zipOut.putNextEntry(new ZipEntry(String.format("%05d", i + 1) + ".tif"));
zipOut.write(imageBytes);
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception();
} finally {
try {
if (zipOut != null)
zipOut.close();
if (baos != null)
baos.close();
if (s != null)
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return size;
}


}
1 0
原创粉丝点击