【问题标题】:How to fit QTextDocument to printer's full page width如何使 QTextDocument 适合打印机的整个页面宽度
【发布时间】:2018-06-03 01:10:16
【问题描述】:

在较早的stackoverflow discussion 之后,我正在尝试使用QtQTextDocument 生成带有文本和图像的pdf。

这是我作为 MCVE 的代码:

#include <QApplication>
#include <QIcon>
#include <QDesktopServices>
#include <QWidget>
#include <QPrinter>
#include <QPainter>
#include <QPagedPaintDevice>
#include <QUrl>
#include <QFile>
#include <QTextDocument>

#include <sstream>
#include <memory>
#include <assert.h>

std::shared_ptr<QPrinter> getPrinter()
{
    std::shared_ptr<QPrinter> printer( new QPrinter( QPrinter::ScreenResolution ) );
    printer->setOutputFormat(QPrinter::PdfFormat);
    printer->setOrientation(QPrinter::Portrait);
    printer->setPaperSize(QPrinter::A4);
    printer->setPageMargins(10.0,10.0,10.0,10.0,QPrinter::Millimeter);
    printer->setOutputFormat(QPrinter::PdfFormat);
    printer->setColorMode(QPrinter::Color);
    printer->setFullPage( true );
    return printer;
}

bool generateReport( const std::string& fileName )
{
    auto printer = getPrinter();
    QSize pageSize = printer->pageRect().size();

    QTextDocument qtdoc;  // start with a QTextDocument
    qtdoc.setPageSize(pageSize);
    qtdoc.setDocumentMargin( 10 );

    std::stringstream str;
    str << "<html><head/><body>";
    str << "<table style=\"width: 100%\" border=\"1\"><tbody><tr><td>Foo</td><td>Bar</td></tr></tbody></table>";
    str << "</body></html>";

    qtdoc.setHtml(str.str().c_str());

    printer->setOutputFileName(fileName.c_str());
    qtdoc.print(printer.get());

    QDesktopServices::openUrl(QUrl::fromLocalFile(fileName.c_str()));

    return true;
}

int main( int argc, char* argv[] )
{
    QApplication app( argc, argv );

    generateReport( "report.pdf" );

    return 0;
}

没有那么糟糕,但是html内容不适合页面:标有“width=100%”的表格实际上并没有占据pdf的整个宽度:

我们如何强制 html 内容适合页面(意味着宽度=100% 的表格应该占据整个页面宽度!)

【问题讨论】:

  • 你确定你最终生成了有效的 HTML 吗?我很怀疑,因为 static std::string htmlContent = "\&lt;!DOCTYPE html&gt;\&lt;html&gt; 应该切断前导 &lt; 括号,如果我理解正确的话。
  • 也许您可以尝试在 QTextDocument 本身上设置边距?虽然我过去不必这样做。 printer-&gt;pageRect().size() 返回什么?此外,其他人在不涉及 QwtPlot 的情况下测试这个会更容易(也许是情节的静态图像?)。
  • @MaxPaperno:简化示例以隔离问题。

标签: html qt pdf printing


【解决方案1】:

问题只是Qt无法识别&lt;table style=\"width: 100%\" border=1&gt;

将其更改为&lt;table width=100% border=1&gt; 解决了问题,而不是表格占据了整个页面宽度!

【讨论】:

  • 很高兴听到!如果您还没有看到它,您可能会发现 this answer 对您解决字体大小/DPI 问题很有用。
  • @MaxPaperno:谢谢,setDefaultFont(font) 正是我想要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
  • 2012-10-29
  • 2014-07-25
相关资源
最近更新 更多