有没有可能用play Framework2渲染pdf文档?
(有一个模块可以为play 1.x渲染pdf。在实战2中有没有渲染的方法?)
发布于 2013-04-24 17:48:38
如果您希望将视图模板呈现为PDF文档,请查看this module。
发布于 2014-12-15 20:13:35
有一个apache fop插件可以从fop文件中创建pdf。
fop文件并不是最直观的文件,但最终我总能找到一种方法来格式化复杂的pdf格式,以我想要的方式。
要将插件添加到您的play应用程序中,请将以下内容添加到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;
}
发布于 2016-07-05 02:28:34
当使用play with 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")
}
https://stackoverflow.com/questions/16188374
复制相似问题