问题
In my app to learn RoR, I want to see how to handle attachments. Got paperclip to work and want to get document properties. So, how can I get document properties (PDF info) from pdf files (attached using Paperclip)?
One way is to use command line, yet how to get it the file (here @annotation.file
- or for other object @document.file
)? Actually, I would need to download the file to a temp folder to do this and do a file delete to clean up. How can I get the details without download?
So controller to look like this:
def pdf
@annotation = Annotation.find(params[:id])
render layout: false
command = 'pdfinfo @annotation.file'
no_of_pages = command.split("\n")[-7].split(":").last.strip
end
It throws an error:
undefined method `split' for nil:NilClass
I get it to my annotation view using:
<%= @no_of_pages %>
Meanwhile I looked at the gem "[pdfinfo][1]
" as an alternative, yet how to use this?
回答1:
An alternative to using a gem
, you can also fetch the details of any pdf
using linux's in-built commands. Just write the below ruby code for executing and you will get all the details. For ex:
For executing a linux
command in your ruby code, write that command like :
def pdf
@annotation = Annotation.find(params[:id])
command = `pdfinfo @annotation.file`
@no_of_pages = command.split("\n")[-7].split(":").last.strip
render layout: false
end
you will get all the details like no. of pages, file_size etc in your command
variable.
You can easily fetch the respective details you want.
I hope this helped !!
UPDATE
Note : give a proper path for your pdf file, the exact directory where it is placed. like in my case :
command = `pdfinfo /home/hbiyawarwala/Documents/books/Rails-Angular-Postgres-and-Bootstrap.pdf`
Second thing is, use variable @no_of_pages
directly in your view like
<%= @no_of_pages %>
回答2:
Easy solutionL use the PDFINFO gem; works very well
来源:https://stackoverflow.com/questions/39484844/pdf-attached-with-paperclip-get-document-properties-like-page-count