Some devices can only process specific versions of PDFs. This post shows how to generate specific PDF versions in Java and JasperReports. If our devices are considerably old, chances are they can only process older versions of PDF documents.
Java, JasperReports, and Other Requirements
We used the following items for this post and most of them are already old in 2021. Using specific requirements could help us port the solution to newer platforms or tools.
- Windows 7 Professional SP1
- Eclipse – Kepler Release
- Java 1.7 (1.7.0_67 – Windows x86)
- NOTE: Set source target and level is Java 1.6
- We have not tested it yet with source target and level 1.7
- JasperReport 3.1.4
Java Codes To Generate Specific PDF Version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | public static void generatePDF(String jasperPath, Map parameters, String outFile, Connection conn) throws Exception { JasperPrint jasperPrint = new JasperPrint(); jasperPrint = JasperFillManager.fillReport(jasperPath, parameters, conn); FileOutputStream fos = new FileOutputStream(outFile, true); BufferedOutputStream bos = new BufferedOutputStream(fos); String pdfVersion = (String)parameters.get("pdf_version"); if(pdfVersion != null) { pdfVersion = pdfVersion.trim(); JRPdfExporter exporter = new JRPdfExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, bos); if(pdfVersion.equals(JRPdfExporterParameter.PDF_VERSION_1_2.toString())) { exporter.setParameter(JRPdfExporterParameter.PDF_VERSION,JRPdfExporterParameter.PDF_VERSION_1_2); } else if(pdfVersion.equals(JRPdfExporterParameter.PDF_VERSION_1_3.toString())) { exporter.setParameter(JRPdfExporterParameter.PDF_VERSION,JRPdfExporterParameter.PDF_VERSION_1_3); } else if(pdfVersion.equals(JRPdfExporterParameter.PDF_VERSION_1_4.toString())) { exporter.setParameter(JRPdfExporterParameter.PDF_VERSION,JRPdfExporterParameter.PDF_VERSION_1_4); } else if(pdfVersion.equals(JRPdfExporterParameter.PDF_VERSION_1_5.toString())) { exporter.setParameter(JRPdfExporterParameter.PDF_VERSION,JRPdfExporterParameter.PDF_VERSION_1_5); } else if(pdfVersion.equals(JRPdfExporterParameter.PDF_VERSION_1_6.toString())) { exporter.setParameter(JRPdfExporterParameter.PDF_VERSION,JRPdfExporterParameter.PDF_VERSION_1_6); } else { exporter.setParameter(JRPdfExporterParameter.PDF_VERSION,JRPdfExporterParameter.PDF_VERSION_1_4); } exporter.exportReport(); } else { //If pdf_version not in (2,3,4,5,6),by default 1.4 version will be created. JasperExportManager.exportReportToPdfStream(jasperPrint, bos); } bos.flush(); bos.close(); fos.flush(); fos.close(); bos = null; fos = null; } |