Search code examples
javajasper-reportsitextbookmarksexport-to-pdf

How to open bookmarks automatically in Jasper Report PDF export?


When a PDF is exported from Crystal Reports, the bookmarks panel shows by default when the PDF is opened; however, when using JasperReports, the bookmark panel is not opened by default and has to be opened manually.

How can JasperReports export a PDF that opens with bookmarks shown by default?


Solution

  • AFIK there is no configuration in jasper-report to set view preference (page mode). My only solution would be to post elaborate the pdf with itext (library used to export to pdf, already in classpath)

    Example

    We will export jasper as a PDF to a memory stream (ByteArrayOutputStream) then use itext's PdfStamper to add viewer preferences PageModeUseOutlines1

    //Get the JasperPrint object (exact code to achieve this intentional left out since command depends on application)
    JasperPrint jasperPrint = JasperFillManager.fillReport(...); 
    
    //Export to pdf into a memory stream
    JRPdfExporter exporter = new JRPdfExporter();
    exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
    ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();
    exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(memoryStream));
    SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
    exporter.setConfiguration(configuration);
    exporter.exportReport();
            
    //Use stamper to set viewer prederence 
    PdfReader pdfReader = new PdfReader(new ByteArrayInputStream(memoryStream.toByteArray()));
    PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("my.pdf"));          
    pdfStamper.getWriter().setViewerPreferences(PdfWriter.PageModeUseOutlines);
    pdfStamper.close();
    pdfReader.close();
    

    1. Link is to itext5 api, but note that jasper-reports actually uses a special version of itext 2.1.7 see maven dependence for more information