java实现Img与PDF相互转换
本文实例为大家分享了java实现Img与PDF相互转换的具体代码,供大家参考,具体内容如下
不善于表达,就直接贴出代码吧。请大牛忽视我。
importjava.awt.image.BufferedImage;
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.InputStream;
importjava.io.RandomAccessFile;
importjava.nio.ByteBuffer;
importjava.nio.channels.FileChannel;
importjava.util.Map;
importjava.util.Map.Entry;
importjava.util.TreeMap;
importcom.Utils.ImgFileTool;
importcom.lowagie.text.Document;
importcom.lowagie.text.Image;
importcom.lowagie.text.Rectangle;
importcom.lowagie.text.pdf.PdfCopy;
importcom.lowagie.text.pdf.PdfImportedPage;
importcom.lowagie.text.pdf.PdfReader;
importcom.lowagie.text.pdf.PdfWriter;
importcom.sun.image.codec.jpeg.JPEGCodec;
importcom.sun.image.codec.jpeg.JPEGImageEncoder;
importcom.sun.pdfview.PDFFile;
importcom.sun.pdfview.PDFPage;
/**
*
*@authorhubiao
*@dateTime2014-06-07
*本工具对实现对IMG与PDF相互转换。
*运行测试需要导入以下2个jar包
*itext-2.0.2.jar
*PDFRenderer.jar
*
*/
@SuppressWarnings("unused")
publicclassImgPdfUtils{
publicstaticvoidmain(String[]args)throwsException{
//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(newFile("F:\\temp\\Project\\数据\\dfdsfds\\巴黎公社活动家传略_img").listFiles(),newFile("F:\\temp\\Project\\数据\\dfdsfds\\","巴黎公社活动家传略.pdf"));
}
privatestaticvoidlistOrder(){
File[]listFiles=newFile("F:\\temp\\Project\\数据\\dfdsfds\\巴黎公社活动家传略_img").listFiles();
TreeMaptree=newTreeMap();
for(Filef:listFiles)
{
tree.put(Integer.parseInt(f.getName().replaceAll(".jpg$","")),f);
}
for(Entryeif:tree.entrySet())
{
System.out.println(eif.getKey()+"="+eif.getValue().toString());
}
}
/**
*@paramlist图片集合
*@paramfile保存路径
*@returntrue,合并完成
*如果文件名不是1.jpg,2.jpg,3.jpg,4.jpg这样的。则需要自己重写TreeMap的排序方式!
*/
publicstaticbooleanimgMerageToPdf(File[]list,Filefile)throwsException{
//1:对图片文件通过TreeMap以名称进行自然排序
Mapmif=newTreeMap();
for(Filef:list)
mif.put(Integer.parseInt(f.getName().replaceAll(".jpg$","")),f);
//2:获取第一个Img的宽、高做为PDF文档标准
ByteArrayOutputStreambaos=newByteArrayOutputStream(2048*3);
InputStreamis=newFileInputStream(mif.get(1));
for(intlen;(len=is.read())!=-1;)
baos.write(len);
baos.flush();
Imageimage=Image.getInstance(baos.toByteArray());
floatwidth=image.width();
floatheight=image.height();
baos.close();
//3:通过宽高,实例化PDF文档对象。
Documentdocument=newDocument(newRectangle(width,height));
PdfWriterpdfWr=PdfWriter.getInstance(document,newFileOutputStream(file));
document.open();
//4:获取每一个图片文件,转为IMG对象。装载到Document对象中
for(Entryeif:mif.entrySet())
{
//4.1:读取到内存中
baos=newByteArrayOutputStream(2048*3);
is=newFileInputStream(eif.getValue());
for(intlen;(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();
returntrue;
}
/**
*
*@paramsource源文件
*@paramtarget目标文件
*@paramx读取源文件中的第几页
*/
privatestaticvoidpdfToJpg(Stringsource,Stringtarget,intx)throwsException{
//创建从中读取和向其中写入(可选)的随机访问文件流,R表示对其只是访问模式
RandomAccessFilerea=newRandomAccessFile(newFile(source),"r");
//将流读取到内存中,然后还映射一个PDF对象
FileChannelchannel=rea.getChannel();
ByteBufferbuf=channel.map(FileChannel.MapMode.READ_ONLY,0,channel.size());
PDFFilepdfFile=newPDFFile(buf);
PDFPagepage=pdfFile.getPage(x);
//getthewidthandheightforthedocatthedefaultzoom
java.awt.Rectanglerect=newjava.awt.Rectangle(0,0,(int)page.getBBox()
.getWidth(),(int)page.getBBox().getHeight());
//generatetheimage
java.awt.Imageimg=page.getImage(rect.width,rect.height,//width&
rect,//cliprect
null,//nullfortheImageObserver
true,//fillbackgroundwithwhite
true//blockuntildrawingisdone
);
BufferedImagetag=newBufferedImage(rect.width,rect.height,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img,0,0,rect.width,rect.height,
null);
FileOutputStreamout=newFileOutputStream(target);//输出到文件流
JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);//JPEG编码
out.close();
}
/**
*@paramsource源PDF文件路径
*@paramtarget保存PDF文件路径
*@parampageNum提取PDF中第pageNum页
*@throwsException
*/
privatestaticvoidpdfExtraction(Stringsource,Stringtarget,intpageNum)throwsException{
//1:创建PDF读取对象
PdfReaderpr=newPdfReader(source);
System.out.println("thisdocument"+pr.getNumberOfPages()+"page");
//2:将第page页转为提取,创建document对象
Documentdoc=newDocument(pr.getPageSize(pageNum));
//3:通过PdfCopy转其单独存储
PdfCopycopy=newPdfCopy(doc,newFileOutputStream(newFile(target)));
doc.open();
doc.newPage();
//4:获取第1页,装载到document中。
PdfImportedPagepage=copy.getImportedPage(pr,pageNum);
copy.addPage(page);
//5:释放资源
copy.close();
doc.close();
pr.close();
}
/**
*@parampdfFile源PDF文件
*@paramimgFile图片文件
*/
privatestaticvoidjpgToPdf(FilepdfFile,FileimgFile)throwsException{
//文件转img
InputStreamis=newFileInputStream(pdfFile);
ByteArrayOutputStreambaos=newByteArrayOutputStream();
for(inti;(i=is.read())!=-1;)
{
baos.write(i);
}
baos.flush();
//取得图像的宽和高。
Imageimg=Image.getInstance(baos.toByteArray());
floatwidth=img.width();
floatheight=img.height();
img.setAbsolutePosition(0.0F,0.0F);//取消偏移
System.out.println("width="+width+"\theight"+height);
//img转pdf
Documentdoc=newDocument(newRectangle(width,height));
PdfWriterpw=PdfWriter.getInstance(doc,newFileOutputStream(imgFile));
doc.open();
doc.add(img);
//释放资源
System.out.println(doc.newPage());
pw.flush();
baos.close();
doc.close();
pw.close();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。