qt5吃掉我插入的所有空白区域

时间:2017-03-20 02:41:05

标签: html qt

我使用QString生成html并通过QTextDocument将其转换为pdf。 但是,空白区域根本无法生效,只剩下一个。

我尝试过google的方法,用指定的asc值替换“”。例如& nbsp& nbsp&#160&#8194&#8195。

如果我用html输入它们,那没关系。

如果在QString中设置html内容,则不正常,直接显示在html中,但不是白色空格。

"<p>&nbsp</p>"

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

只是,尝试了通用的html到pdf示例available from Qt

这是我的HTML代码:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>title</title>
</head>

<body>
    <h1>Hello, World!</h1>
    <p>Words&nbsp;separated&nbsp;with&nbsp;non&nbsp;breakable&nbsp;space</p>
    <p>Lorem ipsum dolor sit amet, consectitur adipisci elit.</p>
</body>

</html>

在Chrome中呈现的内容如下:

enter image description here

然后通过QTextDocument类使用简单的html到pdf转换:

#include <QApplication>

#include <QString>
#include <QPrinter>
#include <QTextDocument>
#include <QWidget>
#include <QFileDialog>

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

    QString fileName = QFileDialog::getSaveFileName((QWidget* )0, "Export PDF", QString(), "*.pdf");
    if (QFileInfo(fileName).suffix().isEmpty()) { fileName.append(".pdf"); }

    QPrinter printer(QPrinter::PrinterResolution);
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setPaperSize(QPrinter::A4);
    printer.setOutputFileName(fileName);

    QTextDocument doc;
    doc.setHtml("<h1>Hello, World!</h1><p>Words&nbsp;separated&nbsp;with&nbsp;non&nbsp;breakable&nbsp;space</p><p>Lorem ipsum dolor sit amet, consectitur adipisci elit.</p>");
    doc.setPageSize(printer.pageRect().size()); // This is necessary if you want to hide the page number
    doc.print(&printer);

    return a.exec();
}

给我一​​个输出pdf文件,呈现如下: enter image description here

正如我所看到的,没有任何空间被删除,一切都应该如此。 这段代码片段会帮助您实现您想要的目标吗?

或者您可以提供简单的可编辑示例,以便我们检查出错了什么?