I have an application that allows users to make custom PDFs. On the backend, we use Prawn to add the changes to a given PDF. The code looks something like this:
path_to_existing_pdf = '/path/to/test.pdf'
document = Prawn::Document.new margin: 0, template: path_to_existing_pdf
With a normal PDF (no encryption), this works just fine. However, if the PDF has encryption enabled, Prawn with throw the error Prawn::Errors::TemplateError: Template file is an encrypted PDF, it can't be used as a template
. What I'm looking for is a tool (preferably in ruby) that can take the encrypted PDF, save an unencrypted version, and then use that one for the Prawn template. The code would probably look something like:
path_to_existing_pdf, document = '/Users/[]/Documents/test.pdf', nil
begin
document = Prawn::Document.new margin: 0, template: path_to_existing_pdf
rescue Prawn::Errors::TemplateError
path_to_existing_pdf = [encrypted to unencrypted conversion here]
retry
end
And just to clarify, users upload encrypted PDFs all the time with the intention of being able to modify them, so this question is not how to circumvent the users' security measures; this question is aimed more at providing my users with a good experience when using my app. I want to avoid telling the users to just go save an unencrypted copy of their PDF to then upload to the app.
I know Preview.app can do just such a conversion, so what would be the best way to do such a thing programmatically? Thanks for any suggestions!
In a project I worked on in the past where we needed to modify PDFs uploaded by users, which were in some cases encrypted, we used the program ps2pdfwr
which is part of the ghostscript package to remove the protections from the originals. Despite the name it will accept PDF files as the input.