Rails generate password protected PDF file with Prawn

Generating password protected PDF file is required if data being exported is sensitive. In Rails, Prawn gem can be used to generate password protected PDF file.

Sometimes data being exported in PDF files can have sensitive information. For example, Banking, Health care industry generates PDFs which has sensitive information.

Prawn:

Prawn is a widely used PDF generation library in Ruby. The other available libraries for PDF generation with Ruby don’t have capabilities of generating password protected PDF files.

1. Install Prawn

To install gem Prawn, use the command given below.

gem install prawn
Prawn PDF With Rails

If you are planning to use the gem with Rails application, add gem to Gemfile as,

# Gemfile
gem "prawn-rails"

Prawn Rails offers more features to generate PDF with the help of view layer of Ruby on Rails application.

Bundle install in order to install gems listed in Gemfile.

bundle install

##### 2. Create a new PDF

To create a new PDF object with prawn, let’s use Prawn::Document class as given below.

  pdf = Prawn::Document.new

##### 3. Add some data to PDF file

Now that we have an object of Prawn::Document class, We can add some data / text / table / images to this PDF document.

Let’s add some table data to the document that we have.

table = [
    [ 'ID', 'Site Name', 'Site Description', 'Post Title', 'Author'],
    [ 1, 'Ruby in Rails', 'Ruby on Rails development tutorials for beginner and advanced learners.', 'Rails generate password protected PDF file', 'Akshay Mohite' ],
]

Let’s add this table to PDF.

pdf.table table
4. Add password to PDF document

Now, we can encrypt this document by adding a password to it with the help of code given below.

pdf.encrypt_document(
    user_password: "7fPm>um6KcXDTpLoZo3FfPsW",
    owner_password: "7fPm>um6KcXDTpLoZo3FfPsW",
    permissions: {
        print_document: true,
        modify_contents: false,
        copy_contents: false,
        modify_annotations: false
    }
)

Support Options for PDF encryption:

Option Permission
owner_password Password for encrypting PDF file
modify_contents Able to modify contents of PDF file
copy_contents Able to copy text from PDF file
modify_annotations Able to modify annotations from the PDF file
5. Write (Render) the file

Now, we have added data to PDF file and file is encrypted as well, render this file to save to desired location.

pdf.render_file "Password-Protected-PDF-Report.pdf"

This will save PDF in the current directory with name as Password-Protected-PDF-Report.pdf

References