Print Widget to PDF with the minimal content
Solved
General and Desktop
-
wrote on 23 Feb 2020, 09:46 last edited by
Hello,
I print a widget (a tab from a QTabWidget) with its content with this code :
void MainWindow::print() { quint8 tabIndex = quint8(ui->tabWidget->currentIndex()); CharacterSheetWidget* widget = dynamic_cast< CharacterSheetWidget* >( ui->tabWidget->widget(tabIndex) ); QString tabName = ui->tabWidget->tabText(tabIndex); QString filePath = QFileDialog::getSaveFileName(this, QString(tr("Print as PDF...")), QString(), "PDF file (*.pdf)"); if(filePath.isEmpty()) return; QPrinter printer; printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(filePath); printer.setPaperSize(QPrinter::A4); printer.setResolution(300); printer.setFullPage(false); printer.setPageMargins(5, 5, 5, 5, QPrinter::Millimeter); QString originalStyle = widget->styleSheet(); widget->setStyleSheet("background-color:white;"); QPainter painter; painter.begin(&printer); double xscale = printer.pageRect().width() / double(widget->width()); double yscale = printer.pageRect().height() / double(widget->height()); double scale = qMin(xscale, yscale); painter.translate(printer.paperRect().center()); painter.scale(scale, scale); painter.translate(- widget->width()/ 2, - widget->height()/ 2); painter.setRenderHint(QPainter::Antialiasing, true); painter.setRenderHint(QPainter::SmoothPixmapTransform, true); widget->render(&painter); painter.end(); widget->setStyleSheet(originalStyle); }
but it printed it with a lot of space on the right and on bottom.
I would like to print the minimal content.
For exemple on this image, you see that it prints the red area in the pdf, I would like it prints the blue area.
How should I do (if you need more information, please tell me) -
wrote on 27 Feb 2020, 07:32 last edited by
By the way, I founded a solution : Before "QPainter painter;", I added this code :
QSize minSize = widget->minimumSizeHint(); int minWidth = minSize.width(); int minHeight = minSize.height();
And replaced all widget->width() and widget->height by minWidth and minHeight.
solved
1/2