4

我正在使用 QPrinter 用文本填写表格并在打印机上打印它们。

对于测试,我生成 pdf 文件以避免纸张和墨水浪费。我发现 PDF 和实际打印的字体间距不同

最小的例子:

#include <QApplication>
#include <QPrinter>
#include <QPrinterInfo>
#include <QPainter>
#include <QFontDatabase>

void printForm(bool pdf);

QString g_fontFamily = "";

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

    int id = QFontDatabase::addApplicationFont(":/IBMPlexMono-Medium.ttf");
    g_fontFamily = QFontDatabase::applicationFontFamilies(id).at(0);

    printForm(true); //pdf
    printForm(false); //physical printer

    return a.exec();
}


void printForm(bool pdf)
{
    //setup printer
    QPrinter *printer;
    if(pdf)
    {
        printer = new QPrinter(QPrinter::ScreenResolution);
        printer->setOutputFormat(QPrinter::PdfFormat);
        printer->setOutputFileName("./regular.pdf");
    }
    else
    {
        printer = new QPrinter(QPrinterInfo::defaultPrinter(), QPrinter::ScreenResolution);
        printer->setOutputFormat(QPrinter::NativeFormat);
    }
    printer->setOrientation(QPrinter::Orientation::Landscape);
    QPageSize customSize(QSizeF(105.0, 157.76), QPageSize::Millimeter, "", QPageSize::ExactMatch);
    printer->setPageSize(customSize);

    //draw background
    QImage img(":/regular_transfer_form");
    QPainter painter(printer);
    painter.drawImage(QRect(0,0, printer->width(), printer->height()), img, QRect(0,0, img.width(), img.height()));

    //draw text
    painter.setPen(Qt::black);
    QFont font(g_fontFamily, 11);
    font.setStyleHint(QFont::TypeWriter);
    font.setLetterSpacing(QFont::PercentageSpacing, 212);

    painter.setFont(font);

    QTextOption textOption(Qt::AlignVCenter | Qt::AlignLeft);
    textOption.setWrapMode(QTextOption::NoWrap);

    QString text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";

    QRectF relativeArea(0.05838, 0.0783, 0.8971, 0.04583); //coords relative to background

    QRectF areaOnPaper(relativeArea.x() * printer->width(),
                                relativeArea.y() * printer->height(),
                                relativeArea.width() * printer->width(),
                                relativeArea.height() * printer->height()
                                );

    painter.drawText(areaOnPaper, text, textOption); //draw 1-st line wit percentage Spacing

    //set spacing to absolute
    font.setLetterSpacing(QFont::AbsoluteSpacing, 10);
    painter.setFont(font);

    areaOnPaper.setRect(areaOnPaper.x(), areaOnPaper.y() + 28, areaOnPaper.width(), areaOnPaper.height());
    painter.drawText(areaOnPaper, text, textOption); //draw 2-nd line wit absolute Spacing

}

结果:

PDF:很好 在此处输入图像描述

从打印机打印: 在此处输入图像描述

正如你所看到的——在纸上,字母不在盒子里,但两者的代码是相同的。

由于QPrinter 文档中的注释,我尝试使用QFont::PercentageSpacing(1-st line) 和(2nd line) 。没有成功。QFont::AbsoluteSpacing

我做错了什么还是Qt中有错误?

有没有办法在这两种情况下达到相同的结果?

github上带有背景图像和字体的完整示例

编辑https ://bugreports.qt.io/browse/QTBUG-72939

4

0 回答 0