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

相关文章

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

java中long的一些常见用法

《java中long的一些常见用法》在Java中,long是一种基本数据类型,用于表示长整型数值,接下来通过本文给大家介绍java中long的一些常见用法,感兴趣的朋友一起看看吧... 在Java中,long是一种基本数据类型,用于表示长整型数值。它的取值范围比int更大,从-922337203685477

Nexus安装和启动的实现教程

《Nexus安装和启动的实现教程》:本文主要介绍Nexus安装和启动的实现教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、Nexus下载二、Nexus安装和启动三、关闭Nexus总结一、Nexus下载官方下载链接:DownloadWindows系统根

java Long 与long之间的转换流程

《javaLong与long之间的转换流程》Long类提供了一些方法,用于在long和其他数据类型(如String)之间进行转换,本文将详细介绍如何在Java中实现Long和long之间的转换,感... 目录概述流程步骤1:将long转换为Long对象步骤2:将Longhttp://www.cppcns.c