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


Qt Code:
  1. void ReportPreview::on_printButton_clicked( )
  2. {
  3. QPrinter prn(QPrinter::HighResolution);
  4. prn.setOutputFormat(QPrinter::PdfFormat);
  5. prn.setOutputFileName("test.pdf");
  6. prn.setPageSize(QPrinter::Letter);
  7. prn.setColorMode(QPrinter::GrayScale);
  8. prn.setOrientation(QPrinter::Landscape);
  9.  
  10. QPrintDialog prnDiag(&prn, this);
  11. if (prnDiag.exec() == QDialog::Accepted)
  12. {
  13. QAbstractTextDocumentLayout::PaintContext ctx;
  14. QTextDocument *t = textBrowser->document()->clone(0); //Create a copy of the TextDocument
  15.  
  16. qreal w = (qreal)prn.width(); //Printer's page width
  17. qreal h = (qreal)prn.height(); //Printer's page height
  18.  
  19. //Set the TextDocument's page size
  20. t->documentLayout()->setPaintDevice(&prn);
  21. t->setPageSize(QSizeF(w,h));
  22.  
  23. p.begin(&prn); //Start printing
  24.  
  25. //Page 1
  26. ctx.clip = QRectF(0,0,w,h); //Set the context clip to the first page
  27. t->documentLayout()->draw(&p,ctx);
  28.  
  29. //Page 2
  30. prn.newPage();
  31. ctx.clip = QRectF(0,h+1,w,h); //Set the context clip to the second page
  32. t->documentLayout()->draw(&p,ctx);
  33.  
  34. //Eventually there will be a FOR loop printing the pages specified in prnDiag
  35.  
  36. p.end(); //End printing
  37.  
  38. //Clean up
  39. delete t;
  40. }
  41. }
To copy to clipboard, switch view to plain text mode