Rails : How to preview Office files ?
We use to work with CSV or PDF files when we talk about web apps. CSV are easy to use and edit after exportation (we can also easily create them), PDF are easy to read and and pretty much a standard. But when we have to deal with `.docx`, `.xslx` or similar formats, things get complicated.
Preview a file
In your app, you have certainly used a preview for images or PDFs files. But how will you do in case of an emails app that must show preview of all attachments or another DMS app that must preview files with exotic extensions (docx, pptx, xslx, odt, ods, odp etc.) ?
Convert them to PDF and you are done !
Libre office to the rescue
To get this tool, just install libreoffice on your server using :
apt-get install libreoffice -qq
A little look to the doc and you can see two options we will use :
--convert-to
: allow us to convert a file from our extension to pdf
--headless
: it ignore GUI environment
libreoffice --headless --convert-to pdf my_file.docx
Rails : there is a gem for that
In a rails app, just add a gem on your Gemfile :
# Gemfile
gem 'libreconv'
# In your ruby file module or class
Libreconv.convert("#{Rails.root}/public/files/my_file.docx", "#{Rails.root}/public/files/my_file.pdf")
Bundle install, and now you can make a preview of your file using the PDF version on your server. Note that libreoffice’s tool don’t convert only in PDF but can convert a file from extension that it can open and read to a file with extension that he can write. PDF won’t disappoint you ;)
Originally published at Dev.to.