Grails Render PDF Plugin返回NullPointerException

时间:2015-01-30 14:04:30

标签: java grails pdf grails-plugin flying-saucer

我正在尝试使用渲染插件渲染pdf文件。我的控制器代码是:

def toPDF(){
    DomainClass domainClass = DomainClass.get(params.id)


    try{
        renderPdf(template: "/domainClass/pdf", model: [domain: domainClass], filename: System.currentTimeMillis().toString() + "_" + domainClass.id.toString() + ".pdf")
    }catch(e){
        redirect action: "error"
    }

}

在开发模式下,它可以正常工作。但在生产中,此操作会抛出NullPointerException

    2015-01-30 11:51:40,393 [http-apr-8080-exec-48] ERROR StackTrace  - Full Stack Trace:
java.lang.NullPointerException
    at org.xhtmlrenderer.swing.NaiveUserAgent.getBinaryResource(NaiveUserAgent.java:228)
    at org.xhtmlrenderer.pdf.ITextFontResolver.importFontFaces(ITextFontResolver.java:97)
    at org.xhtmlrenderer.pdf.ITextRenderer.setDocument(ITextRenderer.java:178)
    at org.xhtmlrenderer.pdf.ITextRenderer.setDocument(ITextRenderer.java:142)
    at grails.plugin.rendering.pdf.PdfRenderingService.doRender(PdfRenderingService.groovy:36)
    at grails.plugin.rendering.RenderingService.render(RenderingService.groovy:43)
    at grails.plugin.rendering.RenderingService.render(RenderingService.groovy:37)
    at grails.plugin.rendering.RenderingService.render(RenderingService.groovy:35)
    at grails.plugin.rendering.RenderingService.render(RenderingService.groovy:65)
    at RenderingGrailsPlugin$_closure3.doCall(RenderingGrailsPlugin.groovy:59)
    at plano.ensino.PlanoController.toPDF(PlanoController.groovy:33)
    at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:198)
    at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)

我已经尝试过这种模式了:

def render = g.render(template: "/domainClass/pdf",
            model: [domain: domain])

    ITextRenderer renderer = new ITextRenderer()
    ByteArrayOutputStream baos = new ByteArrayOutputStream()
    byte[] b
    renderer.setDocumentFromString(render.toString());
    renderer.layout()
    renderer.createPDF(baos)
    b = baos.toByteArray()
    def filename = "file.pdf"

    response.setContentType("application/pdf")
    response.setHeader("Content-disposition", "attachment; filename=${filename}")
    response.setContentLength(b.length)
    response.getOutputStream().write(b)

我该怎么做才能解决这个问题?

2 个答案:

答案 0 :(得分:2)

当我删除css文件中的自定义字体时,此问题已解决。我将这些字体更改为默认的sans-serif字体,现在一切正常。

答案 1 :(得分:0)

模板文件必须以_(下划线)开头。尝试在文件的开头添加下划线。也尝试一个简单的文件名。以下是我的一个工作实例。

renderPdf(template:“print”,model:[tipInstance:tipInstance,mdeLogo:mdeLogo],filename:“TipLine.pdf”)

您要渲染的模板中是否有图像?尝试取出图像,看看会发生什么。使用渲染插件图像需要额外的努力。

您是否将以下DOCTYPE作为模板的第一行?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">