Home » Programming » Archive by category "C#"

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.

Ordered a Nexus 7 tablet

Nexus-7-2013I just ordered a Nexus 7 (2013) tablet for a really nice price. I plan on using it for Android development and website testing. Together with my iPad 3 and Android phone this should cover a wide range of test cases. Now to decide if I should go with Xamarin C# or stick with Java…

Since I’m note a big fan of Java I’m leaning towards Xamarin but the yearly subscription costs are a bit steep if you’re not actually generating money out of mobile stuff. Still, with Xamarin it’s easier and maybe cheaper in the sense of time to develop for both Android and iOS since you can write the core of your application in C# and use that on both target platforms.

I’m now a freelance developer

To my surprise I hadn’t even announced here that I have recently started freelancing! As of August the 1st I now operate under the name Kras IT and am available as a freelance developer. Since it’s now the 1st of September this means I’m already in business for a month now which has been exciting. I’ve been with my previous employer for almost 7 years and after a lot of thinking and planning I decided to take the leap!

As a freelance developer you can hire me for all your PHP and Perl work. I mainly do webdevelopment but I do a lot of backend as well. Aside from that I also enjoy configuring Linux servers. I personally think being able to configure and optimize both your app and the server(s) the app is running on can be a great asset, as it gives a lot more insight in the overall workings of your software.

Aside from doing freelance work I also plan on doing product development. I’ve got a few ideas in the pipeline of which one I expect to launch within 5 months. I’m likely to blog about this in the near future as well as about freelancing and running your own business.

For a full list of skills you can take a look at my website at Kras IT. Currently the website is still Dutch only but my LinkedIn and résumé are in English. Do you’ve got any questions or are in need of a freelance developer? Feel free to contact me!

Programming languages I planned on learning in 2011

Earlier this year I posted about which languages I planned on learning in 2011. A few months later I posted about my progress. Now that 2011 almost has come to an end it’s time to review and see if I actually met any of those goals. How exciting.

I had listed 4 programming languages I planned on learning: Lua, C#, Haskell and Java. And with absolute self confidence I can proudly tell you I’ve fully learned none of them! So, what happened?

Lua

I believe I haven’t written a single line of Lua this year at all. Or maybe I did, I can’t even remember. I do know I was experimenting on a BlitzMax based IRC client, which could be scripted by Lua. But this just might’ve been in 2010… In short, the reason I haven’t done any was because I didn’t have any project I wanted to embed Lua in. Perhaps Maximus? Sure, I know I can use Lua standalone, but I think the true beauty of Lua is the easiness of embedding it. So I think I’ll give my IRC client experiment another go in 2012.

C#

Of all the languages to learn I’ve spent most time with C#. Reason for this was because I needed it to do my homework assignments in it as well as several small projects. Heck, I’ve even used XNA! But I can’t say I’ve spent enough time with it to say I actually learned C#. I can read the code just fine, it’s just that I haven’t memorized some of the basic syntax. Overall I’ve made most progress on C#. In general I don’t enjoy C# too much, but LINQ makes it a lot more fun, that’s for sure.

Haskell

I actually did try some Haskell examples from the book Learn You A Haskell For Great Good. But didn’t come much further with either reading the book or trying stuff out. I have however come to use Amanda, which is another functional programming language which has borrowed a lot from Haskell. It’s what we use at university for the discrete math course. Since I’ll also have to do a couple of exams on it I decided to let Haskell wait a little bit longer. The reason for this is that even though the syntax of both languages are very much alike there’re subtle differences in syntax, which could cost me my head at the paper exams. But I do feel Haskell has given me an advantage in picking up Amanda and discrete math.

Java

Oh Java, thy dreadful beast. I’m most glad I haven’t done anything with Java this year! Turns out we’ll only be using it starting the 2nd school year, together with C++. I’ve already used C++ for a short year, so that won’t be too much of a problem. But finding out I don’t enjoy C# too much (yet), makes me fear how awful programming in Java will be :-(. Perhaps I should give Java a chance though before burning it to the ground.

What’s next

So for 2012 I’m still planning on working with these 4 languages, though Java totally depends on my university. I’ll most likely pick up Haskell somewhere at the beginning of the summer. Perhaps earlier. C# will be needed for more school projects. For Lua I’ll be sure to find a project to integrate it into (probably the IRC client). In the meantime of me not using Lua 5.1, version 5.2 already came out. I haven’t checked yet but I hope they don’t differ too much.

I’ve also still got the book Seven Languages In Seven Weeks which I plan on working through. I’m at the final day for Ruby if I remember correctly. So I’ll be touching several different languages briefly as well.

As a final conclusion I’m not too disappointed. For most of the year I was still having issues with my hands (sometimes still have) which has since been getting better and better. All in all 4 languages might’ve been a bit too much, especially if you consider it was only more or less 6 months I was able to spend time on it. Not forgetting school and work eating up a considerable amount of time next to it as well.

Progress on programming languages to learn in 2011

A while ago I posted about Programming languages to learn in 2011. Now that we’re almost halfway into 2011 I though I do a little reflection of what languages I’ve learned so far… None!

Although none isn’t exactly correct, I can’t say I have learned enough of any of the listed languages to program with. So far all I’ve really done is reading the amazing book Learn You a Haskell for Great Good. So far I’m halfway through the book and I actually did some of the examples and am able to figure out what most of the syntax means. But not more than that.

Not exactly what I had in mind but still it’s better than nothing. I’ll be able to catchup soon though as I’m still only working full-time for 6 more weeks. After that I’ll have 2 months off (I’ll still have to do work from home, but will have a lot more free time on my hands) so that should be plenty of time to learn some new stuff!

Since almost 6 months has passed now, why is it that I haven’t done more yet? Well, there’s still the issues I have with my hands, although the last couple of 5 weeks or so this is getting much more better. I’m still trying to get my Vitamin D level up and am also getting Vitamin B12 injections. On top of that I’m still visiting the Acupuncturist every month or so.

In these weeks that I’ve finally been able to get some stuff done I focused on getting the Maximus website up and running and make it feature complete. All required functionality is in there now and it actually already hosts quite a lot of modules. Out of my head over 250. There’s still more work to be done for the final 1.0.0 release but it’s mostly refactoring, writing test cases and the occasional bug fixing.

So no, I haven’t been able to study the listed programming languages, but I have been able to do some more Perl and get Maximus in a state where it’s usable. In the coming months I do plan to focus on Haskell and C# though, as well as refreshing my Math skills. So all in all I’m pleased with my progress so far.