首页>代码>JPA使用视图进行查询、使用Adobe Acrobat准备表单生成PDF>/JpaFormPdf/src/main/java/com/ldg/test/controller/Report1Controller.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.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.data.domain.Page; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; 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.List; import java.util.Map; @Controller public class Report1Controller { @Autowired private IUserService service; @RequestMapping("/report/{id}") public void showEditUserForm(@PathVariable(name = "id") Long id, HttpServletRequest request, HttpServletResponse response) throws IOException { User user = service.get(id); String f = "用户信息表_" + user.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", user.getName()); map.put("address", user.getAddress()); map.put("phone", user.getPhone()); map.put("remark", user.getRemark()); PdfReader reader; //ByteArrayOutputStream bos=null; 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.setFormFlattening(false); 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日
暂无贡献等级