As the importance of security grows, a huge number of products and businesses keep locks on their data. The first line of defense against data breaches could be to keep the PDFs password protected — especially in sensitive areas such as Healthcare and Fintech.
Statistics by Varonis showcase why every enterprise needs to have password-protected PDFs:
Looking at the statistics above, it’s time to protect your PDFs with passwords irrespective of your industries when dealing with sensitive data using PDFs.
Having worked on such products — in this article, I will show how you can generate password-protected PDFs in Rails using the wicked PDF gem.
Before we begin, understand that PDFs are generated in essentially four simple steps:
This convoluted process is needed because of wicked pdf, which doesn’t provide the functionality to add a password while creating the PDF and the prawn gem doesn’t accept HTML to create password-protected PDFs :)
And, as you might have guessed — wicked PDF uses wkhtmltopdf, an open-source (LGPLv3) command-line tool to render HTML into PDF and various image formats using the Qt WebKit rendering engine. These run entirely “headless” and do not require a display or display service.
Before we begin, you will need to install the following gems in your Ruby on Rails application:
In other words, rather than dealing with a PDF generation DSL of some sort, you simply write an HTML view as you would normally, then let Wicked PDF take care of the hard stuff.
Wicked PDF provides a PDF file to the users converted from HTML.
Above we have generated pdf from string using WickedPdf and store it in a temp file. It’s easy a pie!
Now we move to how we can make it password protected :)
ImageMagick helps in generating images from the PDF file. You can learn how to install ImageMagick on your device from the below link.
For a Heroku server, use ImageMagick build pack.
If image generation gives unauthorized error then change below in the /etc/ImageMagick-6/policy.xml file
<policy domain=”coder” rights=”read|write” pattern=”PS” />
<policy domain=”coder” rights=”read|write” pattern=”PDF” />
As mentioned before, we generate the images for the prawn gem as it doesn’t handle HTML to PDF conversion like wicked PDF does!
Prawn is a Ruby on Rails (RoR) library that generates PDFs for various functionalities.
You can store the encrypted file in the database with a password value — and Voila! you’re done.
I hope this article will help you to generate password protected PDF in Ruby On Rails. I hope someday wicked pdf allows us to generate password-protected PDFs so that someday my article would become irrelevant! :)
I’m Manthan —a Software Developer at Solutelabs. An ordinary boy with extraordinary dreams. I am enthusiastic about writing clean, efficient and accessible code in a functional framework.
Apart from work, I like to play cricket, watch movies and spend time with family.