保存对话框创建pdf

时间:2013-06-06 14:02:57

标签: java jsp

我有一个jsp调用一个servlet来创建'on fly'一个pdf。

  public class HelloWorld extends Action
  {
     public static final String RESULT= "C:\hello.pdf";

     public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
     {
        try {
           new HelloWorld().createPdf(RESULT);
        } catch (Exception e) {
           e.printStackTrace();
           return mapping.findForward("Failure");
        }
        return mapping.findForward("Success");
     }

     public void createPdf(String filename) throws IOException, DocumentException {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
        PdfPTable table = createTable1();
        document.add(table);
        document.close();
     }

     public static PdfPTable createTable1() throws DocumentException {
        ...
     }
  }

我希望有一个类似“另存为”的消息框,而不是静态路径C:\hello.pdf

1 个答案:

答案 0 :(得分:1)

您可以使用缓冲区输出流在内存中创建pdf,而不是创建FileOutputStream,然后您可以使用jsp将pdf作为二进制文件返回并让浏览器处理它(显示另存为窗口)。

你的jsp代码会是这样的(假设你有一个代表你的PDF文件的byte []):

response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "inline; filename=\"filename.pdf\"");
response.setBufferSize(pdf.length);
response.setContentLength(pdf.length);
response.getOutputStream().write(pdf);

请确保在回复中不要在这些说明之前写任何字符。

希望这有帮助,
此致

相关问题