Can't generate pdf with acceptable output quality using Qt

不问归期 提交于 2019-12-04 12:06:40

Personally I would strongly consider creating the content as a QTextDocument and then printing it. You can (IIRC, haven't used QwtPlot in a while) render the charts to images. Then it is easy to add the image to the document wherever you want. Same with your static image(s), of course. You can use HTML/CSS in the document (despite "Text" in the class name), and lots of other options.

Example added on request:

This is going to be very simplified and not fully formed, but hope it helps...

QTextDocument qtdoc;  // start with a QTextDocument

// prepare standard html with embedded image
QString html = "<html><body>" \
    "<h1>Hello World!</h1>" \
    "<img src='mydata://myimg.png' border='0' />" \
"</body></html>";  

QImage image = getChartImage();  // theoretical function

// here we add the actual image data to the document
qtdoc.addResource(QTextDocument::ImageResource, QUrl("mydata://myimg.png"), image);

qtdoc.setHtml(html);
// document is now fully formed and ready for display/print

To print to a PDF or HTML file:

void printToFile(const QTextDocument & qtdoc)
{
  QString fn = QFileDialog::getSaveFileName(this, tr("Select output file"), QString(), tr("PDF Files(*.pdf);;HTML-Files (*.htm *.html)"));
  if (fn.isEmpty())
    return;
  if (fn.endsWith(".pdf", Qt::CaseInsensitive)) {
    QPrinter printer;
    printer.setPageMargins(10.0,10.0,10.0,10.0,printer.Millimeter);
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setColorMode(QPrinter::Color);
    printer.setOutputFileName(fn);
    qtdoc.print(&printer);
  }
  else {  // HTML
    QTextDocumentWriter writer(fn);
    writer.write(qtdoc);
  }
}

Output to a printer:

void print(const QTextDocument & qtdoc)
{
  QPrinter printer;
  printer.setPageMargins(10.0,10.0,10.0,10.0,printer.Millimeter);
  QPrintDialog *dialog = new QPrintDialog(&printer, this);
  dialog->setWindowTitle(tr("Print Document"));
  if (dialog->exec() != QDialog::Accepted)
    return;
  qtdoc.print(&printer);
}

An actual screenshot of a working version (code for it starts here but is a bit of a chore to follow):

And the PDF export: http://max.wdg.us/docs/so/SO-47879329.pdf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!