我有以下Qt代码加载本地html文件并使用已安装的PDFCreator打印它。打印到PDFCreator时,文本在右侧被剪切,仅打印在第一页上。后续页面没有填充背景颜色的文本。
使用QPrinter::PdfFormat
作为输出格式并设置文件路径时,会成功生成PDF文件并正确显示内容。我使用的是Qt 5.4。
我是否需要为打印机设置特殊参数,或者这仍然是Qt错误(Qt 5.0报告了一个)。
#include <QApplication>
#include <QWebPage>
#include <QWebFrame>
#include <QTimer>
#include <QFileInfo>
#include <QPrinter>
class Task : public QObject {
Q_OBJECT
public:
Task(QObject *parent = 0) : QObject(parent) {}
public slots:
void run()
{
QFileInfo fileInfo("test.html");
QUrl url = QUrl::fromLocalFile(fileInfo.absoluteFilePath());
connect(&page, SIGNAL(loadFinished(bool)), this, SLOT(print()));
page.mainFrame()->load(url);
}
void print()
{
QPrinter printer;
printer.setPrinterName("PDFCreator");
printer.setPaperSize(QPrinter::A4);
#ifdef PRINT_TO_PDF
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName("output.pdf");
#endif
page.mainFrame()->print(&printer);
emit finished();
}
signals:
void finished();
private:
QWebPage page;
};
#include "main.moc"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// Task parented to the application so that it
// will be deleted by the application.
Task *task = new Task(&app);
// This will cause the application to exit when
// the task signals finished.
QObject::connect(task, SIGNAL(finished()), &app, SLOT(quit()));
// This will run the task from the application event loop.
QTimer::singleShot(0, task, SLOT(run()));
return app.exec();
}