image2PDF

图片 转 pdf

使用poiitext库实现。

maven 依赖

itext 依赖了 poi 不用手动添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<dependencies>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>io</artifactId>
<version>7.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>7.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>layout</artifactId>
<version>7.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.9</version>
</dependency>
</dependencies>

工具实现

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
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.waysoft.modules.tools.FileUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;


public class ImageToPdf implements Converter{

private static ImageToPdf imageToPdf = null;

private ImageToPdf(){}

public static ImageToPdf create(){
if(imageToPdf == null){
imageToPdf = new ImageToPdf();
}
return imageToPdf;
}

@Override
public byte[] convertToPdf(File imageFile) throws Exception {
// FileUtil.readFileToByteArray(imageFile) 把 file 转为 btye[]
return convertToPdf(FileUtil.readFileToByteArray(imageFile));
}

@Override
public byte[] convertToPdf(byte[] file) throws Exception {
ByteArrayOutputStream outputStream = null;
try {
outputStream = new ByteArrayOutputStream();

// 创建一个新的PDF文档
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outputStream));

// 创建一个文档对象
Document document = new Document(pdfDoc);

Image pdfImage = new Image(ImageDataFactory.create(file));
document.add(pdfImage) ;

document.close();
return outputStream.toByteArray();
}finally {
outputStream.close();
}
}

}