赞
踩
需要引入的Maven依赖:
- <!-- pdf替换图片 -->
- <dependency>
- <groupId>e-iceblue</groupId>
- <artifactId>spire.pdf.free</artifactId>
- <version>5.1.0</version>
- </dependency>
java代码:
- public AjaxResult replacepdf(MultipartFile file) {
- try {
- //初始化 PdfDocument 类的实例
- PdfDocument doc = new PdfDocument();
- PdfDocument doc1 = null;
- int fileType = 0;
- doc.loadFromStream(file.getInputStream());
- //加载 PDF 文档
- //region 单页模板替换
- if (doc.getPages().getCount() <= 1) {
- //获取所需的页面
- PdfPageBase page = doc.getPages().get(0);
-
- //region 获取原图大小 位置
- PdfImageInfo[] imagesInfo = page.getImagesInfo();
- //获取指定图片的坐标
- Rectangle2D bounds = imagesInfo[imagesInfo.length - 1].getBounds();
- double x = bounds.getX();
- double y = bounds.getY();
- double width = bounds.getWidth();
- double height = bounds.getHeight();
- //endregion
- //替换公章
- PdfImage image2 = PdfImage.fromFile(uploadPath + "//zryk//zrykseal//img//zrykseal.jpg");
- page.deleteImage(imagesInfo.length - 1);
- page.getCanvas().drawImage(image2, x + 40, y, 87, 87);
- PdfImage image = PdfImage.fromFile(uploadPath + "//zryk//zryklogo//img//zryk.jpg");
- page.replaceImage(0, image);
- }
- //endregion
-
- //region 文字替换
- for (Object pageFonts : doc.getPages()) {
- PdfPageBase pageF = (PdfPageBase) pageFonts;
-
- //region 需要替换的文字信息
- String oldPhone = "xxxx-25689581";
- String newPhone = "xxxx-4523 2358";
- String oldPhone1 = "25569861";
- String newPhone1 = "55586662";
-
- PdfTextFindCollection collection = pageF.findText(oldPhone, false);
- PdfTextFindCollection collection1 = pageF.findText(oldPhone1, false);
- //endregion
-
- // 指定替换文本
- String newText = newPhone;
- String newText1 = newPhone1;
-
- //region 查找并替换文本1
- for (Object findObj : collection.getFinds()) {
- PdfTextFind find = (PdfTextFind) findObj;
- // 获取文本在页面中的范围
- Rectangle2D.Float rec = (Rectangle2D.Float) find.getBounds();
- // 写入空白范围遮住原来的文本
- pageF.getCanvas().drawRectangle(PdfBrushes.getWhite(), rec);
- PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 10f);// 创建字体
- pageF.getCanvas().drawString(newText, font, PdfBrushes.getBlack(), rec.getX(), rec.getY());
- }
- //endregion
-
- //region 查找并替换文本2
- for (Object findObj : collection1.getFinds()) {
- PdfTextFind find = (PdfTextFind) findObj;
- // 获取文本在页面中的范围
- Rectangle2D.Float rec = (Rectangle2D.Float) find.getBounds();
- // 写入空白范围遮住原来的文本
- pageF.getCanvas().drawRectangle(PdfBrushes.getWhite(), rec);
- PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 10f);// 创建字体
- pageF.getCanvas().drawString(newText1, font, PdfBrushes.getBlack(), rec.getX(), rec.getY());
- }
- //endregion
-
- }
- //endregion
-
- return AjaxResult.success("上传成功");
- }catch(Exception e){
- return AjaxResult.error("上传失败,请联系管理员",JSON.toJSON(e.getStackTrace()));
-
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。