是否可以使用 play framework 2 渲染 pdf 文档?
(有一个模块可以为play 1.x渲染pdf。有没有办法在play 2中渲染?)
是否可以使用 play framework 2 渲染 pdf 文档?
(有一个模块可以为play 1.x渲染pdf。有没有办法在play 2中渲染?)
如果您希望将视图模板呈现为 PDF 文档,请查看此模块。
有一个 apache fop 插件,它可以从 fop 文件中创建 pdf。
fop 文件不是最直观的文件,但最后我总能找到一种方法来按照我想要的方式格式化复杂的 pdf。
要将插件添加到您的播放应用程序中,请将其添加到 build.sbt :
"org.apache.avalon.framework" % "avalon-framework-api" % "4.2.0" from "http://repo1.maven.org/maven2/avalon-framework/avalon-framework-api/4.2.0/avalon-framework-api-4.2.0.jar",
"org.apache.avalon.framework" % "avalon-framework-impl" % "4.2.0" from "http://repo1.maven.org/maven2/avalon-framework/avalon-framework-impl/4.2.0/avalon-framework-impl-4.2.0.jar",
"org.apache.xmlgraphics" % "fop" % "1.1"
这是我从 fop 字符串创建 pdf 文件的函数:
private static FopFactory fopFactory = FopFactory.newInstance();
/**
* Wrote according to this example :
* http://xmlgraphics.apache.org/fop/1.1/embedding.html#examples
* @param outputPath Path to the file to create (must end by .pdf).
* @param foString Description of the pdf document to render.
* http://www.w3schools.com/xslfo/default.asp
* @return the output path.
*/
public static String toPdf(String outputPath, String foString)
{
OutputStream out;
try {
File fileOutput = new File(outputPath);
out = new BufferedOutputStream(new FileOutputStream(fileOutput));
} catch (FileNotFoundException e) {
Logger.error("InvoicePdf.invoiceToPdf: " + e.getMessage());
return null;
}
try {
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
Source src = new StreamSource(new StringReader(foString));
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
}catch (Throwable e){
Logger.error("InvoicePdf.invoiceToPdf: " + e.getMessage());
e.printStackTrace();
return null;
} finally {
try {
out.close();
} catch (Throwable e) {
Logger.error("InvoicePdf.invoiceToPdf: " + e.getMessage());
}
}
return outputPath;
}
使用 scala 游戏时,您可以使用 scala 库https://github.com/cloudify/sPDF。
然后在您的 Play 2.x 控制器中,您可以使用以下代码呈现 pdf:
import io.github.cloudify.scala.spdf.{Pdf, PdfConfig, Portrait}
def yourAction = Action { implicit request =>
val pdf = Pdf(
executablePath = "/usr/bin/wkhtmltopdfPath",
config = new PdfConfig {
orientation := Portrait
pageSize := "A4"
marginTop := "0.5in"
marginBottom := "0.5in"
marginLeft := "0.5in"
marginRight := "0.5in"
printMediaType := Some(true)
}
)
val outputStream = new ByteArrayOutputStream
pdf.run(
sourceDocument = views.html.yourTemplate().toString(),
destinationDocument = outputStream
)
Ok(outputStream.toByteArray).as("application/pdf")
}