All posts by Waldemar Bautista

Easy PDF Generation

Most web applications require some form of PDF generation for reports and other uses. These can already be done by many PDF libraries out there searchable by your favorite search engine. However, sometimes, a report has a certain format that it takes time and effort to create its template either by drawing it manually using a PDF library or creating a HTML/CSS file which will be converted later on.

In one of my projects, I need a report with lots of table cells. Creating a template using either one of the options I mentioned earlier is time consuming for me. I’m sure there are techniques to speed them up that I haven’t looked up yet but below is the one that I have found to be the easiest.

Since I need a lot of table cells, just use a spreadsheet application. It is easy to create a different sizes of rows and columns there. Formatting is also easy. One thing to look out for is the total width of all your cells. Make sure that the width fit in your target paper size.

Then, open the spreadsheet in your web application and fill it with your data. It is easy to put data there because you can specify the cell just by its row and column numbers. Just like PDF libraries, there are spreadsheet libraries out there. Choose the one you like the most.

Now that you have a spreadsheet with all the report data, convert it to PDF using the following command:

$ /usr/bin/libreoffice --headless --convert-to pdf --outdir <output folder> <spreadsheet file>

You now have a generated PDF! Note that you need to install LibreOffice for this. Also, you have to call a command outside of your application. You need to factor these before using this technique.