4

我如何申请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();
4

2 回答 2

7

这可能是一个老问题,但我花了一些时间研究如何压缩 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,如果有人知道更好的选择或更好的方法,请评论这个答案。

于 2016-08-09T19:54:06.130 回答
1

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

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

于 2015-07-07T15:22:49.353 回答