<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
public static InputStream Pdf(ArrayList<String> imageUrllist) throws IOException {
//imageUrllist为 图片url访问路径 (本地路径or网络访问路径 带上http/https)
Document doc = new Document(PageSize.A4, 20, 20, 20, 20); //new一个pdf文档
//创建一个空字节输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = null;
try {
PdfWriter.getInstance(doc, out); //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();
//转换成输入流
in = new ByteArrayInputStream(out.toByteArray());
} catch (IOException | DocumentException e) {
e.printStackTrace();
} finally {
try {
if (out!=null){
out.close();
}
}catch (IOException e){
e.printStackTrace();
}
try {
if (doc!=null) {
doc.close();
}
}catch (RuntimeException e){
e.printStackTrace();
}
try {
if (in != null) {
in.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
return in; //反回文件输入流
}
//String srais = MinioUtil.uploadInputStream("srais", freshName, in);
//上传mini的代码不另外复制了,自行百度
public static int getPercent(float h, float w) {
int p = 0;
float p2 = 0.0f;
if (h > w) {
p2 = 297 / h * 100;
} else {
p2 = 210 / w * 100;
}
p = Math.round(p2);
return p;
}
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;
}