1
我正嘗試使用Struts2下載PDF文件。爲了生成PDF,我使用PDFBox。Pdf文件未與內容一起下載
我可以下載PDF文件,但問題是它的大小是0字節。
Action類
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'公共字符串getPdf()拋出異常{ \t的inputStream =新的FileInputStream(新文件(「C:\\ downloadfile.pdf 「)); \t return SUCCESS; \t}' –
嘗試使用contentStream.flush() – niiraj874u
刷新contentStream操作和結果代碼都很好。你確定這個文件在動作中不是0字節嗎?你可以在退出方法之前打印'bos.toByteArray()。length'? –