是否可以使用play framework 2呈现pdf文档?
(有一个模块可以播放pdf播放1.x.有没有办法在播放2中渲染?)
答案 0 :(得分:5)
如果您要将视图模板呈现为PDF文档,请查看this module。
答案 1 :(得分:0)
有一个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;
}
答案 2 :(得分:0)
使用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")
}