From b5ca1e7364ed7796e674c9a73ebaa7dae1268cc8 Mon Sep 17 00:00:00 2001 From: ma <1062634917@qq.com> Date: Mon, 9 Aug 2021 14:51:40 +0800 Subject: [PATCH] =?UTF-8?q?PDf=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/ccsens/tall/web/DebugController.java | 137 ++++++++++++++++++ .../main/java/com/ccsens/util/PdfUtil.java | 48 ++---- .../test/java/com/ccsens/util/PDFTest.java | 101 +++++++++++++ 3 files changed, 251 insertions(+), 35 deletions(-) create mode 100644 util/src/test/java/com/ccsens/util/PDFTest.java diff --git a/tall/src/main/java/com/ccsens/tall/web/DebugController.java b/tall/src/main/java/com/ccsens/tall/web/DebugController.java index 6b22c904..c0637bd9 100644 --- a/tall/src/main/java/com/ccsens/tall/web/DebugController.java +++ b/tall/src/main/java/com/ccsens/tall/web/DebugController.java @@ -12,12 +12,15 @@ import com.ccsens.util.bean.message.common.InMessage; import com.ccsens.util.bean.message.common.MessageConstant; import com.ccsens.util.bean.message.common.MessageRule; import com.ccsens.util.config.RabbitMQConfig; +import com.itextpdf.text.*; +import com.itextpdf.text.pdf.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; +import org.junit.Test; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.PlatformTransactionManager; @@ -31,7 +34,11 @@ import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.io.ByteArrayOutputStream; +import java.io.FileOutputStream; +import java.io.IOException; import java.util.*; +import java.util.List; @Slf4j @Api(tags = "DEBUG" , description = "DebugController | ") @@ -162,4 +169,134 @@ public class DebugController { return a; } + + + @ApiOperation(value = "PDF") + @ApiImplicitParams({ + }) + @RequestMapping(value = "/pdf", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"}) + public void pdf() throws Exception { + String id = "142602199908292517"; + //文字 + Map map = new HashMap(); + map.put("name","张三"); + map.put("nation","汉"); + char[] idChar = id.toCharArray(); + for (int i = 0; i < idChar.length; i++) { + map.put("id"+(i+1),idChar[i]+""); + } + + //单选 + Map map3 = new HashMap(); + map3.put("gender","0"); +// map3.put("Group7","1"); + //多选 + Map duoxuan = new HashMap(); + duoxuan.put("JMRS-RSYY","0"); + +// duoxuan.put("CheckBox5","0"); +// duoxuan.put("CheckBox6","1"); + //图片 + Map map2 = new HashMap(); +// map2.put("img","c:/50336.jpg"); + + Map o=new HashMap(); + o.put("datemap",map); + o.put("imgmap",map2); + o.put("danxuan",map3); + o.put("duoxuan",duoxuan); + pdfout(o); + + } + + // 利用模板生成pdf + public static void pdfout(Map o) { + // 模板路径 + String templatePath = "C:/Users/10626/Desktop/pdf表单1.pdf"; + // 生成的新文件路径 + String newPDFPath = "C:/Users/10626/Desktop/测试导出pdf.pdf"; + + PdfReader reader; + FileOutputStream out; + ByteArrayOutputStream bos; + + PdfStamper stamper; + try { + BaseFont bf = BaseFont.createFont("c://windows//fonts//simsun.ttc,1" , BaseFont.IDENTITY_H, BaseFont.EMBEDDED); + Font FontChinese = new Font(bf, 5, Font.NORMAL); + out = new FileOutputStream(newPDFPath);// 输出流 + reader = new PdfReader(templatePath);// 读取pdf模板 + bos = new ByteArrayOutputStream(); + stamper = new PdfStamper(reader, bos); + AcroFields form = stamper.getAcroFields(); + + //文字类的内容处理 + Map datemap = (Map)o.get("datemap"); + form.addSubstitutionFont(bf); + for(String key : datemap.keySet()){ + String value = datemap.get(key); + form.setField(key,value); + } + //单选 + Map danxuan = (Map)o.get("danxuan"); + form.addSubstitutionFont(bf); + for (String key : danxuan.keySet()) { + + form.setField(key,"0",true); + + } + //多选 + Map duoxuan = (Map)o.get("duoxuan"); + form.addSubstitutionFont(bf); + for (String key : duoxuan.keySet()) { + form.setField(key,"0"); + form.setField(key,"1"); + form.setField(key,"2"); + + + } + form.setField("WRSYY","3",true); + + //图片类的内容处理 + Map imgmap = (Map)o.get("imgmap"); + for(String key : imgmap.keySet()) { + String value = imgmap.get(key); + String imgpath = value; + int pageNo = form.getFieldPositions(key).get(0).page; + Rectangle signRect = form.getFieldPositions(key).get(0).position; + float x = signRect.getLeft(); + float y = signRect.getBottom(); + //根据路径读取图片 + Image image = Image.getInstance(imgpath); + //获取图片页面 + PdfContentByte under = stamper.getOverContent(pageNo); + //图片大小自适应 + image.scaleToFit(signRect.getWidth(), signRect.getHeight()); + //添加图片 + image.setAbsolutePosition(x, y); + under.addImage(image); + } + stamper.setFormFlattening(true);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑 + stamper.close(); + Document doc = new Document(); + Font font = new Font(bf, 32); + PdfCopy copy = new PdfCopy(doc, out); + doc.open(); + //这行只会打印指定页 +// PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1); + PdfImportedPage importPage = null; + for (int i = 1; i <= reader.getNumberOfPages(); i++) { + importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()),i); + copy.addPage(importPage); + } + + doc.close(); + + } catch (IOException e) { + System.out.println(e); + } catch (DocumentException e) { + System.out.println(e); + } + + } } diff --git a/util/src/main/java/com/ccsens/util/PdfUtil.java b/util/src/main/java/com/ccsens/util/PdfUtil.java index 2034380d..0116bb91 100644 --- a/util/src/main/java/com/ccsens/util/PdfUtil.java +++ b/util/src/main/java/com/ccsens/util/PdfUtil.java @@ -28,14 +28,14 @@ public class PdfUtil { /** * 生成pdf - * @param parentPath 文件夹路径 - * @param title 标题 + * @param parentPath + * @param title * @param subhead 副标题 - * @param intros 介绍 - * @param contentArr 正文 + * @param intros + * @param content * @return */ - public static String createPdf(String parentPath, String title, String subhead, Margin margin, List intros, List... contentArr) { + public static String credatePdf(String parentPath, String title, String subhead, List intros, List content, Margin margin) { String fileName = "pdf/" + DateUtil.today() + "/" + System.currentTimeMillis() + ".pdf"; log.info("pdf文件名:{}", fileName ); File file = new File(parentPath, fileName); @@ -51,7 +51,7 @@ public class PdfUtil { // 中文字体 BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); // 标题字体 - Font titleChinese = new Font(bfChinese, 14, Font.NORMAL); + Font titleChinese = new Font(bfChinese, 24, Font.BOLD); //设置标题 Paragraph par = new Paragraph(title, titleChinese); par.setAlignment(Element.ALIGN_CENTER); @@ -59,27 +59,22 @@ public class PdfUtil { if (StrUtil.isNotBlank(subhead)) { // 标题字体 - Font subheadChinese = new Font(bfChinese, 15, Font.NORMAL); + Font subheadChinese = new Font(bfChinese, 22, Font.NORMAL); //设置标题 Paragraph subheadPar = new Paragraph(subhead, subheadChinese); subheadPar.setAlignment(Element.ALIGN_CENTER); document.add(subheadPar); } // 每行加空白 - fillBlankRow(document, new Font(bfChinese, 3, Font.NORMAL)); + fillBlankRow(document, titleChinese); //设置介绍内容 if (CollectionUtil.isNotEmpty(intros)) { fillRow(intros, document); } - if (contentArr != null && contentArr.length > 0 ) { - for (List content:contentArr) { - if (CollectionUtil.isNotEmpty(content)) { - fillRow(content, document); - } - } + if (CollectionUtil.isNotEmpty(content)) { + fillRow(content, document); } - } catch (DocumentException e) { e.printStackTrace(); log.error("导出pdf异常", e); @@ -126,7 +121,7 @@ public class PdfUtil { PdfPTable table = new PdfPTable(size); table.setSpacingBefore(0); - table.setWidthPercentage(100); + table.setWidthPercentage(90); for (int j = 0; j < rows.size(); j++) { Row row = rows.get(j); table.setHorizontalAlignment(row.align); @@ -134,9 +129,8 @@ public class PdfUtil { for (int i = 0; i < row.cells.size(); i++) { Cell cell = row.cells.get(i); PdfPCell pdfpCell = new PdfPCell(new Phrase(cell.content,font)); - pdfpCell.setBorderWidthTop(j == 0 && cell.borderTop == null && cell.borderBottom != null ? cell.borderBottom : cell.borderTop == null ? 0 : cell.borderTop); + pdfpCell.setBorderWidthTop(cell.borderTop == null ? 0 : cell.borderTop); pdfpCell.setBorderWidthLeft(cell.borderLeft == null ? 0 : cell.borderLeft); -// pdfpCell.setBorderWidthRight(i==row.cells.size() && cell.borderRight == null && cell.borderLeft != null ? cell.borderLeft : cell.borderRight == null ? 0 : cell.borderRight); pdfpCell.setBorderWidthRight(cell.borderRight == null ? 0 : cell.borderRight); pdfpCell.setBorderWidthBottom(cell.borderBottom == null ? 0 : cell.borderBottom); pdfpCell.setColspan(cell.colSpan); @@ -201,22 +195,6 @@ public class PdfUtil { // 单元格是否居中 private boolean isCenter = true; - public Cell() { - } - public Cell(String content) { - this.content = content; - } - public Cell(String content,int colSpan,int rowSpan) { - this.content = content; - this.colSpan = colSpan == 0 ? 1 : colSpan; - this.rowSpan = rowSpan == 0 ? 1 : rowSpan; - } - public Cell(String content,int colSpan,int rowSpan,Integer borderRight) { - this.content = content; - this.colSpan = colSpan == 0 ? 1 : colSpan; - this.rowSpan = rowSpan == 0 ? 1 : rowSpan; - this.borderRight = borderRight; - } } /** @@ -225,7 +203,7 @@ public class PdfUtil { @Data public static class Margin{ private float left = 72; - private float right = 72; + private float right = 0; private float top = 32; private float bottom = 32; } diff --git a/util/src/test/java/com/ccsens/util/PDFTest.java b/util/src/test/java/com/ccsens/util/PDFTest.java new file mode 100644 index 00000000..47e2a630 --- /dev/null +++ b/util/src/test/java/com/ccsens/util/PDFTest.java @@ -0,0 +1,101 @@ +package com.ccsens.util; + +import com.itextpdf.text.*; +import com.itextpdf.text.pdf.*; +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.ResourceLoader; + +import javax.script.ScriptException; +import java.io.ByteArrayOutputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +@Slf4j +public class PDFTest { + + @Test + public void test1() throws IOException { + Map map = new HashMap(); + map.put("undefined","张三"); + + + Map map2 = new HashMap(); + map2.put("img","c:/50336.jpg"); + + Map o=new HashMap(); + o.put("datemap",map); + o.put("imgmap",map2); + pdfout(o); + + } + + // 利用模板生成pdf + @Test + public static void pdfout(Map o) { + // 模板路径 + String templatePath = "C:/Users/10626/Desktop/静脉溶栓、血管内介入治疗数据直报表(试行)Form.pdf"; + // 生成的新文件路径 + String newPDFPath = "C:/Users/10626/Desktop/testout1.pdf"; + + PdfReader reader; + FileOutputStream out; + ByteArrayOutputStream bos; + PdfStamper stamper; + try { + BaseFont bf = BaseFont.createFont("c://windows//fonts//simsun.ttc,1" , BaseFont.IDENTITY_H, BaseFont.EMBEDDED); + Font FontChinese = new Font(bf, 5, Font.NORMAL); + out = new FileOutputStream(newPDFPath);// 输出流 + reader = new PdfReader(templatePath);// 读取pdf模板 + bos = new ByteArrayOutputStream(); + stamper = new PdfStamper(reader, bos); + AcroFields form = stamper.getAcroFields(); + //文字类的内容处理 + Map datemap = (Map)o.get("datemap"); + form.addSubstitutionFont(bf); + for(String key : datemap.keySet()){ + String value = datemap.get(key); + form.setField(key,value); + } + //图片类的内容处理 + Map imgmap = (Map)o.get("imgmap"); + for(String key : imgmap.keySet()) { + String value = imgmap.get(key); + String imgpath = value; + int pageNo = form.getFieldPositions(key).get(0).page; + Rectangle signRect = form.getFieldPositions(key).get(0).position; + float x = signRect.getLeft(); + float y = signRect.getBottom(); + //根据路径读取图片 + Image image = Image.getInstance(imgpath); + //获取图片页面 + PdfContentByte under = stamper.getOverContent(pageNo); + //图片大小自适应 + image.scaleToFit(signRect.getWidth(), signRect.getHeight()); + //添加图片 + image.setAbsolutePosition(x, y); + under.addImage(image); + } + stamper.setFormFlattening(true);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑 + stamper.close(); + Document doc = new Document(); + Font font = new Font(bf, 32); + PdfCopy copy = new PdfCopy(doc, out); + doc.open(); + PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1); + copy.addPage(importPage); + doc.close(); + + } catch (IOException e) { + System.out.println(e); + } catch (DocumentException e) { + System.out.println(e); + } + + } + +}