通过Java用AbstractPdfView通过电子邮件发送PDF

时间:2019-04-30 04:22:42

标签: java spring email pdf itext

我使用AbstractPdfView类生成pdf并在浏览器中下载,但我还需要通过电子邮件发送它。我知道解决方案非常明显,但是我已经坚持了一天,无法看到它。这是我到目前为止所拥有的:

@GetMapping()
public PdfView generate(Model model, @RequestParam int event) {

  model.addAttribute("event", eventService.getEventById(event));

  return new PdfView();


}

这是PdfView类:

public class PdfView extends AbstractPdfView {

   @Override
   protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception {

        //add the iformation for the pdf
        document.add(getInvoiceInfo());

   }
}

这是AbstractPdfView类:

public abstract class AbstractPdfView extends AbstractView {

   public AbstractPdfView() {
      setContentType("application/pdf");
   }

   @Override
   protected boolean generatesDownloadContent() {
      return true;
   }

   @Override
   protected final void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

  ByteArrayOutputStream out = createTemporaryOutputStream();

  Document document = new Document(PageSize.A4.rotate(), 35, 35, 50, 36);
  PdfWriter writer = PdfWriter.getInstance(document, out);
  prepareWriter(model, writer, request);
  buildPdfMetadata(model, document, request);

  document.open();
  buildPdfDocument(model, document, writer, request, response);
  document.close();

    //i know i has to happen before this bit here but not sure how
   writeToResponse(response, out);

}

   protected void prepareWriter(Map<String, Object> model, PdfWriter writer, HttpServletRequest request) throws DocumentException {
      writer.setViewerPreferences(getViewerPreferences());
   }

   protected int getViewerPreferences() {
      return PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage;
   }


   protected void buildPdfMetadata(Map<String, Object> model, Document document, HttpServletRequest request) {
   }

   protected abstract void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer,
                                            HttpServletRequest request, HttpServletResponse response) throws Exception;
}

欢迎任何帮助!谢谢你们。

1 个答案:

答案 0 :(得分:0)

好吧,我已经做到了。如果有人遇到此问题,请在此处发布。我基本上在AbstractPdfView的实现中自动连接了emailService,并用它来调用抽象类的构造函数。这也是有关该主题的好读物:https://www.baeldung.com/spring-autowired-abstract-class