Ayan Banerjee
Ayan Banerjee

Reputation: 161

QT html and CSS to pdf file

I am using QTextDocument and using setHtml to add html. Then I used QPrinter to print in A4 pdf format QPrinter::PdfFormat but the printed pdf did not take the css style sheets. I also tried QTextDocument::setDefaultHtml and setResource.

The code is as follows. How to get the CSS style in pdf format. I use ubuntu and qmake for compiling.

const int highQualityDPI = 300;
QDir::setCurrent(QCoreApplication::applicationDirPath());

QFile  htmlFile ("myhtml.html");
if (!htmlFile.open(QIODevice::ReadOnly | QIODevice::Text)){
    return -1;
}

QString htmlContent;
QTextStream in(&htmlFile);
htmlContent=in.readAll();

QFile  cssFile ("style.css");
if (!cssFile.open(QIODevice::ReadOnly | QIODevice::Text)){
    return -1;
}
QString cssContent;
QTextStream cssIn(&cssFile);
cssContent = cssIn.readAll();

QTextDocument *document = new QTextDocument();
document->addResource( QTextDocument::StyleSheetResource, QUrl( "style.css" ), cssContent );
document->setHtml( htmlContent ); 

QPrinter printer(QPrinter::HighResolution);
printer.setPageSize(QPrinter::A4);
printer.setOutputFormat(QPrinter::PdfFormat);

printer.setOutputFileName("output.pdf");

document->print(&printer);
delete document;
return 0;

Upvotes: 4

Views: 3717

Answers (1)

mohabouje
mohabouje

Reputation: 4050

What about using QWebEngineView & QWebEnginePage? Just load your HTML file in the WebView and call printToPdf funciton:

 const QString fileName = QFileDialog::getSaveFileName(0,
                                                tr("Save pdf"),
                                                getLastDirectory(),
                                                tr("PDF Files (*.pdf)"));
if (fileName.isEmpty()) {
    return;
}
ui->webView->page()->printToPdf(fileName);

To use with QWebKit:

    // Set location of resulting PDF
    const QString fileName = QFileDialog::getSaveFileName(0,
                                                tr("Save pdf"),
                                                getLastDirectory(),
                                                tr("PDF Files (*.pdf)"));
    if (fileName.isEmpty()) {
       return;
    } 

    QPrinter printer(QPrinter::HighResolution);
    printer.setOutputFileName(fileName);

    // Create PDF
    ui->webview->print(&printer);

How to load the html file with the css? If your HTML links the CSS file correctly in the same folder:

QFile  htmlFile ("myhtml.html");
ui->webView->load(QUrl::fromLocalFile(QFileInfo(htmlFile).absoluteFilePath()));

Upvotes: 2

Related Questions