package com.mlh.utils;
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.stereotype.Component;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.List;
import java.util.Map;
/**
* 文件工具类
*/
@Component
public class FileUtils {
/**
* @param imagesUrlMapList 图片列表
* imageUrl:图片全路径 imageName:图片名称
*/
public static ByteArrayOutputStream imagesToPdf(List<Map> imagesUrlMapList) {
// 创建一个document对象
Document document = new Document();
try {
// 创建一个PdfWriter实例
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
// 打开文档
document.open();
Rectangle a4Rectangle = PageSize.A4;
// 设置中文字体
String os = System.getProperty("os.name").toLowerCase();
String fontPath = "";
String fontName = "simsun";
if (os.contains("win")) {
// Windows系统字体路径
fontPath = "C:\\Windows\\Fonts\\" + fontName + ".ttc";
} else if (os.contains("mac")) {
// macOS系统字体路径
fontPath = "/Library/Fonts/" + fontName + ".ttc";
} else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
// Linux系统字体路径
fontPath = "/usr/share/fonts/" + fontName + ".ttc";
// 检查是否存在,如果不存在,尝试 ~/.fonts/
if (!new File(fontPath).exists()) {
fontPath = System.getProperty("user.home") + "/.fonts/" + fontName + ".ttc";
}
}
File fontFile = new File(fontPath);
if (fontFile.exists() && fontFile.canRead()) {
fontPath = fontFile.getAbsolutePath() + ",0";
}
BaseFont baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font font = new Font(baseFont, 20, Font.BOLD);
// 在文档中增加图片
for (Map imageUrlMap : imagesUrlMapList) {
String imageUrl = imageUrlMap.get("ImageUrl") + "";
String imageName = imageUrlMap.get("ImageName") + "";
Image img = Image.getInstance(imageUrl);
// 设置图片居中
img.setAlignment(Image.ALIGN_MIDDLE);
// 图片等比缩放
img.scaleToFit(a4Rectangle.getWidth() * 0.8F, a4Rectangle.getHeight() * 0.8F);
// 设置纸张大小
document.setPageSize(a4Rectangle);
document.newPage();
document.add(img);
// 设置中文字体并居中显示
Paragraph paragraph = new Paragraph(imageName, font);
paragraph.setAlignment(Paragraph.ALIGN_CENTER);
document.add(paragraph);
}
return baos;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to create PDF", e);
} finally {
// 关闭文档
document.close();
}
}
}