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();
}
}
In our recent project we needed to convert HTML to Pdf. We first tried PHP based library called tcpdf, but it has lots of limitations.
Finally solution was to use Qt. Here is the code written in PyQT:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://www.google.com"))
#web.show()
printer = QPrinter()
printer.setPageSize(QPrinter.A4)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("file.pdf")
def convertIt():
web.print_(printer)
print "Pdf generated"
QApplication.exit()
QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)
sys.exit(app.exec_())
To convert HTML text we can also use setHtml() instead of load() which takes url of the page you want to convert. But on Windows when we use setHtml() the loadFinished() signal was not emitted( bug?? ) whereas it works on Linux.
My friend’s new mobile charger..

I’m very happy PHP exists. It’s a bright shiny object to keep the stupid people away from more advanced things like Perl. : Randal Schwartz


