WebObjects/Web 應用程式/開發/PDF 生成
外觀
您可能還想檢視 返回檔案 示例。
重要的是在“其他引數”列表中新增“-Djava.awt.headless=true”以抑制執行 WOBootstrap 的控制檯視窗,該視窗會嘗試彈出並隨後無法關閉,這似乎阻止了執行緒返回,從而導致應用程式掛起。
private ByteArrayOutputStream pdf()
{
// binary container for PDF
ByteArrayOutputStream out = null;
try
{
// assume these exist
String xsl, xml;
TransformerFactory transformerFactory = TransformerFactory.newInstance();
// configure FOP, apache's XML->PDF transformer
Fop fop = new Fop(MimeConstants.MIME_PDF);
out = new ByteArrayOutputStream();
fop.setOutputStream(out);
// configure XSLT transformer
Source xsltSrc = new StreamSource(new StringReader(xsl));
Transformer transformer = transformerFactory.newTransformer(xsltSrc);
// pipe XSL transformation through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
// grab XML input stream
Source src = new StreamSource(new StringReader(xml));
// Start the transformation and rendering process
transformer.transform(src, res);
}
catch (Exception e)
{
// actually, catch the following, one by one:
// TransformerConfigurationException
// FOPException
// TransformerFactoryConfigurationError
// TransformerException
}
return out;
}
public void appendToResponse(WOResponse response, WOContext context)
{
ByteArrayOutputStream out = pdf();
// without data, show the PDF page, which is just an error message.
if (out == null)
super.appendToResponse(response, context);
// assume this exists
String filename;
response.setHeader("application/pdf", "Content-Type");
response.setHeader("" + out.size() + "", "Content-Length");
response.setHeader("attachment;filename=" + filename, "Content-Disposition");
response.setContent(new NSData(out.toByteArray()));
}