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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With