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 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.
Prawn PDF With Rails
If you are planning to use the gem with Rails application, add gem to Gemfile as,
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.
##### 2. Create a new PDF
To create a new PDF object with prawn, let’s use Prawn::Document class as given below.
##### 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.
Let’s add this table to PDF.
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.
Support Options for PDF encryption:
|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.
This will save PDF in the current directory with name as Password-Protected-PDF-Report.pdf