java实现Img与PDF相互转换

2024-08-21 09:18
文章标签 java 实现 转换 pdf img 相互

本文主要是介绍java实现Img与PDF相互转换,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

不善于表达,就直接贴出代码吧。请大牛忽视我.................
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<Integer, File> tree = new TreeMap<Integer, File>();for(File f : listFiles){tree.put(Integer.parseInt(f.getName().replaceAll(".jpg$", "")), f);}for(Entry<Integer, File> eif : tree.entrySet()){System.out.println(eif.getKey()+"="+eif.getValue().toString());}}/**	* @param list	图片集合* @param file 保存路径* @return	true,合并完成* 		如果文件名不是1.jpg,2.jpg,3.jpg,4.jpg这样的。则需要自己重写TreeMap的排序方式!*/public static boolean imgMerageToPdf(File[] list, File file)throws Exception {//1:对图片文件通过TreeMap以名称进行自然排序Map<Integer,File> mif = new TreeMap<Integer,File>();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<Integer,File> 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 rectnull, // null for the ImageObservertrue, // fill background with whitetrue // 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 {//文件转imgInputStream 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转pdfDocument 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实现Img与PDF相互转换的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1092742

相关文章

Kotlin Map映射转换问题小结

《KotlinMap映射转换问题小结》文章介绍了Kotlin集合转换的多种方法,包括map(一对一转换)、mapIndexed(带索引)、mapNotNull(过滤null)、mapKeys/map... 目录Kotlin 集合转换:map、mapIndexed、mapNotNull、mapKeys、map

SpringBoot中六种批量更新Mysql的方式效率对比分析

《SpringBoot中六种批量更新Mysql的方式效率对比分析》文章比较了MySQL大数据量批量更新的多种方法,指出REPLACEINTO和ONDUPLICATEKEY效率最高但存在数据风险,MyB... 目录效率比较测试结构数据库初始化测试数据批量修改方案第一种 for第二种 case when第三种

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

Java docx4j高效处理Word文档的实战指南

《Javadocx4j高效处理Word文档的实战指南》对于需要在Java应用程序中生成、修改或处理Word文档的开发者来说,docx4j是一个强大而专业的选择,下面我们就来看看docx4j的具体使用... 目录引言一、环境准备与基础配置1.1 Maven依赖配置1.2 初始化测试类二、增强版文档操作示例2.

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in