java实现Img与PDF相互转换

http://blog.csdn.net/hubiao_0618/article/details/29226883?utm_source=tuicool&utm_medium=referral

https://github.com/itext/itextpdf 实现

import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.RandomAccessFile;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

import java.util.Map;

import java.util.Map.Entry;

import java.util.TreeMap;

import com.Utils.ImgFileTool;

import com.lowagie.text.Document;

import com.lowagie.text.Image;

import com.lowagie.text.Rectangle;

import com.lowagie.text.pdf.PdfCopy;

import com.lowagie.text.pdf.PdfImportedPage;

import com.lowagie.text.pdf.PdfReader;

import com.lowagie.text.pdf.PdfWriter;

import com.sun.image.codec.jpeg.JPEGCodec;

import com.sun.image.codec.jpeg.JPEGImageEncoder;

import com.sun.pdfview.PDFFile;

import com.sun.pdfview.PDFPage;

/**

*

* @author hubiao

* @dateTime 2014-06-07

*本工具对实现对IMG与PDF相互转换。

*运行测试需要导入以下2个jar包

*itext-2.0.2.jar

*PDFRenderer.jar

*

*/

@SuppressWarnings("unused")

public class ImgPdfUtils {

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

//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(new File("F:\\temp\\Project\\数据\\dfdsfds\\巴黎公社活动家传略_img").listFiles(),new File("F:\\temp\\Project\\数据\\dfdsfds\\","巴黎公社活动家传略.pdf"));

}

private static void listOrder() {

File[] listFiles = new File("F:\\temp\\Project\\数据\\dfdsfds\\巴黎公社活动家传略_img").listFiles();

TreeMap tree = new TreeMap();

for(File f : listFiles)

{

tree.put(Integer.parseInt(f.getName().replaceAll(".jpg$", "")), f);

}

for(Entry eif : tree.entrySet())

{

System.out.println(eif.getKey()+"="+eif.getValue().toString());

}

}

/**

* @param list图片集合

* @param file 保存路径

* @returntrue,合并完成

* 如果文件名不是1.jpg,2.jpg,3.jpg,4.jpg这样的。则需要自己重写TreeMap的排序方式!

*/

public static boolean imgMerageToPdf(File[] list, File file)throws Exception {

//1:对图片文件通过TreeMap以名称进行自然排序

Map mif = new TreeMap();

for(File f : list)

mif.put(Integer.parseInt(f.getName().replaceAll(".jpg$", "")), f);

//2:获取第一个Img的宽、高做为PDF文档标准

ByteArrayOutputStream baos = new ByteArrayOutputStream(2048*3);

InputStream is = new FileInputStream(mif.get(1));

for(int len;(len=is.read())!=-1;)

baos.write(len);

baos.flush();

Image image = Image.getInstance(baos.toByteArray());

float width = image.width();

float height = image.height();

baos.close();

//3:通过宽高 ,实例化PDF文档对象。

Document document = new Document(new Rectangle(width,height));

PdfWriter pdfWr = PdfWriter.getInstance(document, new FileOutputStream(file));

document.open();

//4:获取每一个图片文件,转为IMG对象。装载到Document对象中

for(Entry eif : mif.entrySet())

{

//4.1:读取到内存中

baos = new ByteArrayOutputStream(2048*3);

is = new FileInputStream(eif.getValue());

for(int len;(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();

return true;

}

/**

*

* @param source 源文件

* @param target 目标文件

* @param x读取源文件中的第几页

*/

private static void pdfToJpg(String source,String target,int x) throws Exception {

//创建从中读取和向其中写入(可选)的随机访问文件流,R表示对其只是访问模式

RandomAccessFile rea = new RandomAccessFile(new File(source), "r");

//将流读取到内存中,然后还映射一个PDF对象

FileChannel channel = rea.getChannel();

ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY,0, channel.size());

PDFFile pdfFile = new PDFFile(buf);

PDFPage page = pdfFile.getPage(x);

// get the width and height for the doc at the default zoom

java.awt.Rectangle rect = new java.awt.Rectangle(0, 0, (int) page.getBBox()

.getWidth(), (int) page.getBBox().getHeight());

// generate the image

java.awt.Image img = page.getImage(rect.width, rect.height, // width &

rect, // clip rect

null, // null for the ImageObserver

true, // fill background with white

true // block until drawing is done

);

BufferedImage tag = new BufferedImage(rect.width, rect.height,

BufferedImage.TYPE_INT_RGB);

tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height,

null);

FileOutputStream out = new FileOutputStream(target); // 输出到文件流

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

encoder.encode(tag); // JPEG编码

out.close();

}

/**

* @param source 源PDF文件路径

* @param target 保存PDF文件路径

* @param pageNum 提取PDF中第pageNum页

* @throws Exception

*/

private static void pdfExtraction(String source,String target,int pageNum) throws Exception{

//1:创建PDF读取对象

PdfReader pr = new PdfReader(source);

System.out.println("this document "+pr.getNumberOfPages()+" page");

//2:将第page页转为提取,创建document对象

Document doc = new Document(pr.getPageSize(pageNum));

//3:通过PdfCopy转其单独存储

PdfCopy copy = new PdfCopy(doc, new FileOutputStream(new File(target)));

doc.open();

doc.newPage();

//4:获取第1页,装载到document中。

PdfImportedPage page = copy.getImportedPage(pr,pageNum);

copy.addPage(page);

//5:释放资源

copy.close();

doc.close();

pr.close();

}

/**

* @param pdfFile 源PDF文件

* @param imgFile图片文件

*/

private static void jpgToPdf(File pdfFile,File imgFile) throws Exception {

//文件转img

InputStream is = new FileInputStream(pdfFile);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

for(int i;(i=is.read())!=-1;)

{

baos.write(i);

}

baos.flush();

//取得图像的宽和高。

Image img = Image.getInstance(baos.toByteArray());

float width = img.width();

float height = img.height();

img.setAbsolutePosition(0.0F, 0.0F);//取消偏移

System.out.println("width = "+width+"\theight"+height);

//img转pdf

Document doc = new Document(new Rectangle(width,height));

PdfWriter pw = PdfWriter.getInstance(doc,new FileOutputStream(imgFile));

doc.open();

doc.add(img);

//释放资源

System.out.println(doc.newPage());

pw.flush();

baos.close();

doc.close();

pw.close();

}

}

java 图片合并成pdf_java实现Img与PDF相互转换相关推荐

  1. java 图片合并成pdf_Java中PDF的转换(图片)与展示

    解决的问题 有些时候我们需要在项目中展示PDF,但是直接在浏览器中加入PDF展示的插件,存在兼容性问题,某些浏览器显示效果不理想,所以我们可以将PDF转为图片,然后已图片的方式展示,效果很好. 那么怎 ...

  2. java 图片合并成pdf_java将多张图片合并转为PDF

    [实例简介] [实例截图] [核心代码] package weaver.gy.util; import java.awt.image.BufferedImage; import java.io.Fil ...

  3. jpg怎么合成一份_如何将多张JPG图片合并成一个GIF?

    原标题:如何将多张JPG图片合并成一个GIF? 今天是广东入秋成功的某一天,虽然天气变冷了,但外面的紫外线还是毒辣得很,所以大家还是在室内跟小编一起研究教程方案吧! 今天要给大家介绍的是将多张静图合并 ...

  4. 图片合并成PDF,两个PDF的合并

    需求: 将多张手机照片合并成一个PDF,并于另一个成型PDF合并 过程: 使用全能扫描王处理一遍,拆剪掉多余部分,并提高亮度增加文字对比度 合并: 使用Faststone Capture合并图片即可. ...

  5. 如何将多个图片合并成一个pdf?

    如何将多个图片合并成一个pdf?我们在办公中会遇到各种各样的问题,遇到问题的时候一定要静下心里好好的想一想方法,所以让我们从一些简单的策略方法开始,让我们的工作效率提升起来.我们在办公中会遇到这种情况 ...

  6. 两个pdf怎么打开成两个窗口_如何将图片合并成PDF?教你两个免费方法

    我们都知道图片只能一张张查看,如果数量较多就比较麻烦了,所以经常会将图片合并转成PDF文件更方便.那么分享两个免费图片转PDF的方法给大家. 方法1:PDF编辑器合并 其实PDF编辑器除了编辑PDF格 ...

  7. java 图片合并_Java如何实现图片的叠加与拼接操作

    关于Java实现图片的叠加与拼接的文章网络上确实很多,碰巧小编开发工作中也遇到这些问题,就做了简要的梳理,作为笔记以备不时之需. Java对图片的处理主要使用的是BufferedImage类. Buf ...

  8. 如何将图片合并成PDF?教你两个免费方法

    我们都知道图片只能一张张查看,如果数量较多就比较麻烦了,所以经常会将图片合并转成PDF文件更方便.那么分享两个免费图片转PDF的方法给大家. 方法1:PDF编辑器合并 其实PDF编辑器除了编辑PDF格 ...

  9. 怎样将图片合并成一个PDF文档

    图片转pdf就是将一些图片文件合并成一个PDF格式的文档,那具体怎样操作?又有哪些方法可以把图片转pdf? 首先可以用jpg转换成pdf软件来实现,首先在工具中的其他文件转pdf类型中选择" ...

最新文章

  1. fastjson的使用问题
  2. bat脚本调用函数 简单列子
  3. 自己的JS 监听器。用于选择文字
  4. c语言e怎么表示_来测测!这11个C语言入门基础知识你都掌握了吗?
  5. mysql删除不安全的账户_【20200407】MySQL账号不规则删除导致权限错误
  6. Numpy 笔记: 多维数组的切片(slicing)和索引(indexing)【转】
  7. uni-app获取当前具体日期时间并将其格式化
  8. win7中安装redis
  9. Win10系列:C#应用控件进阶10
  10. 一块带给无数人年少欢乐的CPU
  11. Nginx优化服务之网页压缩
  12. 检查型异常有哪些java_JAVA系列之检查型异常与非检查型异常的详解
  13. linux安装英伟达显卡驱动
  14. 安装MikTex+WinEdt
  15. 云计算未来的发展前景和就业前景怎么样?
  16. PCM音频文件格式的头信息
  17. 2020-10-16 js实现模拟双色球摇号
  18. 验证码的生成及简单效果展示(Java篇)
  19. echarts option 平均线和副标题
  20. HG Plugins 1.0 For JQuery

热门文章

  1. linux配置文件如何排序,Linux系统中sort排序命令的使用教程
  2. 2021年电工(初级)实操考试视频及电工(初级)理论考试
  3. 微信小程序中view水平垂直居中
  4. 左图右文或者上图下文的排列
  5. 171023 逆向-BDCTF(Re)
  6. MySQL——超详细数据库触发器教程
  7. Tableau图表制作-蝴蝶图
  8. 请你谈谈IP地址和MAC地址关系,为何需要两个地址?
  9. 字符串类型的算法面试
  10. 关于语义分割预测出来的图片全黑的解决办法