如何使QTextDocument适合打印机的整页宽度

问题描述 投票:1回答:1

在早期的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的全宽:

enter image description here

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

html qt pdf printing
1个回答
0
投票

问题只是Qt不承认<table style=\"width: 100%\" border=1>

将其更改为<table width=100% border=1>修复了问题,而不是表占据整页宽度!

© www.soinside.com 2019 - 2024. All rights reserved.