如何使QTextDocument适应打印机的整个页面宽度 [英] How to fit QTextDocument to printer's full page width

查看:178
本文介绍了如何使QTextDocument适应打印机的整个页面宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在较早的stackoverflow 讨论之后,我正尝试使用QtQTextDocument.

After an earlier stackoverflow discussion, I'm trying to generate a pdf with text and images using Qt and QTextDocument.

这是我作为MCVE的代码:

Here is my code as an 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的全部宽度:

It does not work that bad, but the html content is not fitted to page: the table marked with "width=100%" does not actually occupy the full width of the pdf:

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

How can we force the html content to fit to page (meaning a table with width=100% should occupy the full page width!)

推荐答案

问题只是Qt无法识别<table style=\"width: 100%\" border=1>

The problem was just that Qt does not recognize <table style=\"width: 100%\" border=1>

将其更改为<table width=100% border=1>可以解决此问题,而不是表格占据了整个页面的宽度!

Changing it to <table width=100% border=1> fixed the issue, not the table occupies the full page width!

这篇关于如何使QTextDocument适应打印机的整个页面宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆