Browse Source

PDf测试

tall3
ma 4 years ago
parent
commit
b5ca1e7364
  1. 137
      tall/src/main/java/com/ccsens/tall/web/DebugController.java
  2. 48
      util/src/main/java/com/ccsens/util/PdfUtil.java
  3. 101
      util/src/test/java/com/ccsens/util/PDFTest.java

137
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.MessageConstant;
import com.ccsens.util.bean.message.common.MessageRule; import com.ccsens.util.bean.message.common.MessageRule;
import com.ccsens.util.config.RabbitMQConfig; import com.ccsens.util.config.RabbitMQConfig;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.PlatformTransactionManager;
@ -31,7 +34,11 @@ import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*; import java.util.*;
import java.util.List;
@Slf4j @Slf4j
@Api(tags = "DEBUG" , description = "DebugController | ") @Api(tags = "DEBUG" , description = "DebugController | ")
@ -162,4 +169,134 @@ public class DebugController {
return a; 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<String,String> 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<String,String> map3 = new HashMap();
map3.put("gender","0");
// map3.put("Group7","1");
//多选
Map<String,String> duoxuan = new HashMap();
duoxuan.put("JMRS-RSYY","0");
// duoxuan.put("CheckBox5","0");
// duoxuan.put("CheckBox6","1");
//图片
Map<String,String> map2 = new HashMap();
// map2.put("img","c:/50336.jpg");
Map<String,Object> 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<String,Object> 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<String,String> datemap = (Map<String,String>)o.get("datemap");
form.addSubstitutionFont(bf);
for(String key : datemap.keySet()){
String value = datemap.get(key);
form.setField(key,value);
}
//单选
Map<String,String> danxuan = (Map<String,String>)o.get("danxuan");
form.addSubstitutionFont(bf);
for (String key : danxuan.keySet()) {
form.setField(key,"0",true);
}
//多选
Map<String,String> duoxuan = (Map<String,String>)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<String,String> imgmap = (Map<String,String>)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);
}
}
} }

48
util/src/main/java/com/ccsens/util/PdfUtil.java

@ -28,14 +28,14 @@ public class PdfUtil {
/** /**
* 生成pdf * 生成pdf
* @param parentPath 文件夹路径 * @param parentPath
* @param title 标题 * @param title
* @param subhead 副标题 * @param subhead 副标题
* @param intros 介绍 * @param intros
* @param contentArr 正文 * @param content
* @return * @return
*/ */
public static String createPdf(String parentPath, String title, String subhead, Margin margin, List<Row> intros, List<Row>... contentArr) { public static String credatePdf(String parentPath, String title, String subhead, List<Row> intros, List<Row> content, Margin margin) {
String fileName = "pdf/" + DateUtil.today() + "/" + System.currentTimeMillis() + ".pdf"; String fileName = "pdf/" + DateUtil.today() + "/" + System.currentTimeMillis() + ".pdf";
log.info("pdf文件名:{}", fileName ); log.info("pdf文件名:{}", fileName );
File file = new File(parentPath, 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); 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); Paragraph par = new Paragraph(title, titleChinese);
par.setAlignment(Element.ALIGN_CENTER); par.setAlignment(Element.ALIGN_CENTER);
@ -59,27 +59,22 @@ public class PdfUtil {
if (StrUtil.isNotBlank(subhead)) { 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); Paragraph subheadPar = new Paragraph(subhead, subheadChinese);
subheadPar.setAlignment(Element.ALIGN_CENTER); subheadPar.setAlignment(Element.ALIGN_CENTER);
document.add(subheadPar); document.add(subheadPar);
} }
// 每行加空白 // 每行加空白
fillBlankRow(document, new Font(bfChinese, 3, Font.NORMAL)); fillBlankRow(document, titleChinese);
//设置介绍内容 //设置介绍内容
if (CollectionUtil.isNotEmpty(intros)) { if (CollectionUtil.isNotEmpty(intros)) {
fillRow(intros, document); fillRow(intros, document);
} }
if (contentArr != null && contentArr.length > 0 ) { if (CollectionUtil.isNotEmpty(content)) {
for (List<Row> content:contentArr) { fillRow(content, document);
if (CollectionUtil.isNotEmpty(content)) {
fillRow(content, document);
}
}
} }
} catch (DocumentException e) { } catch (DocumentException e) {
e.printStackTrace(); e.printStackTrace();
log.error("导出pdf异常", e); log.error("导出pdf异常", e);
@ -126,7 +121,7 @@ public class PdfUtil {
PdfPTable table = new PdfPTable(size); PdfPTable table = new PdfPTable(size);
table.setSpacingBefore(0); table.setSpacingBefore(0);
table.setWidthPercentage(100); table.setWidthPercentage(90);
for (int j = 0; j < rows.size(); j++) { for (int j = 0; j < rows.size(); j++) {
Row row = rows.get(j); Row row = rows.get(j);
table.setHorizontalAlignment(row.align); table.setHorizontalAlignment(row.align);
@ -134,9 +129,8 @@ public class PdfUtil {
for (int i = 0; i < row.cells.size(); i++) { for (int i = 0; i < row.cells.size(); i++) {
Cell cell = row.cells.get(i); Cell cell = row.cells.get(i);
PdfPCell pdfpCell = new PdfPCell(new Phrase(cell.content,font)); 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.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.setBorderWidthRight(cell.borderRight == null ? 0 : cell.borderRight);
pdfpCell.setBorderWidthBottom(cell.borderBottom == null ? 0 : cell.borderBottom); pdfpCell.setBorderWidthBottom(cell.borderBottom == null ? 0 : cell.borderBottom);
pdfpCell.setColspan(cell.colSpan); pdfpCell.setColspan(cell.colSpan);
@ -201,22 +195,6 @@ public class PdfUtil {
// 单元格是否居中 // 单元格是否居中
private boolean isCenter = true; 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 @Data
public static class Margin{ public static class Margin{
private float left = 72; private float left = 72;
private float right = 72; private float right = 0;
private float top = 32; private float top = 32;
private float bottom = 32; private float bottom = 32;
} }

101
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<String,String> map = new HashMap();
map.put("undefined","张三");
Map<String,String> map2 = new HashMap();
map2.put("img","c:/50336.jpg");
Map<String,Object> o=new HashMap();
o.put("datemap",map);
o.put("imgmap",map2);
pdfout(o);
}
// 利用模板生成pdf
@Test
public static void pdfout(Map<String,Object> 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<String,String> datemap = (Map<String,String>)o.get("datemap");
form.addSubstitutionFont(bf);
for(String key : datemap.keySet()){
String value = datemap.get(key);
form.setField(key,value);
}
//图片类的内容处理
Map<String,String> imgmap = (Map<String,String>)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);
}
}
}
Loading…
Cancel
Save