JFreeChart没有显示生成的Spring MVC和iText PDF [英] JFreeChart not showing in generated Spring MVC and iText PDF

查看:147
本文介绍了JFreeChart没有显示生成的Spring MVC和iText PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前问过 在另一个PDF文件的可用空间附加PDF 我已经成功地将本地iText和JFreeChart合并在一个页面上制作了PDF。

I asked before the question "Append PDF at the available space of another PDF file" and I have successfully made a PDF with both native iText and JFreeChart combined in one page.

我使用教程 Spring Web MVC with PDF查看示例(使用iText 5.x)

I merged this setup to my Spring MVC application using the tutorial "Spring Web MVC with PDF View Example (using iText 5.x)".

我理解使用Spring的 AbstractView 反过来实现为

I understand that using Spring's AbstractView and in turn implemented as

@Override
protected void buildPdfDocument(Map<String, Object> map, Document document,
        PdfWriter pdfWriter, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // do iText and JFreeCharts

}

和JFreeCh art实例需要将现有的PDF文件插入其中,如 创建带有嵌入式JFreeChart的iText pdf

and that a JFreeChart instance needs an existing PDF file to be inserted into it as demonstrated in "Creating an iText pdf with embedded JFreeChart":

// get the direct pdf content
PdfContentByte dc = docWriter.getDirectContent();

// get a pdf template from the direct content
PdfTemplate tp = dc.createTemplate(width, height);

// create an AWT renderer from the pdf template
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper() );
Rectangle2D r2D = new Rectangle2D.Double(0,0, width,height);
chart.draw(g2,r2D,null);
g2.dispose();

// add the rendered pdf template to the direct content
// you will have to play around with this because the chart is absolutely positioned.
// 38 is just a typical left margin
// docWriter.getVerticalPosition(true) will approximate the position that the content above the chart ended
dc.addTemplate(tp, 38, docWriter.getVerticalPosition(true)-height);

我现在的问题是每当我调用扩展 AbstractView的方法(请参阅第二个链接),在插入JFreeChart之前显示PDF而不是生成图表的。我没有遇到任何错误,但我想知道是否有这种行为的解决方案。

My problem now is that whenever I call the method that extends AbstractView (refer to the second link), it shows the PDF before inserting the JFreeChart and not the one with the generated chart. I haven't encountered any errors for this one but I would like to know if there is a solution for this behavior.

我只是希望用户看到PDF JFreeChart,就像Spring MVC中的普通PDF实现一样。

I just want the user to see the PDF with JFreeChart, just like a normal PDF implementation in Spring MVC.

正如您所看到的,我只是按照上面的教程并将它们组合在一起。他们在一个单独的项目中完美地工作但是当我与Spring合并时,JFreeChart没有显示,特别是显示了错误的PDF文件。

As you can see I just followed the tutorials above and combined them. They worked perfectly in a separate project but when I merged with Spring, the JFreeChart is not showing, specifically the wrong PDF file is shown.

我知道我可以用JFreeChart调用生成的PDF并通过放置正确文件的链接来稍微拦截查看但是我对此设置保持希望,因为这将是一种方便的方式来使用这三个技术完全没有服务器中的文件I / O的麻烦(我遇到了麻烦)。

I know that I can just call the generated PDF with JFreeChart and somewhat intercept the viewing by putting a link to the correct file but I am keeping my hopes up with this setup because it would be a convenient way to use the three technologies altogether without the hassle of file I/O in server (which I have trouble in).

下面是一个片段来自 AbstractITextPdfView example-using-itext-5xrel =nofollow noreferrer> Spring Web MVC with PDF View Example(使用iText 5.x) 我使用的。

Below is a snippet of the class AbstractITextPdfView from "Spring Web MVC with PDF View Example (using iText 5.x)" that I use.

有人可以告诉我如何将PDF文件打开到带有图表的文件,即在 buildPdfDocument()

Can someone tell me how to direct the PDF file being opened to the one with the chart ie inside the buildPdfDocument()?

@Override
protected void renderMergedOutputModel(Map<String, Object> model,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    // IE workaround: write into byte array first.
    ByteArrayOutputStream baos = createTemporaryOutputStream();

    // Apply preferences and build metadata.
    Document document = newDocument();
    PdfWriter writer = newWriter(document, baos);
    prepareWriter(model, writer, request);
    buildPdfMetadata(model, document, request);

    // Build PDF document.
    document.open();
    buildPdfDocument(model, document, writer, request, response);
    document.close();

    // Flush to HTTP response.
    writeToResponse(response, baos);
}






更新



我通过在 JFreeChart 之后保存到一个文件中截获 ByteArrayOutputStream 将本身附加到 iText PDF。


Update

I intercepted the ByteArrayOutputStream by saving in into a file after JFreeChart "attaches" itself to the iText PDF.

@Override
protected void renderMergedOutputModel(Map<String, Object> model,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    // IE workaround: write into byte array first.
    ByteArrayOutputStream baos = createTemporaryOutputStream();

    // Apply preferences and build metadata.
    Document document = newDocument();
    PdfWriter pdfWriter = newWriter(document, baos);
    prepareWriter(model, pdfWriter, request);
    buildPdfMetadata(model, document, request);

    // Build PDF document.
    document.open();
    buildPdfDocument(model, document, pdfWriter, request, response);
    document.close();

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(new File("D:/MUST-HAVE-CHART.pdf"));
        baos.writeTo(fos);
    } catch (IOException ioe) {
        // Handle exception here
        ioe.printStackTrace();
    } finally {
        fos.close();
    }
    System.out.println(baos.toString());

    // Flush to HTTP response.
    writeToResponse(response, baos);
}

发生的事情是 MUST-HAVE-CHART。 PDF 没有图表,与创建后的Spring MVC提供的图表相同。然而,带有图表的那个保存在其他地方,如代码所示:

What happened is that MUST-HAVE-CHART.PDF does not have the chart, same as the one provided by Spring MVC after creation. The one with the chart however is saved somewhere else, as seen in the code:

@Override
protected void buildPdfDocument(Map<String, Object> map, Document document,
        PdfWriter pdfWriter, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    logger.info("Start of PDF creation");

    Domain domain = (Domain) map.get("domain");

    ServletContext servletContext = request.getSession()
            .getServletContext();
    File servletTempDir = (File) servletContext
            .getAttribute("javax.servlet.context.tempdir");

    if (servletTempDir == null)
        throw new IllegalStateException(
                "Container does not provide a temp dir");

    File targetFile = new File(servletTempDir, NAME_FILE);

    pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(
            targetFile));

    logger.info("PDF file path: " + targetFile.getAbsolutePath().toString());

    document.open();

    PdfBuilder.assemble(document, pdfWriter, domain);

    document.close();
    pdfWriter.close();

    logger.info("End of PDF creation");

    map.put("file", targetFile.getAbsolutePath().toString());
}

正确的保存在 javax.servlet中。 context.tempdir C:/tomcat/work/Catalina/localhost/my_spring_app/pdf_file.pdf

推荐答案

我遇到了同样的问题。
我使用以下代码解决了它,现在文件正在下载而不是渲染新的pfd-view页面(我更喜欢这个)。

I had the same problem. I resolved it using the following code, and the file is now downloading instead of rendering a new pfd-view page (I prefer this).

protected final void renderMergedOutputModel(Map<String, Object> model, 
           HttpServletRequest request, HttpServletResponse response) throws Exception {

    // IE workaround: write into byte array first.
    ByteArrayOutputStream baos = createTemporaryOutputStream();

    // Apply preferences and build metadata.
    Document document = newDocument();
    PdfWriter writer = newWriter(document, baos);
    prepareWriter(model, writer, request);
    buildPdfMetadata(model, document, request);

    // Build PDF document.
    document.open();
    buildPdfDocument(model, document, writer, request, response);
    document.close();

    //Custom code start 
    String filestorePath = "/var/www/xxx/xxxxx/";
    String downloadfileNm = "DeliveryNote.pdf";
    String filePath = filestorePath+downloadfileNm;
    URL url = new URL("file:"+filePath);
    File file = new File(url.toURI());
    if (file.exists()) {
        response.setContentLength(new Long(file.length()).intValue());
        response.setHeader("Content-Disposition", "attachment; filename="+downloadfileNm);
        FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());      
    }
    //Custom code end

    // Flush to HTTP response.
    //writeToResponse(response, baos);

}

这篇关于JFreeChart没有显示生成的Spring MVC和iText PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆