Question

I have following printing code:

void Print(QPrinter *printer)
{
    QPainter q(printer);
    q.setRenderHint(QPainter::HighQualityAntialiasing, true);

    q.setPen(QPen(QColor("red")));
    q.drawRect(printer->pageRect());
    q.drawLine(printer->pageRect().topRight(), printer->pageRect().bottomLeft());

    q.setPen(QPen(QColor("blue")));
    q.drawRect(printer->paperRect());
    q.drawLine(printer->paperRect().topRight(), printer->paperRect().bottomLeft());
}

The result is different with QPrintPreviewDialog, rendered PDF, output to printers (HP LaserJet, PdfFactory, PdfCreator). Most of time the resulting rectangle is out of paper. What to do so the output is similar to all printers?

Was it helpful?

Solution 2

The Qt code I reviewed assumes 5% of paper as it's margin. Nobody trusts on correct paper margins.

OTHER TIPS

This really was asked some time ago, but I took the code from above and it cost me some hours to figure out, what's wrong with it. First, looking at the Qt source code, I could not find any place which assumes a 5% margin. Qt reads back the margins correctly from Windows XP and you can completely trust the page margins (Qt 4.5.3 with Windows XP).

The code above contains two issues: for printing a paperrect, the fullPage option must be set. Then the paperRect is printed at least on the preview correctly. Of course not on a real printer, as it is outside the pageRect. Generally, printing the paperRect makes no sense, as, if printed correctly, it lies exactly on the paper border.

The second major issue stems from printing pageRect without correcting the origin. If fullPage is disabled (default), then the pageRect origin lies at the paperRect origin thus includes the margins. But printing starts at QPoint(leftMargin,topMargin), so the margin is added twice.

To fix the issue, pageRect.moveTo(0,0) needs to be called and then the pageRect prints nicely where it belongs.

That different printers show different results comes from different device margins. Only devices with 0-margin will work with the original code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top