【问题标题】:Pdf file is not downloading with contentPdf文件没有下载内容
【发布时间】:2014-04-17 07:01:02
【问题描述】:

我正在尝试使用 Struts2 下载 PDF 文件。为了生成 PDF,我使用的是 PDFBox。

我可以下载 PDF 文件,但问题是它的大小为 0 字节。

动作类

public class BarcodeAction extends ActionSupport {

    private InputStream inputStream;
    //getter and setter

    public String getPdf() {
        System.out.println("Get Pdf");
        PDDocument document = null;
        try {
            document = new PDDocument();
            PDPage page = new PDPage();
            document.addPage(page);
            PDFont headingFont = PDType1Font.TIMES_ROMAN;
            PDPageContentStream contentStream = 
                            new PDPageContentStream(document, page, false, true);
            contentStream.beginText();
            contentStream.setFont(headingFont, 26);
            contentStream.moveTextPositionByAmount(250, 700);
            contentStream.drawString("Hello World !");
            contentStream.endText();
            contentStream.close();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            document.save(bos);
            setInputStream(new ByteArrayInputStream(bos.toByteArray()));
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (COSVisitorException e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }
}

struts.xml

<action name="GenerateBarCode" class="foo.bar.BarcodeAction" method="getPdf">
   <result name="success" type="stream">
        <param name="contentDisposition">attachment;filename=test.pdf</param>
        <param name="contentType">application/pdf</param>
        <param name="inputName">inputStream</param>
        <param name="bufferSize">1024</param>
    </result>
    <result name="input">/pages/ExpNImp/Export.jsp</result>
    <result name="login">/pages/login.jsp</result>
</action>

如何正确下载PDF文件?

【问题讨论】:

  • 先试试这个看看有没有下载pdf public String getPdf() throws Exception { inputStream= new FileInputStream(new File("C:\\downloadfile.pdf")); return SUCCESS; }
  • 尝试使用 contentStream.flush() 刷新 contentStream
  • 操作和结果代码都可以。您确定文件在操作中不是 0 字节吗?你能在退出方法之前打印bos.toByteArray().length吗?
  • 感谢 cmets。并提出富有成效的建议

标签: java jsp pdf struts2 pdfbox


【解决方案1】:

我只做了一项更改,但它不起作用 我删除了 document.close(); 从上面的代码。

现在可以正常使用了

【讨论】:

  • 这很奇怪,毕竟你在关闭文档之前对文档进行了序列化。可能有一些未捕获的Throwable
猜你喜欢
  • 1970-01-01
  • 2013-05-01
  • 2012-03-13
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
相关资源
最近更新 更多