gpt4 book ai didi

java - 创建 pdf 的保存对话框

转载 作者:行者123 更新时间:2023-12-01 14:29:01 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com