In one of our Rails application, we needed to generate password protected PDFs. We used wicked_pdf (an awesome gem that generates PDFs from HTML template) to generate PDFs but it doesn't provide feature to secure it.
While searching for solution to secure PDFs we came across PDFtk (PDF toolkit). It is a cross-platform tool for manipulating PDF documents. It has feature to add password to PDF document using "user password" as well as "master password" (owner password) which is great.
Installing PDFtk
You need to install "PDFtk Server" which is a command-line tool for working with PDFs. More info & download instructions are nicely described here
Working with PDFtk
Usage of PDFtk Server is described here. Since we want to add password we need to run following statement on terminal.
pdftk <input PDF path> output <output PDF path> owner_pw <master password> user_pw <user password>
Example - pdftk test.pdf output test_password.pdf owner_pw master user_pw user
test.pdfis the input PDF that needs to be securedtest_password.pdfis the name of secured PDF to be generatedmasteris the master password of the PDF (optional)useris the user password which will be shared to end user

Note - owner_pw is optional.
Make it work with Rails
Above command should be ran on terminal. Now we need to make it run with Rails.
Ruby comes with a module Open3. We can use its popen3 method to run our PDFtk command-line statement.
Open3.popen3("<command>") do |_stdin, _stdout, stderr|
// something to do in case of error (stderr)
end
Hope this helps.