How to compress PDF in JasperReports

2019-06-27 12:47发布

问题:

How do I apply the IS_COMPRESSED = true property to a Jasper PDF report?

This is what I have but when I create a PDF report it is the same size as it's clone without compression enabled:

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();

回答1:

This may be an old question, but I spent some time looking how to compress PDF files and I want to share the answer...

The setParameter method alternative is deprecated, and in order to do the same, the documentation indicates that you should use an implementation of PdfExporterConfiguration. A simple one called SimplePdfExporterConfiguration is provided and should be used like this:

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

A complete example of a PDF generation using an XML as source:

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();

I managed to compress files from 4 mb to 1.9 mb, if someone knows a better alternative or better way please comment this answer.



回答2:

I found that the size of the PDF file output by my report did not change, until the compression property (net.sf.jasperreports.export.pdf.compressed) was embedded in each subreport and set to 'true'.

After that, the size of the PDF produced by the report shrank from 4MB to just over 1MB. Not bad.