【问题标题】:How to compress PDF in JasperReports如何在 JasperReports 中压缩 PDF
【发布时间】:2012-05-09 04:08:07
【问题描述】:

如何将IS_COMPRESSED = true 属性应用于 Jasper PDF 报告?

这是我所拥有的,但是当我创建 PDF 报告时,它的大小与未启用压缩的克隆相同:

File pdfFile = new File (pdfDirectory.getAbsolutePath() + File.separator +  reportName + ".pdf");
File jrPrintFile = new File(jrprintFileLocation.getAbsolutePath() + File.separator + templateName + ".jrprint");

JasperPrint jasperPrint = (JasperPrint)JRLoader.loadObject(jrPrintFile);

JRPdfExporter jrPdfExporter = new JRPdfExporter();

jrPdfExporter.setParameter(JRPdfExporterParameter.IS_COMPRESSED, true);
jrPdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
jrPdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, pdfFile.getAbsolutePath());

jrPdfExporter.exportReport();

【问题讨论】:

  • 我刚刚检查了这段代码:jrPdfExporter.setParameter(JRPdfExporterParameter.IS_COMPRESSED, Boolean.TRUE);,它工作正常。我正在使用 JR 4.1.2。
  • 嗯,很有趣。我看不到我的 PDF 大小有任何差异... Jasper 开箱即用是否已将其默认设置为 true?
  • 文档说默认是 false

标签: pdf properties compression jasper-reports


【解决方案1】:

这可能是一个老问题,但我花了一些时间研究如何压缩 PDF 文件,我想分享答案...

setParameter 方法替代方案已被弃用,为了做到这一点,文档表明您应该使用PdfExporterConfiguration 的实现。提供了一个名为SimplePdfExporterConfiguration 的简单函数,应该像这样使用:

SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
configuration.setCompressed(true);

使用 XML 作为源生成 PDF 的完整示例:

Document document = JRXmlUtils.parse(JRLoader.getLocationInputStream(PATH_XML));

//report parameters
Map params = new HashMap();
//document as a parameter
params.put(JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, document);
//other parameters needed for the report generation
params.put("parameterName", parameterValue);

JasperPrint jasperPrint = JasperFillManager.fillReport(PATH_JASPER, params);

JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(PATH_PDF));

//configuration
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
configuration.setCompressed(true);

//set the configuration
exporter.setConfiguration(configuration);
//finally exporting the PDF
exporter.exportReport();

我设法将文件从 4 mb 压缩到 1.9 mb,如果有人知道更好的替代方案或更好的方法,请评论这个答案。

【讨论】:

    【解决方案2】:

    我发现我的报告输出的 PDF 文件的大小没有改变,直到压缩属性 (net.sf.jasperreports.export.pdf.compressed) 嵌入到每个子报告中并设置为“true”。

    此后,报告生成的 PDF 的大小从 4MB 缩小到刚刚超过 1MB。还不错。

    【讨论】:

    • 你在哪里嵌入这个属性?
    • 如果你打开报告的JRXML文件,靠近顶部,你会发现有很多XML节点用来设置各种属性。只需添加一个新节点来设置压缩属性,如下所示:
    猜你喜欢
    • 1970-01-01
    • 2014-12-20
    • 2017-09-29
    • 2018-02-14
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 2016-10-07
    • 2010-12-19
    相关资源
    最近更新 更多