java - 创建 pdf 的保存对话框

标签 java jsp

我有一个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

最佳答案

您可以使用缓冲区输出流在内存中创建 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);

请务必不要在回复中的这些说明之前写入任何字符。

希望这有帮助,
问候

关于java - 创建 pdf 的保存对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16964168/

相关文章:

java - 如何在 Java 中解析损坏的 XML 文件?

java - 如何在 Gradle 中使用不同的系统属性值多次运行测试

java - 如何在Java中渲染倾斜的图像?

java - 在构建 JSTL 经典 Select 标签后,我应该将 null 设置为大项吗

java - Spring MVC;避免 url 中的文件扩展名?

JavaFx 对 EDT 的答复?

java - 使用 Spring boot 在 thymeleaf 模板中打印数据时出现问题

java - HTTP 状态 500 - org.apache.jasper.JasperException : java. lang.NullPointerException

javascript - 杰伊: form with jsp and angular

java - Spring mvc 布局没有瓷砖