java保存对话框创建pdf

xqkwcwgp  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(509)

我有一个jsp,它调用一个servlet来创建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

fnx2tebb

fnx2tebb1#

不用创建fileoutputstream,您可以使用缓冲区输出流在内存中创建pdf,然后可以使用jsp将pdf作为二进制文件返回,并让浏览器处理它(显示“另存为”窗口)。
您的jsp代码如下(假设您将有一个字节[]代表您的pdf文件):

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

在你的回答中,一定不要在这些指令之前写任何字符。
希望这有帮助,
当做

相关问题