jar包
<!--PDF工具-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>${itextpdf.version}</version>
</dependency>
pdf工具类
package com.ruoyi.common.utils.pdf;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.ruoyi.common.config.RuoYiConfig;
import com.sun.deploy.net.HttpDownload;
import com.sun.deploy.net.HttpResponse;
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletResponse;
public class PdfUtils {
// 利用模板生成pdf
public static void pdfout(Map<String,Object> o,String filePath) {
// 模板路径
String templatePath = "pdf/xfpdfdemo.pdf";
// 生成的新文件路径
String newPDFPath = filePath;
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);
}
//图片类的内容处理
try {
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);
}
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
stamper.setFormFlattening(true);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
stamper.close();
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
copy.addPage(importPage);
doc.close();
// IOUtils.write(bos.toByteArray(), response.getOutputStream());
} catch (IOException e) {
System.out.println(e);
} catch (DocumentException e) {
System.out.println(e);
}
}
}
serviceImpl(把一一对应的map格式,传给PdfUtils)
public void xzpdf(String uqprojectid, String filePath) throws NullPointerException {
Map<String, String> map = new HashMap();
Map<String, String> map2 = new HashMap();
Map strafftypemap = new HashMap();
TxfProject txfProject = txfProjectMapper.selectTxfProjectById(uqprojectid);
if (txfProject.getUqorgid() != null && !txfProject.getUqorgid().equals("")) {
TxfOrg txfOrg = txfOrgMapper.selectTxfOrgById(txfProject.getUqorgid());
// 处理从业人员
String cyrys = txfProject.getCyry();
if (cyrys != null && !cyrys.equals("")) {
String[] cyryList = cyrys.split(",");
Integer a = 2;
for (String cyry : cyryList) {
TxfUser txfUser = txfUserMapper.selectTxfUserById(cyry);//cyry 保存的多个id
// txfUser.getStafftype();//从业人员类别
List<SysDictData> sysDictDatalist = sysDictTypeService.selectDictDataByType("4");
//变量
if (txfUser.getStafftype() != null && !txfUser.getStafftype().equals("")) {
String[] types = txfUser.getStafftype().split(",");
for (String type : types) {
// strafftypemap.put(sysDictData.getDictValue(), sysDictData.getDictLabel());
// if (sysDictData.getDictValue().equals("4_1") || sysDictData.getDictValue().equals("4_2")) {
if (type.equals("4_1") || type.equals("4_2")) {
map.put("username1", txfUser.getUsername());
map.put("mobile1", txfUser.getMobile());
map.put("certificatenoorg", txfUser.getCertificatenoorg());
map2.put("imgCertificatenoorg", txfUser.getImgCertificatenoorg());
}
if (type.equals("4_5") || type.equals("4_6") || type.equals("4_7")) {
map.put("username" + a, txfUser.getUsername());
map.put("mobile" + a, txfUser.getMobile());
map.put("cto" + a, txfUser.getCto());
if (txfUser.getImgSelf() != null && !txfUser.getImgSelf().equals("")) {
TxfFilemap txfFilemap = txfFilemapMapper.selectTxfFilemapById(txfUser.getImgSelf());
map2.put("img" + a, txfFilemap.getFilepath());
}
a++;
}
}
}
}
// 保存所有的服务类型内容
HashMap<String, String> typeHashMap = new HashMap<>();
String[] types = {"9", "7", "6"};
for (String type : types) {
// 查询所有的服务类型内容,便利保存
List<SysDictData> sysDictDatas = sysDictTypeService.selectDictDataByType(type);
for (SysDictData sysDictData : sysDictDatas) {
typeHashMap.put(sysDictData.getDictValue(), sysDictData.getDictLabel());
}
}
if (txfProject.getServicecontent() != null && !txfProject.getServicecontent().equals("")) {
String[] split = txfProject.getServicecontent().split(",");
String servicecontent = "";
for (int i = 0; i < split.length; i++) {
typeHashMap.get(split[i]);
if (i == 0) {
servicecontent = typeHashMap.get(split[i]);
} else {
servicecontent += "," + typeHashMap.get(split[i]);
}
}
map.put("servicecontent", servicecontent);
}
map.put("jianzhuname", "");
map.put("orgname", txfOrg.getOrgname());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
if (txfProject.getContractstartdate() != null) {
map.put("contractstartdate", simpleDateFormat.format(txfProject.getContractstartdate()) + "至");
}
if (txfProject.getContractenddate() != null) {
map.put("contractenddate", simpleDateFormat.format(txfProject.getContractenddate()));
}
map.put("tousuphone", "");
map.put("date", "");
Map<String, Object> o = new HashMap();
o.put("datemap", map);
o.put("imgmap", map2);
PdfUtils.pdfout(o,filePath);
}
return;
}
}
controller层
@GetMapping("/downloadGs")
public void fileDownload(String uqprojectid, HttpServletResponse response, HttpServletRequest request)
{
try
{
String realFileName =UUID.randomUUID().toString()+".pdf";
String filePath = RuoYiConfig.getDownloadPath() + realFileName;
txfProjectService.xzpdf(uqprojectid,filePath);
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition",
"attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
FileUtils.writeBytes(filePath, response.getOutputStream());
// 删除
FileUtils.deleteFile(filePath);
}
catch (Exception e)
{
log.error("下载文件失败", e);
}
}