使用FlyingSaucer / iTExt5生成的Pdf为空白

时间:2018-11-13 00:38:06

标签: pdf itext pdf-generation flying-saucer

我正在尝试从html字符串生成PDF,并得到响应,但是该文档未在PDF查看器中显示。我似乎好像丢失了一些东西,响应是损坏的PDF。如果能得到任何建议,将不胜感激。

在我的pom.xml中包含了以下内容

    <!-- dependencies for saving as PDF -->
<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>itextpdf</artifactId>
  <version>5.5.11</version>
</dependency>
<dependency>
  <groupId>org.xhtmlrenderer</groupId>
  <artifactId>flying-saucer-core</artifactId>
  <version>9.1.16</version>
</dependency>
<dependency>
  <groupId>org.xhtmlrenderer</groupId>
  <artifactId>flying-saucer-pdf-itext5</artifactId>
  <version>9.1.6</version>
</dependency>

我的端点是一个控制器,代码如下:

    @POST
@Produces({"application/pdf"})
@Path("/renderPDF")
public void renderPDF(@Context HttpServletRequest request, @Context HttpServletResponse response) throws WebAppException {
    try {
        String  = "<html><body>some content</body></html>";
        RenderPDF.createPDF(response, sb);
    }
    catch (Exception e) {
        LOGGER.error("renderPDF", e);
    }
}

createPDF定义如下:

public class RenderPDF {
public static void createPDF(HttpServletResponse response, String html)
        throws IOException, DocumentException, ParserConfigurationException, SAXException {
    try {
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(html);
        renderer.layout();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        renderer.createPDF(baos);

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control",
                "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength
        response.setContentLength(baos.size());

        OutputStream os = response.getOutputStream();
        baos.writeTo(os);
        os.flush();
        os.close();
    } catch(Exception e) {

    }
}

1 个答案:

答案 0 :(得分:0)

问题出在我的有角度的http拦截器中;响应类型需要设置为arrayBuffer。