2

I'm wondering how to print the document of a QPlainTextEdit component without any colors, backgrounds or formats ( plain text only ). The code I have is printing the background ( white on black in my case ).

QPrinter printer;  
QPrintDialog dialog( &printer, NULL );  
dialog.setWindowTitle( tr( "Print Content" ) );  
if ( isSelection ) {  
    dialog.addEnabledOption( QAbstractPrintDialog::PrintSelection );  
}  
if ( dialog.exec() == QDialog::Accepted ) {  
    document->print(&printer);  
}  

Any ideas ?? Thanks in advance !

Jablonski
  • 18,083
  • 2
  • 46
  • 47
Yore
  • 384
  • 1
  • 4
  • 18

1 Answers1

3

Use this:

QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName("output.pdf");
QString buffer = ui->plainTextEdit->document()->toHtml();
ui->plainTextEdit->setPlainText(ui->plainTextEdit->toPlainText());
ui->plainTextEdit->document()->print(&printer);
ui->plainTextEdit->clear();
ui->plainTextEdit->appendHtml(buffer);

The main idea is to print only plainText without formatting, but set normal formatted text after printing, so user will not lose formatted data.

I thought about improvement, so I wrote also this:

QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName("output.pdf");
QTextDocument *buffer = ui->plainTextEdit->document()->clone();
buffer->setPlainText(ui->plainTextEdit->toPlainText());
buffer->print(&printer);

Why is it better? We clone QTextDocument *buffer so we work with this new document. Our plainTextEdit remains untouchable, so user will not see unformatted text while print. But don't forget delete buffer When you don't need this clone aby more.

Result:

enter image description here

In pdf:

enter image description here

As you can see, there is no formatting.

Jablonski
  • 18,083
  • 2
  • 46
  • 47
  • This works, but it has a low performance if the text is big. Is there any other way of doing the same thing ? – Yore Oct 13 '14 at 20:11
  • @Yore Yes, of course, but everything has low perfomance with big data. As I know there is no method like `printPlainText`, so you should get rid from format anyways. My approach allows to achieve this. I think, that rendering using QPainter will be more inefficient. This answer can be improved only by improving way of format deleting, but now I don't see easy way to make it better. – Jablonski Oct 13 '14 at 20:19
  • In my case it worked. I had to replace a bit of your code since I can't change the contents of my component due to other stuff in it. The final approach was a bit worse in performance I guess but thats life :D Thx. – Yore Oct 13 '14 at 20:30