java實(shí)現(xiàn)Img與PDF相互轉(zhuǎn)換
本文實(shí)例為大家分享了java實(shí)現(xiàn)Img與PDF相互轉(zhuǎn)換的具體代碼,供大家參考,具體內(nèi)容如下
不善于表達(dá),就直接貼出代碼吧。請(qǐng)大牛忽視我。
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
* 本工具對(duì)實(shí)現(xiàn)對(duì)IMG與PDF相互轉(zhuǎn)換。
* 運(yùn)行測(cè)試需要導(dǎo)入以下2個(gè)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轉(zhuǎn)jpg
//pdfToJpg("E:\\java\\資料pdf\\1.pdf","E:\\java\\資料pdf\\1.jpg",1);
//將多個(gè)jpg直接合并成pdf包
//extractionPdf("F:\\temp\\Project\\數(shù)據(jù)\\dfdsfds\\巴黎公社活動(dòng)家傳略_img","F:\\temp\\Project\\數(shù)據(jù)\\dfdsfds\\巴黎公社活動(dòng)家傳略_img.pdf");
//jpg轉(zhuǎn)pdf
//jpgToPdf();
//文件排序
//listOrder();
ImgFileTool.imgMerageToPdf(new File("F:\\temp\\Project\\數(shù)據(jù)\\dfdsfds\\巴黎公社活動(dòng)家傳略_img").listFiles(),new File("F:\\temp\\Project\\數(shù)據(jù)\\dfdsfds\\","巴黎公社活動(dòng)家傳略.pdf"));
}
private static void listOrder() {
File[] listFiles = new File("F:\\temp\\Project\\數(shù)據(jù)\\dfdsfds\\巴黎公社活動(dòng)家傳略_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這樣的。則需要自己重寫(xiě)TreeMap的排序方式!
*/
public static boolean imgMerageToPdf(File[] list, File file)throws Exception {
//1:對(duì)圖片文件通過(guò)TreeMap以名稱進(jìn)行自然排序
Map<Integer,File> mif = new TreeMap<Integer,File>();
for(File f : list)
mif.put(Integer.parseInt(f.getName().replaceAll(".jpg$", "")), f);
//2:獲取第一個(gè)Img的寬、高做為PDF文檔標(biāo)準(zhǔn)
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:通過(guò)寬高 ,實(shí)例化PDF文檔對(duì)象。
Document document = new Document(new Rectangle(width,height));
PdfWriter pdfWr = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
//4:獲取每一個(gè)圖片文件,轉(zhuǎn)為IMG對(duì)象。裝載到Document對(duì)象中
for(Entry<Integer,File> eif : mif.entrySet())
{
//4.1:讀取到內(nèi)存中
baos = new ByteArrayOutputStream(2048*3);
is = new FileInputStream(eif.getValue());
for(int len;(len=is.read())!=-1;)
baos.write(len);
baos.flush();
//4.2通過(guò)byte字節(jié)生成IMG對(duì)象
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 目標(biāo)文件
* @param x 讀取源文件中的第幾頁(yè)
*/
private static void pdfToJpg(String source,String target,int x) throws Exception {
//創(chuàng)建從中讀取和向其中寫(xiě)入(可選)的隨機(jī)訪問(wèn)文件流,R表示對(duì)其只是訪問(wèn)模式
RandomAccessFile rea = new RandomAccessFile(new File(source), "r");
//將流讀取到內(nèi)存中,然后還映射一個(gè)PDF對(duì)象
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頁(yè)
* @throws Exception
*/
private static void pdfExtraction(String source,String target,int pageNum) throws Exception{
//1:創(chuàng)建PDF讀取對(duì)象
PdfReader pr = new PdfReader(source);
System.out.println("this document "+pr.getNumberOfPages()+" page");
//2:將第page頁(yè)轉(zhuǎn)為提取,創(chuàng)建document對(duì)象
Document doc = new Document(pr.getPageSize(pageNum));
//3:通過(guò)PdfCopy轉(zhuǎn)其單獨(dú)存儲(chǔ)
PdfCopy copy = new PdfCopy(doc, new FileOutputStream(new File(target)));
doc.open();
doc.newPage();
//4:獲取第1頁(yè),裝載到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 {
//文件轉(zhuǎn)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轉(zhuǎn)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();
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
springboot項(xiàng)目實(shí)現(xiàn)配置跨域
這篇文章主要介紹了springboot項(xiàng)目實(shí)現(xiàn)配置跨域問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-09-09
Java異常處理Guava?Throwables類(lèi)使用實(shí)例解析
這篇文章主要為大家介紹了Java異常處理神器Guava?Throwables類(lèi)使用深入詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
Java實(shí)現(xiàn)自定義語(yǔ)言和表達(dá)式解析的解釋器模式
Java解釋器設(shè)計(jì)模式通過(guò)解析自定義語(yǔ)言和表達(dá)式,實(shí)現(xiàn)對(duì)復(fù)雜邏輯的處理,提高程序可擴(kuò)展性和靈活性。它將語(yǔ)法解析和執(zhí)行過(guò)程分離,通過(guò)抽象語(yǔ)法樹(shù)和解釋器實(shí)現(xiàn)對(duì)語(yǔ)言和表達(dá)式的解析和求值,避免了硬編碼和復(fù)雜的條件判斷,提高了程序的可讀性和可維護(hù)性2023-04-04
Springboot項(xiàng)目快速實(shí)現(xiàn)過(guò)濾器功能
上篇文章已經(jīng)給大家介紹了Springboot項(xiàng)目如何快速實(shí)現(xiàn)Aop功能,這篇文章給大家介紹Springboot項(xiàng)目如何快速實(shí)現(xiàn)過(guò)濾器功能,感興趣的小伙伴可以參考閱讀2023-03-03
Mybatis傳遞多個(gè)參數(shù)進(jìn)行SQL查詢的用法
本文給大家介紹Mybatis傳遞多個(gè)參數(shù)進(jìn)行SQL查詢的用法的相關(guān)知識(shí),本文還給大家介紹了mybatis通過(guò)Map傳遞多個(gè)參數(shù)和JavaBean傳遞多個(gè)參數(shù),本文介紹的非常詳細(xì),具有參考借鑒價(jià)值,感興趣的朋友一起學(xué)習(xí)吧2016-06-06
SpringMVC REST風(fēng)格深入詳細(xì)講解
這篇文章主要介紹了SpringMVC REST風(fēng)格,Rest全稱為Representational State Transfer,翻譯為表現(xiàn)形式狀態(tài)轉(zhuǎn)換,它是一種軟件架構(gòu)2022-10-10
全網(wǎng)最全SpringBoot集成swagger的詳細(xì)教程
swagger是當(dāng)下比較流行的實(shí)時(shí)接口文文檔生成工具,swagger分為swagger2?和swagger3兩個(gè)常用版本,二者區(qū)別不是很大,主要對(duì)于依賴和注解進(jìn)行了優(yōu)化,swagger2需要引入2個(gè)jar包,swagger3只需要一個(gè),用起來(lái)沒(méi)有什么大的區(qū)別,本文給大家詳細(xì)介紹,感興趣的朋友一起看看吧2022-08-08
Idea 解決 Could not autowire. No beans of ''xxxx'' type found
這篇文章主要介紹了Idea 解決 Could not autowire. No beans of 'xxxx' type found 的錯(cuò)誤提示,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-01-01

