在之前的 stackoverflow 之后讨论 https://stackoverflow.com/a/47879329/3336423,我正在尝试使用以下命令生成包含文本和图像的 pdfQt
and QTextDocument
.
这是我作为 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% 的表格应该占据整个页面宽度!)
问题是Qt不识别<table style=\"width: 100%\" border=1>
将其更改为<table width=100% border=1>
修复了问题,表格不占据整个页面宽度!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)