首页>代码>JPA使用视图进行查询、使用Adobe Acrobat准备表单生成PDF>/JpaFormPdf/src/main/java/com/ldg/test/controller/Report2Controller.java
package com.ldg.test.controller; import com.itextpdf.text.pdf.AcroFields; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.ldg.test.modal.User; import com.ldg.test.modal.UserView; import com.ldg.test.service.IUserService; import com.ldg.test.service.IUserViewService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; @Controller public class Report2Controller { @Autowired private IUserViewService service; @RequestMapping("/report2/{id}") public void showEditUserForm(@PathVariable(name = "id") Long id, HttpServletRequest request, HttpServletResponse response) throws IOException { UserView userView = service.get(id); String f = "用户档案_" + userView.getName() + ".pdf"; //设置请求返回类型 String downFilename = new String(f.getBytes("UTF-8"), "ISO-8859-1"); response.setHeader("Content-Disposition", "attachment; filename=" + downFilename); String filePdf = "user.pdf"; //模板路径,放到项目里用这个ClassPathResource String filePathPdf = "templates/pdf/" + filePdf; ClassPathResource classPathResource = new ClassPathResource(filePathPdf); InputStream inputStream = classPathResource.getInputStream(); Map<String, String> map = new HashMap<>(); map.put("name", userView.getName()); map.put("address", userView.getAddress()); map.put("phone", userView.getPhone()); map.put("depName", userView.getDepName()); map.put("remark", userView.getRemark()); PdfReader reader; PdfStamper stamper; OutputStream out = response.getOutputStream(); try { reader = new PdfReader(inputStream);// 读取pdf模板 stamper = new PdfStamper(reader, out); AcroFields form = stamper.getAcroFields(); //遍历map装入数据 for (Map.Entry<String, String> entry : map.entrySet()) { form.setField(entry.getKey(), entry.getValue()); //System.out.println("插入PDF数据----> key= " + entry.getKey() + " and value= " + entry.getValue()); } stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑,一定要设为true stamper.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } } }
最近浏览更多
3993zby LV2
11月11日
Peny_ZH LV5
9月21日
liiiyou LV1
6月2日
kenhomeliu LV29
4月30日
youwuzuichen LV10
4月17日
woldxy LV12
4月1日
wanglinddad LV55
3月13日
田DJ sozzled
3月2日
暂无贡献等级
1134116035
2月28日
暂无贡献等级
houxianzheng
2月19日
暂无贡献等级