Browse Source

1、图片与pdf互转实现

master
Aug 2 weeks ago
parent
commit
e44105da32
2 changed files with 375 additions and 0 deletions
  1. +58
    -0
      jeecg-boot-module-system/pom.xml
  2. +317
    -0
      jeecg-boot-module-system/src/main/java/org/jeecg/modules/test/imageDemo.java

+ 58
- 0
jeecg-boot-module-system/pom.xml View File

@ -74,6 +74,64 @@
<scope>compile</scope>
</dependency>
<!--语音合成-->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-speech-sdk-java</artifactId>
<version>LATEST</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.tencentcloudapi/tencentcloud-sdk-java -->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>4.0.11</version>
</dependency>
<!--excel导入导出-->
<!-- 文件上传 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.7</version>
</dependency>
<!-- JSON -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
<!-- POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<!--pdf添加水印、文字、图片、印章-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!--pdf转图片-->
<dependency>
<groupId>org.icepdf.os</groupId>
<artifactId>icepdf-core</artifactId>
<version>6.1.2</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
</dependencies>
<build>


+ 317
- 0
jeecg-boot-module-system/src/main/java/org/jeecg/modules/test/imageDemo.java View File

@ -0,0 +1,317 @@
package org.jeecg.modules.test;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import org.icepdf.core.pobjects.Page;
import sun.misc.BASE64Encoder;
import org.icepdf.core.util.GraphicsRenderingHints;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
public class imageDemo {
public static void main(String[] args) {
//pdf转图片base64
List<String> codeList = pdf2imagebase64();
for (String s : codeList) {
System.out.println(s);
}
// //图片转pdf
// image2pdf();
// System.out.println("start");
// String imageBase64 = "base64";
// String imagePath = "F:\\temp\\firsttest.png";
// base64ToImage(imageBase64, imagePath);
}
//pdf转图片base64(一张pdf转成多个base64图片)
public static List pdf2imagebase64(){
//获取当前时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date now = new Date();
String formattedDate = sdf.format(now);
String pdfPath = "F:\\temp\\test.pdf";//pdf文件路径
String imagePath = "F:\\temp\\";//图片文件路径
String fileName = formattedDate + "image_";//图片文件名字
//文件流对象
InputStream in = null;
List<String> pathList = new ArrayList<>();//图片路径列表
List<String> codeList = new ArrayList<>();//base64列表
Map<String, Object> map = new HashMap<>();
try{
org.icepdf.core.pobjects.Document document = new org.icepdf.core.pobjects.Document();
document.setFile(pdfPath);
float scale = 2.5f;//缩放比例
float rotation = 0f;//旋转角度
//pdf转图片
for (int i = 0; i < document.getNumberOfPages(); i++) {
BufferedImage image = (BufferedImage)
document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
RenderedImage rendImage = image;
File fileDir = new File(imagePath);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
String imgName = fileName + i + ".png";//图片名称
String filePath = imagePath + imgName;//图片文件路径
File file = new File(filePath);
ImageIO.write(rendImage, "png", file);
image.flush();
pathList.add(filePath);
}
document.dispose();//关闭流
//图片转base64
for (String path : pathList) {
String imgFile = path;// 待处理的图片
byte[] data = null;
String encode = null; // 返回Base64编码过的字节数组字符串
BASE64Encoder encoder = new BASE64Encoder();// 对字节数组Base64编码
// 读取图片字节数组
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
encode = encoder.encode(data);
codeList.add(encode);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(null != in){
in.close();//关闭文件流
}
}catch (Exception e){
e.printStackTrace();
}
}
return codeList;
}
//图片转pdf
public static String image2pdf(){
//获取当前时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date now = new Date();
String formattedDate = sdf.format(now);
System.out.println(formattedDate);
String images = "F:\\temp\\image_0.png;F:\\temp\\image_1.png;F:\\temp\\image_2.png";//图片文件地址
String pdfPath = "F:\\temp\\"+formattedDate+".pdf"; // 输出pdf文件路径
String[] imageList = images.split(";");
try{
ArrayList<String> imageUrllist = new ArrayList<String>(); //图片list集合
for (int i=0; i<imageList.length; i++) {
imageUrllist.add(imageList[i]);
}
File file = Pdf(imageUrllist, pdfPath);//生成pdf
file.createNewFile();
}catch (Exception e){
e.printStackTrace();
}
return pdfPath;
}
public static File Pdf(ArrayList<String> imageUrllist, String mOutputPdfFileName) {
Document doc = new Document(PageSize.A4, 0, 0, 0, 0); //new一个pdf文档
try {
PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName)); //pdf写入
doc.open();//打开文档
for (int i = 0; i < imageUrllist.size(); i++) { //循环图片List将图片加入到pdf中
doc.newPage(); //在pdf创建一页
Image png1 = Image.getInstance(imageUrllist.get(i)); //通过文件路径获取image
float heigth = png1.getHeight();
float width = png1.getWidth();
int percent = getPercent2(heigth, width);
png1.setAlignment(Image.MIDDLE);
png1.scalePercent(percent + 3);// 表示是原来图像的比例;
doc.add(png1);
}
doc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
File mOutputPdfFile = new File(mOutputPdfFileName); //输出流
if (!mOutputPdfFile.exists()) {
mOutputPdfFile.deleteOnExit();
return null;
}
return mOutputPdfFile; //反回文件输出流
}
public static int getPercent2(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}
/******************************************************************************************************************/
//图片转base64
public static String imageToBase64(String imgPath){
String imgFile = imgPath;// 待处理的图片
InputStream in = null;
byte[] data = null;
String encode = null; // 返回Base64编码过的字节数组字符串
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
try {
// 读取图片字节数组
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
encode = encoder.encode(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return encode;
}
//base64转图片
public static boolean base64ToImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) // 图像数据为空
return false;
// 解密
try {
// 解密
//Base64.Decoder decoder = Base64.getDecoder();
Base64.Decoder decoder = Base64.getMimeDecoder();
// 去掉base64前缀 data:image/png;base64,
imgStr = imgStr.substring(imgStr.indexOf(",", 1) + 1, imgStr.length());
byte[] b = decoder.decode(imgStr);
// 处理数据
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
// 保存图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
// 返回图片的相对路径 = 图片分类路径+图片名+图片后缀
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
//图片转pdf
public static void imgChangePDF(String imageUrl, String target) {
//创建一个文档对象
Document doc = new Document();
try {
//定义输出文件的位置
PdfWriter.getInstance(doc, new FileOutputStream(target));
//开启文档
doc.open();
//路径
Image img = Image.getInstance(imageUrl);
//获得宽高
Float h = img.getHeight();
Float w = img.getWidth();
//统一压缩
Integer percent = getPercent(h, w);
//图片居中
img.setAlignment(Image.MIDDLE);
//百分比显示图
img.scalePercent(percent);
//设置高和宽的比例
doc.add(img);
// 关闭文档
if(doc != null){
doc.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (BadElementException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
//压缩
public static Integer getPercent(Float h,Float w)
{
Integer g=0;
Float g2=0.0f;
g2=480/w*100;
g=Math.round(g2);
return g;
}
/******************************************************************************************************************/
public static void pdf2Pic(String pdfPath, String path, String fileName) throws Exception {
org.icepdf.core.pobjects.Document document = new org.icepdf.core.pobjects.Document();
document.setFile(pdfPath);
//缩放比例
float scale = 2.5f;
//旋转角度
float rotation = 0f;
for (int i = 0; i < document.getNumberOfPages(); i++) {
BufferedImage image = (BufferedImage)
document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
RenderedImage rendImage = image;
try {
File fileDir = new File(path);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
String imgName = fileName + i + ".png";
File file = new File(path + imgName);
ImageIO.write(rendImage, "png", file);
} catch (IOException e) {
e.printStackTrace();
}
image.flush();
}
document.dispose();
}
}

Loading…
Cancel
Save