mercredi 28 septembre 2016

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 setResorce

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;

Aucun commentaire:

Enregistrer un commentaire