FileToImgUtils.java
25.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
package cn.com.polysoft.utils;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Slf4j
@Component
public class FileToImgUtils {
private static final Logger logger = LoggerFactory.getLogger(FileToImgUtils.class);
//File.separator
//去水印
private static boolean getLicense() {
boolean result = false;
try {
InputStream is = FileToImgUtils.class.getClassLoader().getResourceAsStream("license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* excel转pdf
*
* @param excelPath excel路径
* @param pdfPath 生成pdf路径
*/
private static void excel2pdf(String excelPath, String pdfPath) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
Workbook wb = new Workbook(excelPath);// 原始excel路径
FileOutputStream fileOS = new FileOutputStream(new File(pdfPath));
//解决excel宽度过长到pdf自动换行问题
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(true);//把内容放在一张PDF 页面上;
wb.save(fileOS, pdfSaveOptions);// 一个sheet为一个页面
//wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);//原sheet页面宽度不变,适应pdf宽度,超出长度换到下一页
fileOS.close();
LogUtils.logInfo("excel转pdf成功","fileToImg",FileToImgUtils.class,"excel2pdf");
} catch (Exception e) {
LogUtils.logError("excel转pdf失败",e,"fileToImg",FileToImgUtils.class,"excel2pdf");
e.printStackTrace();
}
}
/**
* 通过openOffice将excel转为PDF
* @param excelPath
* @param pdfPath
*/
private static void excel2pdfOpenOffice(String excelPath, String pdfPath) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
SingleOpenOffice openOffice = SingleOpenOffice.getStart();
String resultPath = openOffice.execute2Pdf(excelPath, pdfPath, null);
System.out.println(resultPath);
openOffice.getStop();
}
/**
* word转pdf
*
* @param wordPath word路径
* @param pdfPath 生成Pdf路径
*/
private static void doc2pdf(String wordPath, String pdfPath) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
File file = new File(pdfPath); //新建一个pdf文档
FileOutputStream os = new FileOutputStream(file);
Document doc = new Document(wordPath); //Address是将要被转化的word文档
doc.save(os, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
os.close();
LogUtils.logInfo("word转pdf成功","fileToImg",FileToImgUtils.class,"doc2pdf");
} catch (Exception e) {
LogUtils.logError("word转pdf失败",e,"fileToImg",FileToImgUtils.class,"doc2pdf");
e.printStackTrace();
}
}
/**
* 整个pdf转一张图片
*
* @param inputStream 文件流
* @return
*/
private static BufferedImage pdfToImage(InputStream inputStream) {
//图像合并使用参数
int width = 0; // 总宽度
int[] singleImgRGB; // 保存一张图片中的RGB数据
int shiftHeight = 0;
BufferedImage imageResult = null;//保存每张图片的像素值
try {
//利用PdfBox生成图像
PDDocument pdDocument = PDDocument.load(inputStream);
PDFTextStripper text = new PDFTextStripper();
//String text1 = text.getText(pdDocument);
PDFRenderer renderer = new PDFRenderer(pdDocument);
//循环每个页码
for (int i = 0, len = pdDocument.getNumberOfPages(); i < len; i++) {
//dpi参数越大,越清晰
BufferedImage image = renderer.renderImageWithDPI(i, 200, ImageType.RGB);
//BufferedImage srcImage = resize(image, 4000, 4000);//产生缩略图
int imageHeight = image.getHeight();
int imageWidth = image.getWidth();
if (i == 0) {//计算高度和偏移量
width = imageWidth;//使用第一张图片宽度;
//保存每页图片的像素值
imageResult = new BufferedImage(width, imageHeight * len, BufferedImage.TYPE_INT_RGB);
} else {
shiftHeight += imageHeight; // 计算偏移高度
}
singleImgRGB = image.getRGB(0, 0, width, imageHeight, null, 0, width);
imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width); // 写入流中
}
pdDocument.close();
LogUtils.logInfo("pdf转图片成功","fileToImg",FileToImgUtils.class,"pdfToImage");
} catch (Exception e) {
LogUtils.logError("pdf转图片失败",e,"fileToImg",FileToImgUtils.class,"pdfToImage");
}
return imageResult;
}
/**
* 两页pdf转为一张图片
*
* @param inputStream 文件流
* @param type 文件格式 0 pdf word 1 excel
* @return
*/
private static List<BufferedImage> pdfToImageTwo(InputStream inputStream,Integer type) {
List<BufferedImage> imageList = new ArrayList<>();
try {
Integer dpi=0;
if (type==1){
dpi=160;
}else {
dpi=160;
}
//利用PdfBox生成图像
PDDocument pdDocument = PDDocument.load(inputStream);
PDFTextStripper text = new PDFTextStripper();
//String text1 = text.getText(pdDocument);
PDFRenderer renderer = new PDFRenderer(pdDocument);
//获得页码数
Integer len = pdDocument.getNumberOfPages();
//两页pdf一张图片 一共循环次数
Integer num = len / 2 + len % 2;
//起始下标
Integer index = 0;
//结束下标
Integer end = 2;
if(len==2){
end=2;
}
else if (end > num) {
end = num;
}
//根据页码循环
for (int j = 0; j < num; j++) {
BufferedImage imageResult = null;//保存每张图片的像素值
Integer c = 0;
//图像合并使用参数
int width = 0; // 总宽度
int[] singleImgRGB; // 保存一张图片中的RGB数据
int shiftHeight = 0;
//判断高度为两倍 还是一倍
Integer d = 0;
if (end % 2 != 1) {
d = 2;
} else {
d = 1;
}
//两页pdf转为一张图片
for (int i = index; i < end; i++) {
//dpi参数越大,越清晰
BufferedImage image = renderer.renderImageWithDPI(i, dpi, ImageType.RGB);
//image = resize(image, 3900, imageHeight);//产生缩略图
//图片宽度
int imageWidth = image.getWidth();
//图片高度
int imageHeight = image.getHeight();
//使用第一张图片宽度;
if (c == 0) {//计算高度和偏移量
width = imageWidth;
//保存每页图片的像素值
imageResult = new BufferedImage(width, imageHeight * d, BufferedImage.TYPE_INT_RGB);
if (width > 3900 || imageHeight * d > 3900) {
LogUtils.logInfo("图片像素超出3900,宽:" + width + " 高:" + imageHeight * d,"fileToImg",FileToImgUtils.class,"pdfToImageTwo");
return null;
}
} else {
shiftHeight += imageHeight; // 计算偏移高度
}
singleImgRGB = image.getRGB(0, 0, width, imageHeight, null, 0, width);
imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width); // 写入流中
index++;
c++;
}
//生成图片放入集合
imageList.add(imageResult);
//起始下标,结束下标动态增加
if (end + 2 <= len) {
end = end + 2;
} else {
end = len;
}
}
pdDocument.close();
LogUtils.logInfo("pdf转图片成功","fileToImg",FileToImgUtils.class,"pdfToImageTwo");
} catch (Exception e) {
LogUtils.logError("pdf转图片失败",e,"fileToImg",FileToImgUtils.class,"pdfToImageTwo");
}
return imageList;
}
/**
* 一页pdf转为一张图片
*
* @param inputStream 文件流
* @return
*/
private static List<BufferedImage> pdfToImageOne(InputStream inputStream) {
List<BufferedImage> imageList = new ArrayList<>();
try {
//利用PdfBox生成图像
PDDocument pdDocument = PDDocument.load(inputStream);
PDFTextStripper text = new PDFTextStripper();
//String text1 = text.getText(pdDocument);
PDFRenderer renderer = new PDFRenderer(pdDocument);
//获得页码数
Integer len = pdDocument.getNumberOfPages();
//一页pdf转为一张图片
for (int i = 0; i < len; i++) {
BufferedImage imageResult = null;//保存每张图片的像素值
Integer c = 0;
//图像合并使用参数
int width = 0; // 总宽度
int[] singleImgRGB; // 保存一张图片中的RGB数据
int shiftHeight = 0;
//dpi参数越大,越清晰
BufferedImage image = renderer.renderImageWithDPI(i, 240, ImageType.RGB);
//图片宽度
int imageWidth = image.getWidth();
//图片高度
int imageHeight = image.getHeight();
//使用第一张图片宽度;
width = imageWidth;
//保存每页图片的像素值
imageResult = new BufferedImage(width, imageHeight, BufferedImage.TYPE_INT_RGB);
if (width > 3900 || imageHeight> 3900) {
LogUtils.logInfo("图片像素超出3900,宽:" + width + " 高:" + imageHeight,"fileToImg",FileToImgUtils.class,"pdfToImageOne");
return null;
}
singleImgRGB = image.getRGB(0, 0, width, imageHeight, null, 0, width);
imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width); // 写入流中
//生成图片放入集合
imageList.add(imageResult);
}
pdDocument.close();
LogUtils.logInfo("pdf转图片成功","fileToImg",FileToImgUtils.class,"pdfToImageOne");
} catch (Exception e) {
LogUtils.logError("pdf转图片失败",e,"fileToImg",FileToImgUtils.class,"pdfToImageOne");
}
return imageList;
}
/**
* 若干图片转为pdf
*
* @param outPdfFilepath 生成pdf文件路径
* @param imageFiles 需要转换的图片File类Array,按array的顺序合成图片
*/
public static void imagesToPdf(String outPdfFilepath, File[] imageFiles) throws Exception {
try {
File file = new File(outPdfFilepath);
// 第一步:创建一个document对象。
com.itextpdf.text.Document document = new com.itextpdf.text.Document();
document.setMargins(0, 0, 0, 0);
// 第二步:
// 创建一个PdfWriter实例,
PdfWriter.getInstance(document, new FileOutputStream(file));
// 第三步:打开文档。
document.open();
// 第四步:在文档中增加图片。
int len = imageFiles.length;
Float width = 0f;
Float heigh = 0f;
for (int i = 0; i < len; i++) {
if (imageFiles[i].getName().toLowerCase().endsWith(".bmp")
|| imageFiles[i].getName().toLowerCase().endsWith(".jpg")
|| imageFiles[i].getName().toLowerCase().endsWith(".jpeg")
|| imageFiles[i].getName().toLowerCase().endsWith(".gif")
|| imageFiles[i].getName().toLowerCase().endsWith(".png")) {
String temp = imageFiles[i].getAbsolutePath();
com.itextpdf.text.Image img = com.itextpdf.text.Image.getInstance(temp);
img.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER);
if (i == 0) {
width = img.getWidth();
}
heigh = img.getHeight();
img.scaleAbsolute(width, heigh);// 直接设定显示尺寸
// 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
//document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
document.setPageSize(new Rectangle(width, heigh));
document.newPage();
document.add(img);
}
}
// 第五步:关闭文档。
document.close();
LogUtils.logInfo("图片转pdf成功","fileToImg",FileToImgUtils.class,"imagesToPdf");
} catch (DocumentException e) {
LogUtils.logError("图片转pdf失败",e,"fileToImg",FileToImgUtils.class,"imagesToPdf");
} catch (IOException e) {
LogUtils.logError("图片转pdf失败",e,"fileToImg",FileToImgUtils.class,"imagesToPdf");
}
}
/**
* 一页pdf转一张图片
*
* @param PdfFilePath pdf文件位子
* @param dstImgFolder 生成图片存放位子(不是最终位置)
*/
public static File[] pdf2Image(String PdfFilePath, String dstImgFolder) {
File file = new File(PdfFilePath);
PDDocument pdDocument;
List<File> list = new ArrayList<>();
File[] files = null;
try {
String imgPDFPath = file.getParent();
int dot = file.getName().lastIndexOf('.');
String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
String imgFolderPath = null;
if (dstImgFolder.equals("")) {
imgFolderPath = imgPDFPath + "/" + imagePDFName;// 获取图片存放的文件夹路径
} else {
imgFolderPath = dstImgFolder + "/" + imagePDFName;
}
if (createDirectory(imgFolderPath)) {
pdDocument = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(pdDocument);
/* dpi越大转换后越清晰,相对转换速度越慢 */
PdfReader reader = new PdfReader(PdfFilePath);
int pages = reader.getNumberOfPages();
StringBuffer imgFilePath = null;
for (int i = 0; i < pages; i++) {
//每个图片最终存放位子
String imgFilePathPrefix = imgFolderPath + "/" + imagePDFName;
imgFilePath = new StringBuffer();
imgFilePath.append(imgFilePathPrefix);
imgFilePath.append("_");
imgFilePath.append(String.valueOf(i + 1));
imgFilePath.append(".png");
File dstFile = new File(imgFilePath.toString());
BufferedImage image = renderer.renderImageWithDPI(i, 200);
ImageIO.write(image, "png", dstFile);
list.add(dstFile);
}
LogUtils.logInfo("pdf转图片成功","fileToImg",FileToImgUtils.class,"pdf2Image");
reader.close();
} else {
LogUtils.logInfo("PDF文档转PNG图片失败:" + "创建" + imgFolderPath + "失败","fileToImg",FileToImgUtils.class,"pdf2Image");
}
files = new File[list.size()];
list.toArray(files);
} catch (IOException e) {
LogUtils.logError("pdf转图片失败",e,"fileToImg",FileToImgUtils.class,"pdf2Image");
e.printStackTrace();
}
return files;
}
/**
* 判断文件夹是否存在
*
* @param folder 文件夹路径
* @return
*/
private static boolean createDirectory(String folder) {
File dir = new File(folder);
if (dir.exists()) {
return true;
} else {
return dir.mkdirs();
}
}
/**
* 删除某个文件夹下的所有文件夹和文件
*
* @param delpath String
* @return boolean
* @throws FileNotFoundException
* @throws IOException
*/
public static boolean deletefile(String delpath) throws Exception {
try {
File file = new File(delpath);
// 当且仅当此抽象路径名表示的文件存在且 是一个目录时,返回 true
if (!file.isDirectory()) {
file.delete();
} else if (file.isDirectory()) {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File delfile = new File(delpath + "/" + filelist[i]);
if (!delfile.isDirectory()) {
delfile.delete();
LogUtils.logInfo(delfile.getAbsolutePath() + "删除文件成功","fileToImg",FileToImgUtils.class,"deletefile");
} else if (delfile.isDirectory()) {
deletefile(delpath + "/" + filelist[i]);
}
}
LogUtils.logInfo(file.getAbsolutePath() + "删除成功","fileToImg",FileToImgUtils.class,"deletefile");
file.delete();
}
} catch (FileNotFoundException e) {
LogUtils.logError("删除文件或文件夹失败",e,"fileToImg",FileToImgUtils.class,"deletefile");
}
return true;
}
/**
* 总调用方法
*
* @param filePath 文件原始路径
*/
public static List<String> getImgPath(String filePath,String ocrImgPath) {
//临时pdf路径 最后删除
String pdfPath = filePath.substring(0, filePath.lastIndexOf(".")) + ".pdf";
//判断依据
Integer isPdf=0;
Integer isExcel=0;
//图片文件夹路径,非最终
String imgPath = filePath.substring(0, filePath.lastIndexOf(".")) + ".jpg";
//图片路径集合
List<String> list = new ArrayList<>();
try {
String lastFilePath = "";
InputStream inputStream = null;
BufferedImage bufferedImage = null;
File file = new File(filePath);
//判断依据
//Integer a = 0;
//判断路径是否为空
if (!StringUtils.isNotBlank(filePath) || !StringUtils.isNotBlank(pdfPath) || !StringUtils.isNotBlank(imgPath)) {
LogUtils.logInfo("传入路径存在空","fileToImg",FileToImgUtils.class,"getImgPath");
return null;
}
//判断文件大小 10M
if (file.length() > 10485760) {
LogUtils.logInfo("传入文件大于10M","fileToImg",FileToImgUtils.class,"getImgPath");
return null;
}
//判断文件格式进行文件类型转换
if (filePath.toLowerCase().endsWith("docx") || filePath.toLowerCase().endsWith("doc")) {
doc2pdf(filePath, pdfPath);
lastFilePath = pdfPath;
isPdf=1;
//isExcel=1;
} else if (filePath.toLowerCase().endsWith("xlsx") || filePath.toLowerCase().endsWith("xls")) {
//excel2pdf(filePath, pdfPath);
excel2pdfOpenOffice(filePath, pdfPath);
lastFilePath = pdfPath;
isPdf=1;
isExcel=1;
//a = 1;
} else if (filePath.toLowerCase().endsWith("pdf")) {
lastFilePath = filePath;
} else {
LogUtils.logInfo("传入文件非指定类型","fileToImg",FileToImgUtils.class,"getImgPath");
return null;
}
/* if (a == 1) {
//一页pdf转一张图片
File[] files = pdf2Image(lastFilePath, imgPath);
//合成宽度相同的pdf
File f=new File(lastFilePath);
f.delete();
imagesToPdf(lastFilePath, files);
deletefile(imgPath);
}*/
InputStream is = new FileInputStream(lastFilePath);
//pdf转一整张图片
//bufferedImage = pdfToImage(is);
List<BufferedImage> bufferedImages = pdfToImageTwo(is,isExcel);
//List<BufferedImage> bufferedImages = pdfToImageOne(is);
//判断是否生成图片
if (bufferedImages != null && bufferedImages.size() > 0) {
File files = new File(imgPath);
String name = files.getName();
//拼接年月日小时存放路径
String lastImgPath = ocrImgPath + "/" + TimeUtils.getYearMonthDay(new Date()) + "/" + TimeUtils.getHour(new Date()) + "/" +UuidUtil.getUUID();
//判断文件夹是否存在
File imgFile = new File(lastImgPath);
if (!imgFile.exists()) {
imgFile.mkdirs();
}
//循环生成图片
for (int i = 0; i < bufferedImages.size(); i++) {
//每张图片存放路径
String path = lastImgPath + "/" + i + ".jpg";
//输出图片相关操作
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedImages.get(i), "jpg", os);
inputStream = new ByteArrayInputStream(os.toByteArray());
OutputStream outputStream = new FileOutputStream(path);
byte[] b = new byte[1024];
while ((inputStream.read(b)) != -1) {
outputStream.write(b);
}
is.close();
outputStream.close();
File imgsize = new File(path);
if (imgsize.length() >= 4194304) {
LogUtils.logInfo("生成图片大于4M","fileToImg",FileToImgUtils.class,"getImgPath");
deletefile(lastImgPath);
return null;
}
list.add(path);
}
if(isPdf==1){
//删除临时生成的pdf
// File deletePdfPath=new File(pdfPath);
// deletePdfPath.delete();
LogUtils.logInfo("删除临时生成的pdf","fileToImg",FileToImgUtils.class,"getImgPath");
}
} else {
return null;
}
} catch (Exception e) {
LogUtils.logError("文件转图片出现异常",e,"fileToImg",FileToImgUtils.class,"getImgPath");
e.printStackTrace();
}
LogUtils.logInfo("文件转图片成功,图片路径集合:"+list.toString(),"fileToImg",FileToImgUtils.class,"getImgPath");
return list;
}
public static void main(String[] args) {
//文件路径
String filePath = "E:\\合约账单样本1-IPM20170110-佳达经纪 BA10005.docx";
List<String> imgPath = getImgPath(filePath,"E:\\img");
if (imgPath == null || imgPath.size() == 0) {
System.out.println("异常");
} else {
for (String s : imgPath) {
System.out.println(s);
}
}
}
}