java实现在pdf⽂档上填充内容
需求:
在合同附件模板上填充内容,⽣成⼀个新的合同附件,并可以查看合同附件
思路:
⾸先在模板⽂档上设置⽂本域,根据⽂本域填充内容,使⽤itextpdf在pdf上填充内容
1.在l中加⼊以下依赖:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2.在application.properties中配置⽂件模板路径和⽂件保存路径
conf.uploadContractAttachTemplatePath=D:\\wkgbErp\\upload\\ContractTemplatePath\\\u9644\u4EF6\u4E00 \u623F\u5C4B\u53CA\u79DF\u8D41\u4FE1\u606F\u8868.pdf
conf.saveUploadContractAttachPath=D:\\wkgbErp\\upload\\ContractTemplatePath\\contractAttach\\
3.创建⼀个service接⼝:
/**
* ⽣成合同附件
*/
@Override
public ErrorObject generateContractAttach(String contractId) {
ErrorObject error = new ErrorObject();
PdfReader reader;
FileOutputStream out;
ByteArrayOutputStream bos;
PdfStamper stamper;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
if (StringUtils.isNotBlank(contractId)) {
TblContractPre entity = tblContractPreRepository.findByDeedsn(contractId);
TblIdentify identify = identifyService.Uid());
String fileName = contractId + ".pdf";
String newPDFPath = saveUploadContractAttachPath + fileName;
try {
out = new FileOutputStream(newPDFPath);
reader = new PdfReader(uploadContractAttachTemplatePath);// 读取pdf模板
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = AcroFields();
// java.util.Iterator<String> it = Fields().keySet().iterator();
// while (it.hasNext()) {
/
/ String name = it.next().toString();
// // 填写内容部分
// form.setField(name, Name());
// }
// }
// ateFont("STSongStd-Light", "UTF-8", false);
form.setField("liveName", Name());// 租客姓名
if (DeedsnStart() != null) {
form.setField("deedsnStart", dateFormat.DeedsnStart()));// 合同开始时间
}
if (DeedsnEnd() != null) {
form.setField("deedsnEnd", dateFormat.DeedsnEnd()));// 合同结束时间
}
if (MonthNum() != null) {// ⽀付⽅式
if (MonthNum() == 1) {
form.setField("monthNum", "押⼆ ⽉付");
}
if (MonthNum() == 3) {
form.setField("monthNum", "押⼆ 季付");
}
if (MonthNum() == 6) {
form.setField("monthNum", "押⼆ 半年付");
}
if (MonthNum() == 12) {
form.setField("monthNum", "押⼆ 年付");
}
}
form.setField("roomsn", Roomsn());// 房源编号
if (Rental() != null) {
form.setField("rental", Rental().toString());// 租⾦
BigDecimal rental = Rental();
BigDecimal deposit = rental.multiply(new BigDecimal(2));// 押⾦=租⾦*2
BigDecimal total = rental.multiply(new BigDecimal(12));// 总计
form.setField("total", total + "元");// 总计
form.setField("deposit", String()); // 押⾦
}
form.setField("houseAddress", HouseName().replace(";", ""));// 产权地址
if (BuildArea() != null) {
form.setField("buildArea", BuildArea() + "平⽶");// ⾯积
}
// 填充租⾦⽀付明细
if (DeedsnStart() != null) {
Calendar calendar = Instance();
calendar.DeedsnStart());
calendar.add(Calendar.DATE, -1);
Date date = Time();
form.setField("deedsnStart1", dateFormat.DeedsnStart()));
form.setField("deedsnTime1", dateFormat.DeedsnStart()) + " / " + DateUtil.AddMonth(date, 1));
form.setField("deedsnStart2", DateUtil.DeedsnStart(), 1));
form.setField("deedsnTime2",
DateUtil.DeedsnStart(), 1) + " / " + DateUtil.AddMonth(date, 2));
form.setField("deedsnStart3", DateUtil.DeedsnStart(), 2));
form.setField("deedsnTime3",
DateUtil.DeedsnStart(), 2) + " / " + DateUtil.AddMonth(date, 3));
form.setField("deedsnStart4", DateUtil.DeedsnStart(), 3));
form.setField("deedsnTime4",
DateUtil.DeedsnStart(), 3) + " / " + DateUtil.AddMonth(date, 4));
form.setField("deedsnStart5", DateUtil.DeedsnStart(), 4));
form.setField("deedsnTime5",
DateUtil.DeedsnStart(), 4) + " / " + DateUtil.AddMonth(date, 5));
form.setField("deedsnStart6", DateUtil.DeedsnStart(), 5));
form.setField("deedsnTime6",
DateUtil.DeedsnStart(), 5) + " / " + DateUtil.AddMonth(date, 6));
form.setField("deedsnStart7", DateUtil.DeedsnStart(), 6));
form.setField("deedsnTime7",
DateUtil.DeedsnStart(), 6) + " / " + DateUtil.AddMonth(date, 7));
form.setField("deedsnStart8", DateUtil.DeedsnStart(), 7));
form.setField("deedsnTime8",
DateUtil.DeedsnStart(), 7) + " / " + DateUtil.AddMonth(date, 8));
form.setField("deedsnStart9", DateUtil.DeedsnStart(), 8));
form.setField("deedsnTime9",
DateUtil.DeedsnStart(), 8) + " / " + DateUtil.AddMonth(date, 9));
form.setField("deedsnStart10", DateUtil.DeedsnStart(), 9));
form.setField("deedsnTime10",
DateUtil.DeedsnStart(), 9) + " / " + DateUtil.AddMonth(date, 10));
form.setField("deedsnStart11", DateUtil.DeedsnStart(), 10));
form.setField("deedsnTime11",
DateUtil.DeedsnStart(), 10) + " / " + DateUtil.AddMonth(date, 11));
form.setField("deedsnStart12", DateUtil.DeedsnStart(), 11));
form.setField("deedsnTime12",
DateUtil.DeedsnStart(), 11) + " / " + DateUtil.AddMonth(date, 12)); }
if (SignType() != null) {
if (SignType() == 0) {
form.setField("signType1", "true");// ⾸次签约复选框选中
}
if (SignType() == 1) {
form.setField("signType2", "true");
}
}
if (DepositeType() != null) {
if (DepositeType() == 0) {
form.setField("d1", "true");// ⾸次签约押⾦复选框选中
}
if (DepositeType() == 1) {
form.setField("d2", "true");// ⾸次签约押⾦复选框选中
}
}
form.setField("c1", "true");// ⾝份证复选框选中
if (Sex() != null) {
if (Sex() == 0) {// 性别
form.setField("sex", "⼥");
}
if (Sex() == 1) {
form.setField("sex", "男");
}
}
if (Age() != null) {
form.setField("age", Age().toString());// 年龄
}
form.setField("phone", PhoneNum());//
form.setField("email", Email());
if (StringUtils.EmergencyName())) {// 紧急联系⼈
form.setField("emergencyName", EmergencyName());
}
if (StringUtils.EmergencyPhone())) {// 紧急联系⼈电话
form.setField("emergencyPhone", EmergencyPhone());
}
form.setField("certificateNum", CertificateNum());// ⾝份证号码
if (StringUtils.CompanyAddr())) {
form.setField("companyAddr", CompanyAddr());// 租客通讯地址
}
stamper.setFormFlattening(true);// 如果为false那么⽣成的PDF⽂件还能编辑,⼀定要设为true stamper.close();
getsavefilename// Document doc = new Document();
// PdfCopy copy = new PdfCopy(doc, out);
// doc.open();
// PdfImportedPage importPage = ImportedPage(new
// ByteArray()), 1);
// copy.addPage(importPage);
// doc.close();
out.ByteArray());
out.flush();
out.close();
bos.close();
} catch (FileNotFoundException e1) {
<("{}", e1);
} catch (IOException e2) {
<("{}", e2);
} catch (DocumentException e3) {
<("{}", e3);
}
// 保存附件⽂件名
entity.setFileName(fileName);
// tblContractPreRepository.save(entity);
save(entity);
}
return error;
}
4.单元测试
package com.szwoku.gbwk.web.service;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.st.context.SpringBootTest;
import st.context.junit4.SpringRunner;
import cn.wkgb.AppConfiguration;
import cn.wkgb.api.service.TblContractPreService;
import cn.wkgbmon.framework.dto.ErrorObject;
slf4j.Slf4j;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AppConfiguration.class)
public class TblContractPreServiceTest {
@Resource
private TblContractPreService tblContractPreService;
@Test
public void testGenerateContractAttach() {
ErrorObject error = ateContractAttach("PRE-HA180900079"); log.warn("error= {}", error);
}
}
5.查看合同接⼝
/**
* 查看合同附件
*
* @param fileName
* @param request
* @param response
* @throws Exception
*/
@RequestMapping(value = { "/viewPdf/{fileName:.+}" })
public ErrorObject viewPdf(@PathVariable String fileName, final HttpServletResponse request, final HttpServletResponse response) throws Exception {
ErrorObject error = new ErrorObject();
String ext = StringUtils.substringAfterLast(fileName, ".");
String path = saveUploadContractAttachPath + fileName;
logger.debug(path);
File file = new File(path);
if (!ists()) {
return error;
}
if ("pdf".equalsIgnoreCase(ext)) {
response.setContentType(PDF);
}
OutputStream out = OutputStream();
IOUtils.adFileToByteArray(file), out);
return error;
}
6.页⾯
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论