Converting HTML to Pdf with Java and Qt

Yesterday I wrote about Converting HTML to Pdf with Python and Qt. But in PyQT loadFinished() signal was not working when using setHtml(). Tried with QtJambi today and it works on Windows as well.

Here is the code:

import com.trolltech.qt.core.*;
import com.trolltech.qt.gui.*;
import com.trolltech.qt.webkit.*;

class html2pdf extends QWebView
{
	private QPrinter printer = new QPrinter();

	public html2pdf()
	{
		loadFinished.connect(this, "loadDone()");
		setHtml("This is <b>HTML</b>");
	}

	public void loadDone()
	{
		printer.setPageSize(QPrinter.PageSize.A4);
		printer.setOutputFormat(QPrinter.OutputFormat.PdfFormat);
		printer.setOutputFileName("test.pdf");
		print(printer);
		System.out.println("Done");
		QApplication.exit();
	}

	public static void main(String args[])
	{
		QApplication.initialize(args);

		html2pdf h2p = new html2pdf();
		h2p.show();

		QApplication.exec();
	}
}
Advertisements

5 thoughts on “Converting HTML to Pdf with Java and Qt

  1. I use your proposition and thanks a lot for it. It’s really usefull.
    But now I have to generate dynamically a PDF with multiples pages from many html pages . Any Idea please?

  2. @chima: loop through the html pages and pass it to same printer object 🙂

    Basically it should be like this:
    In constructor you will have printer settings

    html2pdf()
    {
    printer.setPageSize(QPrinter.PageSize.A4);
    printer.setOutputFormat(QPrinter.OutputFormat.PdfFormat);
    printer.setOutputFileName(“test.pdf”);
    }

    Then in there will be a method which will loop through html files.

    In loadDone() just print it

    public void loadDone()
    {
    print(printer);
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s