itextpdf 给pdf文档添加图片
主要流程1、构建图片对象2、放置图片3、pdf拼接主要流程
1、构建图片对象
/*** signDetail 前端canvas 获取的图片信息*/ private static Image buildImageFromSource(String signDetail, float width, float height) {try {signDetail = clearPreffix(signDetail);Image image = Image.getInstance(Base64Utils.decodeFromString(signDetail));image.setAlignment(Image.LEFT);image.setBorder(Image.NO_BORDER);// 将px转成pt 需要 * 0.75,计算完成后,减去上下左右的36pt的边距image.scaleAbsolute((width * 0.75f) -72, (height * 0.75f) -72);return image;} catch (BadElementException | IOException e) {e.printStackTrace();log.error("创建image失败: {}", e.getMessage());}return null;}// 移除保存图片时不需要的前缀private static String clearPreffix(String detail) {if (detail.startsWith("data")) {// 获取点的位置int pointIdx = detail.indexOf(",");detail = detail.substring(pointIdx + 1);}return detail;}
2、放置图片
/*** 新建一个pdf,并追加图片* @param dest输出文件* @param signDetails 图片详细*/public static void newPdf(String dest, List<String> signDetails) {File file = new File(dest);if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {}FileOutputStream fos = null;try {fos = new FileOutputStream(dest);Document document = new Document(PageSize.A4);PdfWriter writer = PdfWriter.getInstance(document, fos);document.open();// 加载模板文件ClassPathResource resource = new ClassPathResource("tpl/signTpl.pdf");PdfReader reader = new PdfReader(resource.getInputStream());PdfImportedPage page = writer.getImportedPage(reader, 1);PdfContentByte cb = writer.getDirectContent();document.newPage();cb.addTemplate(page, 0, 0);float top = document.top();// 默认顶部拿掉,然后再扣掉页眉的高度float y = top - 66 - 20;float x = 36;int signHeight = 75;int rowCount = 3;for (int i = 0; i < signDetails.size(); i++) {String detail = signDetails.get(i);x = 90 + (i % rowCount) * 150;Image image = buildImageFromSource(detail, 214, 148);if (i % rowCount == 0) {y -= signHeight;if (y <= signHeight) {document.newPage();cb.addTemplate(page, 0, 0);y = top - 66 - 90;}}if (image != null) {image.setAbsolutePosition(x, y);document.add(image);}}document.close();} catch (IOException | DocumentException e) {e.printStackTrace();} finally {IoUtil.close(fos);}}
3、pdf拼接
public static void appendImgToPdf(String sourcePath, String targetPath, List<String> details) throws IOException {String tempPath = new File("/tmp/test").getAbsolutePath() + "/" + UUID.fastUUID().toString() + ".png";newPdf(tempPath, details);mergePdf(Lists.newArrayList(sourcePath, tempPath), targetPath);}public static void mergePdf(List<String> sourceFilePaths, String targtPath) throws IOException {PDFMergerUtility mergePdf = new PDFMergerUtility();for (String filePath : sourceFilePaths) {File file = new File(filePath);if (file.exists() && file.isFile()) {mergePdf.addSource(file);}}File file = new File(targtPath);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}mergePdf.setDestinationFileName(targtPath);mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());}