Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTextDocument::drawContents only renders at 96 dpi

I am creating a high-resolution (1200 dpi) PDF document using QPrinter and QPainter. I am trying to draw text at the same resolution using QTextDocument::drawContents. The reason I want to use QTextDocument is because I need to include many tables and formatted text in my document.

My problem is that QTextDocument::drawContents always inserts the text at the screen resolution, which is 96 dpi in my case. All the solutions I have found thus far suggest scaling the text to achieve the correct size. However, this results in low quality text, which I cannot afford.

My question: Is there any way to draw the contents of a QTextDocument at a high resolution?

The code below creates a PDF file with 2 lines of text, one drawn using QPainter::drawText and one drawn using QTextDocument::drawContents. I have used an Arial 8pt font in order to emphasize the problem of the low quality resulting from the scaling.

// Read the screen resolution for scaling
QPrinter screenPrinter(QPrinter::ScreenResolution);
int screenResolution = screenPrinter.resolution();

// Setup the font
QFont font;
font.setFamily("Arial");
font.setPointSize(8);

// Define locations to insert text
QPoint textLocation1(20,10);
QPoint textLocation2(20,20);

// Define printer properties
QPrinter printer(QPrinter::HighResolution); 
printer.setOrientation(QPrinter::Portrait);
printer.setPaperSize(QPrinter::A4);
printer.setResolution(1200);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName("test.pdf");    

// Write text using QPainter::drawText
QPainter painter;
painter.begin(&printer);
painter.setFont(font);
painter.drawText(textLocation1, "QPainter::drawText");

// Write text using QTextDocument::drawContents
QTextDocument doc;
doc.setPageSize(printer.pageRect().size());
QTextCursor cursor(&doc);
QTextCharFormat charFormat;
charFormat.setFont(font);
cursor.insertText("QTextDocument::drawContents", charFormat);
painter.save();
painter.translate(textLocation2);
painter.scale(printer.resolution()/screenResolution, printer.resolution()/screenResolution);
doc.drawContents(&painter);
painter.restore();
painter.end();
like image 949
d11 Avatar asked Apr 24 '12 14:04

d11


1 Answers

The QTextDocument use its own paint device for the layout which is by default at screen resolution.
You can change it with:

doc.documentLayout()->setPaintDevice(&printer);
// just before
doc.setPageSize(printer.pageRect().size());
like image 151
alexisdm Avatar answered Oct 29 '22 12:10

alexisdm