PDFBox模板转图片优化
较之前改动
- 去除 pdDocument.save(path); 模板赋值后没有存到本地,再重新读取—>转图片
- 字体暂做了调整华文新魏 未定 原测试结果字体影响所以赋值时用了大概6-8秒 现3秒内
@Slf4j
@Service
public class PrintBusinessServiceImpl implements PrintBusinessService {
@Value("${uploadFile.location}")
private String location;
@Value("${proofResidenceModel}")
private String proofResidenceModel;
@Value("${stsong}")
private String stsong;
@Autowired
private Sequence<Long> sequence;
@Override
public ResultModelDTO proofResidenceImg(String idCard, Integer modelType) throws Exception {
long begin = System.currentTimeMillis();
// 返回数据
ResultModelDTO resultModelDTO = new ResultModelDTO();
resultModelDTO.setModelType(modelType);
// TODO: 2020/11/5 三方接口 获取信息填入模板
if (modelType == ModelPrintlnEnums.MODEL_RESIDENCE_PERMIT.code) {
proofResidenceModel = ModelPrintlnEnums.MODEL_RESIDENCE_PERMIT.msg;
}
ResidencePermitVO residencePermitVo = getResidencePermitVO();
List<String> list = new ArrayList<>();
/**
* 根据模板生成pdf
*/
String imageName = null;
InputStream inputStream = null;
imageName = pdfToData(residencePermitVo, resultModelDTO);
if (StringUtils.isNotEmpty(imageName)) {
String[] substring = imageName.split(",");
resultModelDTO.setFileName(StringUtils.join(substring, ","));
String pName = String.format("%s%s", location, Constant.FILE_IMAGE);
for (String s : substring) {
byte[] data = null;
String imgPath = String.format("%s/%s", pName, s);
inputStream = new FileInputStream(imgPath);
data = new byte[inputStream.available()];
inputStream.read(data);
// 对字节数组进行Base64编码,得到Base64编码的字符串
BASE64Encoder encoder = new BASE64Encoder();
String base64Str = encoder.encode(data);
list.add(base64Str);
}
/**
if (StringUtils.isNotEmpty(“”)) {
这里做了一些业务操作
} else {
throw new RenException(SystemCode.INTERNAL_PROGRAM_ERROR.code, "");
}
}
if (StringUtils.isNotEmpty(“”)) {
这里做了一些业务操作
} else {
throw new RenException(SystemCode.INTERNAL_PROGRAM_ERROR.code, "");
}*/
//图片生成base64
resultModelDTO.setBases(list);
resultModelDTO.setAngle(Constant.PROOF_ANGLE);
System.out.println(System.currentTimeMillis() - begin);
return resultModelDTO;
}
private ResidencePermitVO getResidencePermitVO() {
Integer size = 1;
size = (size == null || size <= 0) ? 10 : size;
ResidencePermitVO residencePermitVo = new ResidencePermitVO();
for (int i = 0; i < size; ++i) {
String sequ = sequence.nextStr();
String[] split = sequ.split(",");
residencePermitVo.setYeaderYear(split[0]);
residencePermitVo.setHeaderNum(split[1]);
}
residencePermitVo.setTo();
return residencePermitVo;
}
/**
* pdf 根据模板生成pdf
*
* @param residencePermitVo 个人信息
* @return
* @throws Exception
*/
public String pdfToData(ResidencePermitVO residencePermitVo, ResultModelDTO resultModelDTO) throws Exception {
long begin = System.currentTimeMillis();
PDDocument pdDocument;
pdDocument = PDDocument.load(
new ClassPathResource(proofResidenceModel)
.getInputStream());
new ClassPathResource(proofResidenceModel);
Map<String, String> describe = BeanUtils.describe(residencePermitVo);
PDAcroForm acroForm = pdDocument.getDocumentCatalog().getAcroForm();
// PDAcroForm acroForm = new PDAcroForm(pdDocument);
//字体2
InputStream inputStream = new ClassPathResource("ttc/STXINWEI.TTF").getInputStream();
PDFont formFont = PDType0Font.load(pdDocument, inputStream,false);
PDResources resourcesPd = pdDocument.getPage(0).getResources();
String name = resourcesPd.add(formFont).getName();
acroForm.setDefaultResources(resourcesPd);
String defaultAppearanceString = "/" + name + " 14 Tf 0 g";
// acroForm.setDefaultAppearance(defaultAppearanceString);
for (String s : describe.keySet()) {
if (!s.equals("class")) {
PDTextField field = (PDTextField) acroForm.getField(s);
field.setDefaultAppearance(defaultAppearanceString);
field.setValue(describe.get(s));
// field.setRichTextValue(describe.get(s));
}
}
//盖章坐标
PDTextField field = (PDTextField) acroForm.getField(Constant.STAMP);
PDRectangle r = field.getWidget().getRectangle();
if (r != null) {
resultModelDTO.setLlx(Math.ceil(r.getLowerLeftX() * 0.3));
resultModelDTO.setLly(Math.ceil(r.getLowerLeftY()));
resultModelDTO.setUrx(Math.ceil(r.getUpperRightX()));
resultModelDTO.setUry(Math.ceil(r.getUpperRightY()));
}
//保存pdf
File uploadPathFile = new File(location + Constant.FILE_NAME);
if (!uploadPathFile.exists()) {
uploadPathFile.mkdirs();
}
String newFileName = System.currentTimeMillis() + "-" + (int) ((Math.random() * 9 + 1) * 100000) + Constant.SUFFIX;
System.out.println(System.currentTimeMillis() - begin);
String s = pdf2ImageDemo(pdDocument, newFileName, 180, resultModelDTO);
pdDocument.close();
return s;
}
/***
* PDF文件转PNG/JPEG图片
* @param dpi 越大转换后越清晰,相对转换速度越慢,一般电脑默认96dpi
*/
public String pdf2ImageDemo(PDDocument pdDocument,
String name, int dpi, ResultModelDTO resultModelDTO) {
List<String> list = new ArrayList<>();
StringBuffer imageName = new StringBuffer();
try {
int dot = name.lastIndexOf('.');
// 获取图片文件名
String imagePDFName = name.substring(0, dot);
String imgFolderPath = location + File.separator + Constant.FILE_IMAGE;
if (createDirectory(imgFolderPath)) {
PDFRenderer renderer = new PDFRenderer(pdDocument);
int pages = pdDocument.getNumberOfPages();// 获取PDF页数
StringBuffer imgFilePath = null;
for (int i = 0; i < pages; i++) {
String imgFilePathPrefix = imgFolderPath
+ File.separator + imagePDFName;
imgFilePath = new StringBuffer();
imgFilePath.append(imgFilePathPrefix);
imgFilePath.append("_");
imgFilePath.append(i + 1);
imgFilePath.append(".jpg");// PNG
File dstFile = new File(imgFilePath.toString());
BufferedImage image = renderer.renderImageWithDPI(i, dpi);
ImageIO.write(image, "jpg", dstFile);// PNG
pdDocument.close();
if (StringUtils.isEmpty(imageName)) {
imageName.append(dstFile.getName());
} else {
imageName.append(dstFile.getName() + ",");
}
}
log.error("PDF文档转jpg图片成功!");
return imageName.toString();
} else {
if (log.isInfoEnabled()) {
log.error("PDF文档转jpg图片失败:"
+ "创建" + imgFolderPath + "失败");
}
throw new RenException(SystemCode.INTERNAL_PROGRAM_ERROR.code, "PDF文档转jpg图片失败:"
+ "创建" + imgFolderPath + "失败");
}
} catch (Exception e) {
throw new RenException(SystemCode.INTERNAL_PROGRAM_ERROR.code, "PDF文档转jpg图片失败");
}
}
private static boolean createDirectory(String folder) {
File dir = new File(folder);
if (dir.exists()) {
return true;
} else {
return dir.mkdirs();
}
}
}