Christian HagerSoftware Engineer // Technical Director // Photographer

Encrypting and restricting PDF-Reports build with JasperReports

I recently had the Task to encrypt and restrict a PDF-Report created with JasperReports. Since it took me a while to find the approriate current syntax (most blogs still show the deprecated old configuration) I thought I share my solution here. To encrypt our PDF-Report we have to create a SimplePdfExporterConfiguration as shown in the example below. Using this configuration object we can encrypt the created PDF and set the features we require. We have the possibility to set owner and/or user passwords and allow for example printing or copying from the PDF using setPermissions . All possible permissions can be found here.

try
{
  final ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try
  {
    final JRPdfExporter exporter = new JRPdfExporter();
    exporter.setExporterInput( new SimpleExporterInput( jasperPrint ) );
    exporter.setExporterOutput( new SimpleOutputStreamExporterOutput( baos ) );
    SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
    configuration.setOwnerPassword( "ownerpass" );
    configuration.setUserPassword( "userpass" );
    configuration.setEncrypted( true );
    configuration.set128BitKey(true);
    configuration.setPermissions(PdfWriter.ALLOW_COPY);
    exporter.setConfiguration( configuration );
    exporter.exportReport();
  }
  catch (final JRException ex)
  {
    throw new RuntimeException( ex );
  }
  finally
  {
    baos.close();
  }
  return baos.toByteArray();
}
catch (final IOException ex)
{
  throw new RuntimeException( ex );
}

Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *