Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress PDF in JasperReports

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();
like image 840
travega Avatar asked Feb 20 '23 13:02

travega


1 Answers

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.

like image 183
Julio Villane Avatar answered Mar 05 '23 19:03

Julio Villane