Important: Please read the Qt Code of Conduct -

Generating a PDF file from an HTML document

  • Hi,
    we are currently trying to generate a PDF file from an HTML document. For this, we are using the following code:
    QPrinter printer(QPrinter::PrinterResolution);
    printer.setPageMargins(0.,0.,0.,0., QPrinter::Millimeter);

    printer.setOutputFileName(m_projectPath + "/" + m_outFilename + ".pdf");
    m_page->mainFrame()->print(&printer); // m_page is a QWebPage

    The QWebPage m_page is created from an HTML template document (written by hand) containing CSS rules. As we need that the document be divided in 4 pages this template is of the form:
    <!DOCTYPE html>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <meta name="description" content="test de presence d'une description">
    <!-- ============================================== css style ============================================= -->
    <style type="text/css">
    font-family: Calibri;
    font-size: 12pt;
    min-width: 21cm;
    max-width: 21cm;
    margin:0cm 0cm;
    position: relative;
    <!-- ============================================== head / body ============================================== -->
    <div class="page">
    Stuff for the first page...

    <!-- =============== page 2 =============- -->
    <div class="page">
    Stuff for the second page...

    .. and so on for the two other pages...

    As we are using Qt 4.8.4 we cannot put "page break" between the pages (as Qt does not manage them as found as bug in numerous posts on Internet). It is why we are specifying a fixed height for the "page div". And this part is very strange. On my computer (under Windows 8.1) I must specify an height of 36.2cm to be able to have the right printing on a A4 page (i.e. a normal height of 29.7cm). On another computer (under Windows 7), I must specify an height of 30.6cm.

    Does somebody has an idea of the origin of the problem, and the way to solve it?


Log in to reply