spring-portlet生成pdf文件

print ?
 生成PDF有两种方式:一种是用java直接产生PDF文件,但不能定制格式;另一种是使用PDF的模板,由java填充数据,好处可以定制输出格式。如下代码是使用PDF模板来填充数据 

注意在Controller里必须使用ResourceRequest和ResourceResponse来获取输出流

需要注意的是,jsp页面上用href来请求下载功能

  1. @RequestMapping(params = "action=getPDF")
  2. public void getPDF(ResourceRequest request, ResourceResponse response)
  3. throws Exception {
  4. String pdfType = request.getParameter("pdfType");
  5. response.reset();
  6. response.setContentType("application/pdf");
  7. String attachmentFilename = "";
  8. int modelId = 0;
  9. if (pdfType.equals(MailTemplate.TYPE_PAYMENT)) {
  10. modelId = regConfig.getReceiptId();
  11. attachmentFilename = "attachment; filename=\"receipt.pdf" + "\"";
  12. } else if (pdfType.equals(MailTemplate.TYPE_INVITATION)) {
  13. modelId = regConfig.getInvitationId();
  14. attachmentFilename = "attachment; filename=\"invitation.pdf" + "\"";
  15. } else {
  16. return;
  17. }
  18. response.setProperty("Content-disposition", attachmentFilename);
  19. String filepath = defaultTemplateContext.getDefaultDir()
  20. + File.separator;
  21. filepath += MailTemplate.DEF_INVITATION_MODEL_PDF;
  22. ByteArrayOutputStream ous = null;
  23. InputStream ins = null;
  24. try {
  25. Map<String, Object> data = 。。。。。。;
  26. PDFTemplatePrinter rprinter = new PDFTemplatePrinter(filepath);
  27. ous = rprinter.getPDFOutpuStream(data);
  28. ins = new ByteArrayInputStream(ous.toByteArray());
  29. int b = -1;
  30. while ((b=ins.read())!=-1) {
  31. out.write(b);
  32. }
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. } finally {
  36. try {
  37. ins.close();
  38. ous.close();
  39. } catch (IOException e) {
  40. // TODO Auto-generated catch block
  41. e.printStackTrace();
  42. }
  43. }
  44. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值