Qt打印html到打印机

时间:2015-09-23 09:08:47

标签: qt printing

我有一些 HTML ,想要打印到打印机。我的Qt版本是Qt5.5,我写道:

QFile x("E://a.html");
x.open(QIODevice::ReadOnly);
QTextStream in(&x);
QString html = in.readAll();
QTextDocument doc;

QPrinter p(QPrinter::HighResolution);
p.setResolution(QPrinter::HighResolution);
p.setOutputFormat(QPrinter::NativeFormat);
QPrintDialog printDialog(&p);
if (printDialog.exec() == QDialog::Accepted) {
    QSizeF paperSize;
    paperSize.setWidth(p.width());
    paperSize.setHeight(p.height());
    doc.setPageSize(paperSize);
    doc.setHtml(html);
    doc.print(&p);
}

我得到了结果。但 HTML内容太小了...... HTML Content

我想打印一些不同的纸张尺寸,如A3,A4,A5等,我需要 HTML内容自动适应纸张尺寸。

1 个答案:

答案 0 :(得分:0)

查看http://doc.qt.io/qt-5/qtprintsupport-index.html,他们建议使用此代码来缩放打印的小部件:

QPainter painter;
painter.begin(&printer);
double xscale = printer.pageRect().width()/double(myWidget->width());
double yscale = printer.pageRect().height()/double(myWidget->height());
double scale = qMin(xscale, yscale);
painter.translate(printer.paperRect().x() + printer.pageRect().width()/2,
printer.paperRect().y() + printer.pageRect().height()/2);
painter.scale(scale, scale);
painter.translate(-width()/2, -height()/2);
myWidget->render(&painter);