PDA

View Full Version : Printing QTextDocument (by painting, not the .print() func)



darkadept
28th June 2006, 21:49
I am attempting to print out a QTextDocument to the printer with more
control then the QTextDocument.print function. I've searched high
and low for any documentation pertaining to the Qt4 print system in
regards to rich text and have found very little information. See below for the code
I have so far.

For now I am only attempting to print page 1 and page 2 but it doesn't
seem to work quite right. On page 1 it prints properly except an outline
box that prints on the very bottom that seems like it's from page 2.
On page 2 it prints an outline box around where page 1 should be and then
it starts printing page 2 below that but page 2 is cut off.

It seems that the draw() function isn't obeying the clip context completely.

Can anyone shed some light on this. Or is there a better way to print QTextDocuments.
(besides the .print() function).

Thanks in advance for the help!

-Mike



void ReportPreview::on_printButton_clicked( )
{
QPrinter prn(QPrinter::HighResolution);
prn.setOutputFormat(QPrinter::PdfFormat);
prn.setOutputFileName("test.pdf");
prn.setPageSize(QPrinter::Letter);
prn.setColorMode(QPrinter::GrayScale);
prn.setOrientation(QPrinter::Landscape);

QPrintDialog prnDiag(&prn, this);
if (prnDiag.exec() == QDialog::Accepted)
{
QPainter p;
QAbstractTextDocumentLayout::PaintContext ctx;
QTextDocument *t = textBrowser->document()->clone(0); //Create a copy of the TextDocument

qreal w = (qreal)prn.width(); //Printer's page width
qreal h = (qreal)prn.height(); //Printer's page height

//Set the TextDocument's page size
t->documentLayout()->setPaintDevice(&prn);
t->setPageSize(QSizeF(w,h));

p.begin(&prn); //Start printing

//Page 1
ctx.clip = QRectF(0,0,w,h); //Set the context clip to the first page
t->documentLayout()->draw(&p,ctx);

//Page 2
prn.newPage();
ctx.clip = QRectF(0,h+1,w,h); //Set the context clip to the second page
t->documentLayout()->draw(&p,ctx);

//Eventually there will be a FOR loop printing the pages specified in prnDiag

p.end(); //End printing

//Clean up
delete t;
}
}