Home » Page 4

Convert HTML to PDF with HTML2PDF Web Service

HTML2PDF Web ServiceRecently I launched my new product HTML2PDF Web Service — a web service for converting HTML to PDF.

In this post I’d like to talk about HTML2PDF Web Service. Why to choose it, how to use it and what technologies were used to create it.

Why Choose HTML2PDF Web Service?

Programmatically generating PDF documents is a painful and time consuming problem that neither makes your developers nor designers happy. With HTML2PDF Web Service you can design your invoices or reports in HTML, style them with CSS and convert the resulting page into a PDF document. Using HTML2PDF Web Service saves your developers and designers time which is better spent making your product better.

Say your web application or mobile app (or any application for that matter) needs to generate invoices or reports in PDF format. Unless you can install special HTML to PDF conversion software you’re probably stuck with some of the libraries available for your language that can programmatically generate PDF documents. To do this you would probably design your document in something like MS Word, LibreOffice Writer or perhaps HTML. After this design has been approved you can start programming your PDF module; setting up coordinates, font sizes etc. And then all of the sudden you notice your library has limited support for doing actual document layouts and presenting tabular data that can span multiple lines. Now you need to write your own routines for splitting text over multiple lines, keep track of coordinates and make sure nothing overlaps. If like me you’ve already been there, it’s quite the nightmare.

So being able to design in HTML, style with CSS (heck, even use a bit of JavaScript) and convert the resulting page to PDF would speed up this process a lot. Am I starting to tickle your interest?

How to use HTML2PDF Web Service

Simply create your soon to be PDF documents in HTML, style them with CSS and if wanted you can use JavaScript as well. The final document is best previewed in a WebKit based browser such as Google Chrome, since that’s the technology HTML2PDF Web Service uses in the background to render the HTML and convert it to PDF.

Here are some examples on how to call the web service. Converting HTML to PDF is easy with the HTML2PDF Web Service. You can pass an URL to the page you want to convert or either send the HTML code with the request.

cURL

$ curl -H "X-API-Key: F8802062-4D31-11E3-8F59-BFD4058B6BFF"
       -H "X-API-Username: MyUsername"
       -d '{"content":"<html><head><title>My page</title></head><body><h1>Hello World!</h1><p>I am an HTML page converted to PDF!</p></body></html>"}'
       https://html2pdfwebservice.com/api/convert > page.pdf

Perl

#!/usr/bin/env perl
use strict;
use warnings;
use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;
my $tx = $ua->post(
    'https://html2pdfwebservice.com/api/convert' => {
        'X-API-Username' => 'MyUsername',
        'X-API-Key'      => 'F8802062-4D31-11E3-8F59-BFD4058B6BFF'
    } => json => {url => 'http://domain.com/invoice.html'}
);
if (my $res = $tx->success) {
    my $pdf_data = $res->body;
}

Ruby

require 'net/https'
require 'uri'

uri           = URI.parse('https://html2pdfwebservice.com/api/convert')
https         = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
# In case the SSL certificate isn't accepted
https.verify_mode = OpenSSL::SSL::VERIFY_NONE

req = Net::HTTP::Post.new(uri.path)
req['X-API-Username'] = 'MyUsername'
req['X-API-Key']      = 'F8802062-4D31-11E3-8F59-BFD4058B6BFF'
req.body              = '{"url": "http://domain.com/invoice.html"}'

res = https.request(req)
if res.code == '200'
    pdf_data = res.body
    # - or write to file -
    # File.open('invoice.pdf', 'w') { |file| file.write(res.body) }
end

PHP

$settings = array(
    'url' => 'http://domain.com/invoice.html',
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($settings));
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'X-API-Username: MyUsername',
    'X-API-Key: F8802062-4D31-11E3-8F59-BFD4058B6BFF'
));

curl_setopt($curl, CURLOPT_URL, 'https://html2pdfwebservice.com/api/convert');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Helps to debug in case of issues
// curl_setopt($curl, CURLOPT_VERBOSE, 1);

// In case the SSL certificate isn't accepted because of outdated certificates
// on your server
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$res = curl_exec($curl);
// Save PDF to disk
file_put_contents('document.pdf', $res);
curl_close($curl);

Technologies used to develop HTML2PDF Web Service

The most interesting part in developing HTML2PDF Web Service was choosing which technology to use for converting HTML to PDF. After doing research on the subject and testing several solutions I eventually went with a WebKit based solution. By using WebKit it’s easier for the end user to preview their document using a WebKit based browser.

The HTML to PDF conversion server was developed using Go. Go is a fun language to program with, does concurrency in a really nice way and can produce a native executable for Linux, OS X, Windows and some other platforms. Thanks to Go the conversion server is fast, snappy and low on memory and CPU usage. Being able to create a binary executable allows me to sell the conversion server as a standalone product as well.

To get access to the web service there’s also a web application which is written in Perl. My favorite web framework of choice has become Mojolicious for quite some time now and thus HTML2PDF Web Service has been written with it. DBIx::Class has been used for database interaction and Validation::Class is used to validate all user inputted data.

Used databases are PostgreSQL and Redis. The former is used to store user accounts, subscriptions and more. The latter is used to keep track of token usage per user.

Sign up now for a free trial

If after reading all this and you’re still reading, please do sign up for a free trial. The trial gives full access to all the features of the web service so if you like it, please consider buying a subscription.

In case of any questions, please do contact me either through the comments on this page or send an e-mail to support at support@html2pdfwebservice.com.

VirtualBox virtual machine not starting because of missing VT-X support

Today I ran into an issue where VirtualBox wouldn’t start my virtual machines anymore because of missing VT-X support. Which was strange as my CPU (Intel i7) does support this and it did work just a day ago. After some searching and trying the latest version of VirtualBox it turns out that Microsoft’s Hyper-V (Hyper Visor) was preventing VirtualBox from using this technology. Disabling PAE/NX would let me boot the virtual machine again, but without the CPU acceleration.

Disable Hyper-VTo disable Hyper-V in Windows 8 do the following:

  1. Press Windows key + X
  2. Click Programs and Features
  3. Click Turn Windows features on or off
  4. Expand Hyper-V
  5. Uncheck it
  6. Click OK

Now reboot your machine and try booting a virtual machine using VT-X.

Using rsnapshot for daily PostgreSQL backups

Having done backups for MySQL using rsnapshot before I recently had to do the same thing for PostgreSQL. Turns out PostgreSQL has similar tools to do this and it’s actually quite easy to set it up.

First, assuming rsnapshot will run under the root user you’ll need to create a .pgpass file at /root/.pgpass that will hold the credentials that are required for setting up a connection with your database. The expected format is host:port:database:user:password, so for example:

localhost:*:mydbname:myusername:mypassword

With that in place create a shell script that will use this file and run the pg_dump program. Put it some place you can remember, e.g. /usr/local/bin/postgresql-backup.sh:

#!/bin/bash
export PGPASS=/root/.pgpass
pg_dump -w -h localhost -U myusername mydbname > postgresql-dump.sql
gzip postgresql-dump.sql

Again, just as with the using rsnapshot for daily MySQL backups article you need to configure rsnapshot.

Next is setting up /etc/rsnapshot.conf which is easy as well. At the end of this file you’ll find all the instructions of which directories to backup. Enter the next line. Do note that rsnapshot.conf uses a tab to separate values.

backup_script   /usr/local/bin/postgresql-backup.sh  postgresql/

To enable daily backups uncomment the next line:

#interval       hourly  6
interval        daily   7
#interval       weekly  4
#interval       monthly 3

To make rsnapshot run every day update /etc/cron.d/rsnapshot:

# 0 */4         * * *           root    /usr/bin/rsnapshot hourly
  30 3          * * *           root    /usr/bin/rsnapshot daily
# 0  3          * * 1           root    /usr/bin/rsnapshot weekly
# 30 2          1 * *           root    /usr/bin/rsnapshot monthly

Finally, try running rsnapshot. After it has run check your backup directory, which on Ubuntu 12.04 defaults to /.snapshots/. Be sure to mount /.snapshots/ on a separate drive. Because what use is it if your data drive contains your backup and decides to commit suicide?

$ sudo rsnapshot daily

Your PostgreSQL backup file should now be located at /.snapshots/daily.0/postgresql/postgresql-dump.sql. You can restore this file with the psql commandline utility.

Which 2013 tablet is the best for gaming?

Just in the nick of time Apple has launched the new iPad mini 2 with retina display (to give it its full official name) to enable us to declare it the best 2013 tablet for gaming. Just a little time ago we declared that the award should go to the Nexus 7, but at that time it seemed as if the iPad Mini 2 wouldn’t appear until sometime in the New Year. The Nexus is a great tablet for gaming, and in terms of specifications there is little to choose between it and the new iPad Mini 2, however the build of the iPad Mini 2 is so much better than that of the Nexus 7 that it wins hands down. Naturally the iPad mini 2 with retina display is somewhat more expensive, but then you don’t get a sleek machined aluminium case for peanuts. With a price tag of £320 for the entry level model the iPad Mini 2 is no toy, but you never know, with a little luck you might find one in your Christmas stocking.

Although the new iPad Mini 2 might be considered to be overkill for gamers whose main interest in games is Angry Birds or who enjoy playing blackjack and poker at an online casino such as Lucky Nugget’s Australian casino for example. Admittedly those kinds of games are not as demanding as some of the high end console type games which are now available for iOS and Android operating systems. The problem is though that once you pick up and use the new iPad mini 2 with retina display it is very difficult to put it down again. You can get by with less, but do you really want to? You might need to pay a little more, but then you are paying for quality.

The new iPad Mini 2 marks a new beginning for hand held tablet gaming. It certainly deserves the awards as the best 2013 gaming tablet and surpasses its main rival, the Nexus 7, but a large margin in terms of build quality and ergonomics.

Getting close to launching HTML2PDF Web Service!

For the last couple of months I’ve been busy developing HTML2PDF Web Service. Due to some setbacks I had to postpone its launch. The way it’s looking now I’ll be ready to launch by the end of the month.

So what had to change?

  • I had to switch from Payment Service Provider, which is done now. Instead of only credit cards I’m now supporting PayPal, iDEAL, Paysafe Card and Mister Cash. Credit Card support should come back later. Instead of recurring subscriptions you can now buy up to 1 year of access in advance. This is due to not being able to support recurring subscriptions anymore because of the PSP switch.
  • The website is now multilingual: currently supporting English and Dutch. Both have their own domain names. I’ve done this to get a better position in the Dutch market.

All that’s left now is changing the way token usage is being calculated and it should be all set to go. The HTML2PDF Web Service is still in beta, so feel free to try it out. Once the web service is out of beta I’ll do another post here with a follow up on used technology (Perl, Go and more!).