易捷 > PDF教程 > PDF开发/编程技术 >

Java将tiff格式图片转化为PDF格式文件代码

分享到:
发布时间:2013-05-21 18:00   浏览次数:

package com.netcode.pdf;

import java.io.*;

import java.awt.image.RenderedImage;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.util.Hashtable;

import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
import com.sun.media.jai.codec.*;
import com.sun.media.jai.codecimpl.*;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageCodec;

public class TiffToPDF {
Document document;
PdfContentByte cb;

public TiffToPDF(String filename, String[] strImages) throws Exception {
document = new Document();
FileOutputStream rech = new FileOutputStream(filename);
PdfWriter writer = PdfWriter.getInstance(document, rech);
document.open();
cb = writer.getDirectContent();
for (int i = 0; i < strImages.length; ++i) {
addImage(strImages[i]);
}

document.close();
}

public void addImage(String strImageName) throws Exception {
System.out.println(strImageName);
File file = new File(strImageName);
SeekableStream stream = new FileSeekableStream(strImageName);
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();
file.delete();
}

public static void main(String[] args) {
try {
String[] temp = {"1.tiff", "2.tiff", "3.tiff"};
TiffToPDF build = new TiffToPDF("temp.pdf", temp);

} catch (Exception e) {
e.printStackTrace();
}
}

}

 

相关文章推荐

易捷服务大全

在线PDF转换工具

Word

在线Word转PDF

http://wordtopdf.yjpdf.com
 
Excel

在线Excel转PDF

http://exceltopdf.yjpdf.com
 
PPT

在线PPT转PDF

http://ppttopdf.yjpdf.com

本类最新文章

本类本月热门

大家在关注…