PDF attached with Paperclip - get document properties (like page count)

六月ゝ 毕业季﹏ 提交于 2019-12-08 06:09:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!