QPrinter为PDF和物理打印机提供不同的字体间距

时间:2019-01-09 19:17:30

标签: c++ qt qprinter

我正在使用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:很好 enter image description here

从打印机打印: enter image description here

如您所见-在纸上,字母不在框中,但两者的代码相同。

由于QPrinter documentation中的注释,我尝试使用QFont::PercentageSpacing(第一行)和QFont::AbsoluteSpacing(第二行)。没有成功。

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

在这两种情况下,有什么方法可以达到相同的结果吗?

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

0 个答案:

没有答案