print QPlainTextEdit document plain text only - c++

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 !

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:
In pdf:
As you can see, there is no formatting.

Related

How to return QTextEdit RichText as plain text?

I have a QTextEdit whose textFormat is Qt::RichText so it is possible to format the text with HTML tags. On this QTextEdit I have a QPopupMenu thats filled with QActions. One of these actions is a simple copy that connects into SLOT( onClipboardCopy() ).
QTextEdit's copy() is defined as "Copies any selected text (from selection 0) to the clipboard."
If there is something selected this function is perfect. However, I'd like to copy ALL of the TextEdit's content when nothing is selected.
Here's the slot:
void WidgetName::onClipboardCopy()
{
if ( TextEdit->hasSelectedText() )
{
TextEdit->copy();
}
else
{
QClipboard * xClipboard = QApplication::clipboard();
xClipboard->setText( TextEdit->text() );
}
}
The problem is in else TextEdit->text() returns the text with all of it's HTML tags. Is there an easy way to discard them?
Okay, I realized that I could select the text before copying. I get the desired effect by changing the code to:
void WidgetName::onClipboardCopy()
{
if ( TextEdit->hasSelectedText() )
{
TextEdit->copy();
}
else
{
TextEdit->selectAll();
TextEdit->copy();
TextEdit->removeSelection();
//QClipboard * xClipboard = QApplication::clipboard();
//xClipboard->setText( TextEdit->text() );
}
}

Why qDebug and QLabel don't show unicode?

I have a byteArray with 2 bytes. Those 2 bytes in UTF-8 mean "Š" ( one letter ) and in windows-1250 they mean "Š" ( two letters ), so they are properly in these two encodings.
My code:
QByteArray byteArray;
byteArray.append(0xC2);
byteArray.append(0x8A);
QTextStream textStreamUTF(byteArray);
textStreamUTF.setCodec(QTextCodec::codecForName("UTF-8"));
QString stringUTF = textStreamUTF.readLine();
QTextStream textStreamAnsi(byteArray);
textStreamAnsi.setCodec(QTextCodec::codecForLocale());
QString stringAnsi = textStreamAnsi.readLine();
qDebug()<<stringUTF<<stringAnsi;
In debug I see: "\u008A" "Š" , so stringAnsi is correctly displayed. StringUTF is properly set ( \u008A is Š ), but it isn't correctly displayed ( I would like to see "Š" ).
The same with QLabels and setText. When I set stringAnsi, I see on the screen good characters. When I set stringUTF I see nothing.

QMarginsF() not setting margins in QWebEnginePage::printToPdf

I'd like to know if there's anyone who can help me set some margins into qt QWebEnginePage::printToPdf pdf.
I'm loading an html from some url and rendering it with QWebEnginePage and then using printToPdf method to create the pdf file from html content.
But i'm not being able to set document margins (i've managed to set those margins with css, but i'd like to set it with the propert Qt class (QMarginsF)).
The code:
// NEW QT WEBENGINE PAGE
QWebEnginePage page;
// MARGINS
QMarginsF margins(75,75,75,75);
// CONNECT
QObject::connect( &page, &QWebEnginePage::loadFinished, [&page, output, &margins]()
{
// qDebug(QString("Margins: %1").arg(margins.top()).toStdString().c_str());
// PRINT TO PDF
page.printToPdf( [output](const QByteArray &data)
// LAMBDA (print2pdf first param)
{
QFile file(output);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
return;
}
file.write( data );
system( (" xdg-open " + output).toStdString().c_str() );
QApplication::exit(0);
},
// PAGE LAYOUT (print2pdf second param)
QPageLayout( QPageSize( QPageSize::A4 ), QPageLayout::Portrait, margins));
});
Thanks in advance.

Qt C++ writing data in a file , unexpected output

I have a task to save a file to computer. So this is my problem, when i write to file , it writes hex values.. I have no clue, what's wrong with my code. Here it is:
void MainWindow::on_actionSave_triggered()
{
QString filename = QFileDialog::getSaveFileName(
this,
tr("Save Document"),
QDir::currentPath(),
tr("Documents (*.txt)") );
QFile f( filename );
f.open( QIODevice::WriteOnly | QIODevice::Text );
QTextStream out(&f);
out << ui->textEdit->document();
}
QTextEdit's document method return QTextDocument, I think you want to use toPlainText method instead.
QTextEdit::document() will return a QTextDocument* which will be an Hex value (address). That's what you are adding in the file.
To get the contents from the QTextEdit use QString QTextEdit::toPlainText ()
HTH..

Qt: Print raw text

I need to output a ZPL script to a Zebra printer in a Qt application.
The printer is on a smb share network configured as raw printer in the client computer.
Everything goes fine if I call cupsPrintFile( "printer_name", "./tmp_print_file.zpl", "", 0, NULL ) from a C++ test program.
If I use QTextDocument::print() using the same text in "./tmp_print_file.zpl" as document, nothing gets printed.
I sniffed the network and found that the data being sent to the printer server is not raw data, but, a postscript!
Is there any way to get the data sent to the printer with no modification at all?
Let me be clear that I don't want to render a text, but just send the label script, that is ready to print, directly to the printer, that understands the ZPL protocol.
Thanks for all.
EDIT:
As #Martin said, I tried:
printer.setOutputFormat( QPrinter::NativeFormat );
QTextDocument *doc = new QTextDocument( QString( label ), this );
doc->print( &printer );
but it didn't work.
Before I start, must thank Dave. His suggestion to bypass the temporary file while printing with CUPs works fine.
Now, my conclusion: There is no easy way to print raw data using Qt only.
Maybe creating custom QPainter or going down to the bits of QPrinter could give a solution, but it would take me too much time.
The final solution is simply use CUPs API inside my Qt application. Unfortunatelly, it is not portable.
Here is a snippet:
#include <cups/cups.h>
//...
int print_label( const char *text, const char *printer_name, const char *job_name )
{
int jobId = 0;
jobId = cupsCreateJob( CUPS_HTTP_DEFAULT, printer_name, job_name, 0, NULL );
if ( jobId > 0 )
{
qDebug( ) << "Printing job #" << jobId << " (\"" << job_name << "\").";
const char* format = CUPS_FORMAT_TEXT; // CUPS_FORMAT_POSTSCRIPT;
cupsStartDocument( CUPS_HTTP_DEFAULT, printer_name, jobId, text, format, true );
cupsWriteRequestData( CUPS_HTTP_DEFAULT, text, strlen( text ) );
cupsFinishDocument( CUPS_HTTP_DEFAULT, printer_name );
}
return jobId;
}
//...
// Now, inside any Qt function (may be a slot):
QPrinter printer;
QPrintDialog *dialog = new QPrintDialog( &printer, this );
dialog->setWindowTitle( tr( "Zebra label" ) );
if ( dialog->exec( ) != QDialog::Accepted )
return;
// This is the sample label. Can be anything.
const char label[] =
"^XA~TA000~JSN^LT0^MNW^MTD^PON^PMN^LH0,0^JMA^PR4,4^MD0^JUS^LRN^CI0^XZ\n"
"^XA\n"
"^MMT\n"
"^LL0600\n"
"^PW900\n"
"^LS0\n"
"^BY2,3,54^FT24,109^BCN,,Y,N\n"
"^FD>;43210000>773>0000^FS\n"
"^PQ1,0,1,Y^XZ\n";
// Informative only.
ui->txtLabelScript->setPlainText( label );
// Call the printing function.
if ( print_label( label, printer.printerName( ).toAscii( ), "Zebra_Label" ) == 0 )
qDebug( ) << "CUPS Error: " << ippErrorString( cupsLastError( ) );
And it's done.
Don't forget to link libcups (-lcups).
I still hope any buddy to add another solution prooving that Qt-only is possible. Meanwhile, it is enough.
Thanks everybody.
Could you just do exactly what you did in your test program:
Create a temporary file (QTemporaryFile).
Send the contents to the file.
Call your cupsPrintFile method.
Or there is probably a way with the CUPS API to bypass the temporary file. Disclaimer: I have absolutely no experience with the CUPS API; this is just based on a cursory look at some online documentation. Looks like perhaps the following sequence:
cupsCreateJob > cupsStartDocument > cupsWriteRequestData > cupsFinishDocument
If that works, you just need to convert your QString to the correct byte encoding.
Thanks for fljx's code, it is very useful for me.
I changed a litte for sending raw text to zebra printer .
const char* format = CUPS_FORMAT_RAW;
Take a look at QPrinter(),
QTextDocument is designed to render formatted text.