Last week we did an article about using HTML to PDF API from the command line. I think it illustrated well how easy the API works, yet how powerful it is.
It also made me realize that Perl is both these things. I think a lot of people nowadays don’t give Perl the credit it deserves and look at Perl as archaic or just plain ‘old’. I think it deserves more credit and definitely more respect. I still feel Perl opened a lot of doors to begin with in the days of old and furthermore – it’s still used succesfully to the day of today and will be in the future!
Therefore – today we’ll be looking at conversion with the HTML to PDF API in Perl.
Basic HTML to PDF API usage
So as we have seen in previous posts and can be seen in the documentation of the API, the API works by sending HTTP requests of the following form:
And in Perl we can send a HTTP request easily, by using either the File::Fetch or the LWP::Simple module. So if we want to send the above HTTP request in Perl we could do the following to get your PDF saved in the /tmp directory:
use File::Fetch; use URI::Escape; my $apikey = 'yourapikey'; my $url = uri_escape ("http://www.google.com"); my $ff = File::Fetch->new(uri => "http://api.htm2pdf.co.uk/urltopdf?apikey=$apikey&url=$url"); my $where = $ff->fetch( to => '/tmp');
So that’s quite easy, isn’t it?
Using other options of the HTML to PDF API in Perl
Just as the basic usage is very easy, adding options (of which there are many – like page size, margins, encryption, watermarking etc.) is also a breeze. You just attach some extra parameters to the API URL you’re sending the HTTP request to!
For example – if you want to create a single page PDF of http://www.digg.com, you want it to be 10 inches wide and you want the PDF to be protected with the password ‘htm2pdf’ then you’d add the following parameters to the API URL:
- width=10 (to indicate the width, also – by not specifying height you will get one long single page PDF)
- unit=in (for the unit of the width)
- userpass=htm2pdf (for the document open password)
Now the example in Perl becomes the following:
use File::Fetch; use URI::Escape; my $apikey = 'yourapikey'; my $url = uri_escape ("http://www.digg.com"); my $width = '10'; my $unit = 'in'; my $pass = 'htm2pdf'; my $ff = File::Fetch->new(uri => "http://api.htm2pdf.co.uk/urltopdf?apikey=$apikey&url=$url&width=$width&unit=$unit&userpass=$pass"); my $where = $ff->fetch( to => '/tmp');
The point I tried to make today is that Perl is still out there and will be for times to come. And that it’s our honour to show that also Perl can easily be used effectively with our API. I hope I succeeded.