Today I’m going to start a series on our HTML to PDF API. I’ll be trying to accomplish something really cool – converting a URL to PDF with just a single line of code. And I’m going to try to accomplish that in PHP first, but the next parts of the series are going to be about C#, Java, Python, Ruby, Perl etc.
Right off the bat I can tell you it’s not going to be possible to convert a URL to PDF, do all kinds of error handling, include libraries and what not – with just a single line of code. Mind you – for the HTML to PDF API you will never need any libraries, you don’t already have on your system though.
What we will limit our challenge to, is that we want to call our API with several options and still use as few lines of codes as possible. And hopefully that will just be one. At the beginning of the series we’re jumping in the deep here – cause I really don’t know if I’m going to succeed to do it in one line in each programming language.
The challenge HTTP request
Our challenge HTTP request, that we will want to send for each programming language is going to be the following:
This will call our API with the API key yourapikey, the URL http://www.google.com and turn it into an encrypted PDF with user password htm2pdf.
Coding the conversion in PHP
In our API documentation we used code similar to the following example code to get this done.
$apikey = 'yourapikey';
$url = 'http://www.google.com';
$result = file_get_contents("http://api.htm2pdf.co.uk/urltopdf?apikey=$apikey&url=$url&userpass=$userpass");
This code breaks up the parameters apikey, url and userpass in separate lines and then feeds them to the file_get_contents command. This is actually the one, which calls and executes the HTTP request (aka calling the API). Subsequently we used file_put_contents to put the PDF in a file with the name /tmp/mypdf.pdf.
Now if we wouldn’t break up the parameters in separate lines, we’d already be done. We would get the PDF in one line of code with:
$result = file_get_contents("http://api.htm2pdf.co.uk/urltopdf?apikey=yourapikey&url=http://www.google.com&userpass=htm2pdf");
As a bonus we can even save it to a filename as well in the same statement, if we just pass the file_get_contents statement as a parameter to the file_put_contents statement.
It will become this:
In this post I showed you that PHP allows you to call the API to do the URL to PDF conversion in just a single line of code. I don’t really recommend this, because it will not make your code easily legible, but for testing purposes this is of course AWESOME!
It also shows how easy-to-use our API really is. In the next articles in this series I’ll hope to show you that you can accomplish the same in C#, Java, Ruby, Python, Perl and maybe some other programming languages.