2012-05-09 43 views
3

如何將IS_COMPRESSED = true屬性應用於Jasper PDF報告?如何在JasperReports中壓縮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(); 
+0

我剛剛檢查了這段代碼:'jrPdfExporter.setParameter(JRPdfExporterParameter.IS_COMPRESSED,Boolean.TRUE);'它工作正常。我正在使用JR 4.1.2。 –

+0

嗯有趣。我沒有看到我的PDF文件的大小有什麼不同......默認情況下Jasper開箱即可將它設置爲true嗎? – travega

+0

文檔說默認是* false * –

回答

0

我發現PDF文件輸出的通過我的報告的大小沒有直到壓縮屬性(net.sf.jasperreports.export.pdf.compressed)嵌入到每個子報表中並設置爲「true」。

之後,報告生成的PDF大小從4MB縮小到略大於1MB。不錯。

+0

你在哪裏嵌入這個屬性? – Gustavo

2

這可能是一個老問題,但我花了一些時間尋找如何壓縮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,如果有人知道更好的選擇或更好的方式,請評論這個答案。