【发布时间】: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