void Qt_help_window::print() { #ifndef QT_NO_PRINTER QPrinter printer; printer.setFullPage(TRUE); if ( printer.setup( this ) ) { QPainter p( &printer ); QPaintDeviceMetrics metrics(p.device()); int dpix = metrics.logicalDpiX(); int dpiy = metrics.logicalDpiY(); const int margin = 72; // pt QRect body(margin*dpix/72, margin*dpiy/72, metrics.width()-margin*dpix/72*2, metrics.height()-margin*dpiy/72*2 ); QSimpleRichText richText( browser->text(), QFont(), browser->context(), browser->styleSheet(), browser->mimeSourceFactory(), body.height() ); richText.setWidth( &p, body.width() ); QRect view( body ); int page = 1; do { richText.draw( &p, body.left(), body.top(), view, colorGroup() ); view.moveBy( 0, body.height() ); p.translate( 0 , -body.height() ); p.drawText( view.right() - p.fontMetrics().width( QString::number(page) ), view.bottom() + p.fontMetrics().ascent() + 5, QString::number(page) ); if ( view.top() >= richText.height() ) break; printer.newPage(); page++; } while (TRUE); } #endif }
bool QPrinterProto::newPage() { QPrinter *item = qscriptvalue_cast<QPrinter*>(thisObject()); if (item) return item->newPage(); return false; }
void ribi::braw::QtPrintRatingDialog::Print(const std::string& filename) { QPrinter printer; printer.setOrientation(QPrinter::Portrait); printer.setPaperSize(QPrinter::A4); printer.setFullPage(false); printer.setOutputFileName(filename.c_str()); //Draw the image to painter to printer (?must be done before printing) QPainter painter; painter.begin(&printer); { //Collect widgets to print const std::vector<QWidget *> widgets = CollectWidgets(); int y = 0; for (QWidget * const widget: widgets) { const int h = widget->height(); if (y+h > painter.window().height()) { printer.newPage(); y = 0; } widget->render(&painter,QPoint(0,y)); y+=h; } } painter.end(); }
void PageScreen::saveAsDocument(const QString &format) { const QString &suffix = QLatin1Char('.') + format.toLower(); QString pathWithoutSuffix = ui->location->text(); if (pathWithoutSuffix.endsWith(suffix, Qt::CaseInsensitive)) { pathWithoutSuffix = pathWithoutSuffix.mid(0, pathWithoutSuffix.length() - suffix.length()); } QPrinter printer; printer.setCreator(QupZilla::tr("QupZilla %1 (%2)").arg(QupZilla::VERSION, QupZilla::WWWADDRESS)); printer.setOutputFileName(pathWithoutSuffix + suffix); printer.setOutputFormat(QPrinter::PdfFormat); printer.setPaperSize(m_pageImages.first().size(), QPrinter::DevicePixel); printer.setPageMargins(0, 0, 0, 0, QPrinter::DevicePixel); printer.setFullPage(true); QPainter painter; painter.begin(&printer); for (int i = 0; i < m_pageImages.size(); ++i) { const QImage &image = m_pageImages.at(i); painter.drawImage(0, 0, image); if (i != m_pageImages.size() - 1) { printer.newPage(); } } painter.end(); }
void Help::filePrint() { QPrinter printer; printer.setFullPage(TRUE); if ( printer.setup() ) { QPainter p( &printer ); QPaintDeviceMetrics metrics(p.device()); int dpix = metrics.logicalDpiX(); int dpiy = metrics.logicalDpiY(); const int margin = 72; // pt QRect body(margin*dpix/72, margin*dpiy/72, metrics.width()-margin*dpix/72*2, metrics.height()-margin*dpiy/72*2 ); QFont font("times", 10); QSimpleRichText richText( browser->text(), font, browser->context(), browser->styleSheet(), browser->mimeSourceFactory(), body.height() ); richText.setWidth( &p, body.width() ); QRect view( body ); int page = 1; for (;;) { richText.draw( &p, body.left(), body.top(), view, colorGroup() ); view.moveBy( 0, body.height() ); p.translate( 0 , -body.height() ); p.setFont( font ); p.drawText( view.right() - p.fontMetrics().width( QString::number(page) ), view.bottom() + p.fontMetrics().ascent() + 5, QString::number(page) ); if ( view.top() >= richText.height() ) break; printer.newPage(); page++; } } }
/*! * \en * Print browser content. * \_en * \ru * Печатает содержимое браузера. * \_ru */ void aReportBrowser::print() { QPrinter printer; QPainter p; if (!printer.setup()) return; if ( p.begin( &printer ) ){ QPaintDeviceMetrics metrics( p.device() ); int dpiy = metrics.logicalDpiY(); int margin = (int) ( (2/2.54)*dpiy ); // 2 cm margins QRect body( margin, margin, metrics.width() - 2*margin, metrics.height() - 2*margin ); QSimpleRichText richText( textBrowser->text(), QFont(), textBrowser->context(), textBrowser->styleSheet(), textBrowser->mimeSourceFactory(), body.height() ); richText.setWidth( &p, body.width() ); QRect view( body ); int page = 1; do { richText.draw( &p, body.left(), body.top(), view, colorGroup() ); view.moveBy( 0, body.height() ); p.translate( 0 , -body.height() ); p.drawText( view.right() - p.fontMetrics().width( QString::number( page ) ), view.bottom() + p.fontMetrics().ascent() + 5, QString::number( page ) ); if ( view.top() >= richText.height() ) break; printer.newPage(); page++; } while (TRUE); } }
void MainWindow::on_pushButton_4_clicked() { QTextDocument doc; QString txt; txt = ::textAt(h3,65,"ASAP Film Order") % ::textAt(h3,40,"From C&C Special Products Co. 952-881-0073") % ::textAt(h3,67,"Mark Robin") % ::textAt(h3,6,"Attn: Customer Service") % ::nbsp(63) % "Rip Settings:"% ::textAt(h3,103,"1) Film Positives") % ::textAt(h3,103,"2) DO NOT TRAP") % ::textAt(h3,103,"3) Send Pre Separated") % ::textAt(h3,6,"Date: " % ui->dateEdit->text()) % ::textAt(h3,6,"File Name: " % ui->lineEdit_2->text()); qDebug() << "The memory used is: " << txt.capacity(); doc.setHtml(txt); #if !defined(QT_NO_PRINTER) && !defined(QT_NO_PRINTDIALOG) QPrinter printer(QPrinter::HighResolution); QPrintDialog *dlg = new QPrintDialog(&printer, this); dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); dlg->setWindowTitle(tr("Print Document")); if (dlg->exec() == QDialog::Accepted) { QPrinter printer; // printer.setOutputFileName("c:\\temp\\filenew.pdf"); // printer.setOutputFormat(QPrinter::PdfFormat); qDebug() << "Sending to printer"; doc.print(&printer); printer.newPage(); printer.setOutputFileName("c:\\temp\\faxASAP.pdf"); printer.setOutputFormat(QPrinter::PdfFormat); qDebug() << "Creating PDF"; doc.print(&printer); printer.newPage(); } delete dlg; #endif }
void QgsComposition::print( QPrinter &printer ) { //set resolution based on composer setting printer.setFullPage( true ); printer.setColorMode( QPrinter::Color ); //set user-defined resolution printer.setResolution( printResolution() ); QPainter p( &printer ); //QgsComposition starts page numbering at 0 int fromPage = ( printer.fromPage() < 1 ) ? 0 : printer.fromPage() - 1 ; int toPage = ( printer.toPage() < 1 ) ? numPages() - 1 : printer.toPage() - 1; if ( mPrintAsRaster ) { for ( int i = fromPage; i <= toPage; ++i ) { if ( i > fromPage ) { printer.newPage(); } QImage image = printPageAsRaster( i ); if ( !image.isNull() ) { QRectF targetArea( 0, 0, image.width(), image.height() ); p.drawImage( targetArea, image, targetArea ); } } } if ( !mPrintAsRaster ) { for ( int i = fromPage; i <= toPage; ++i ) { if ( i > fromPage ) { printer.newPage(); } renderPage( &p, i ); } } }
void UBExportFullPDF::saveOverlayPdf(UBDocumentProxy* pDocumentProxy, const QString& filename) { if (!pDocumentProxy || filename.length() == 0 || pDocumentProxy->pageCount() == 0) return; //PDF qDebug() << "exporting document to PDF Merger" << filename; QPrinter pdfPrinter; pdfPrinter.setOutputFormat(QPrinter::PdfFormat); pdfPrinter.setResolution(UBSettings::settings()->pdfResolution->get().toInt()); pdfPrinter.setOutputFileName(filename); pdfPrinter.setFullPage(true); QPainter* pdfPainter = 0; for(int pageIndex = 0 ; pageIndex < pDocumentProxy->pageCount(); pageIndex++) { UBGraphicsScene* scene = UBPersistenceManager::persistenceManager()->loadDocumentScene(pDocumentProxy, pageIndex); // set background to white, no grid for PDF output bool isDark = scene->isDarkBackground(); bool isCrossed = scene->isCrossedBackground(); scene->setBackground(false, false); // set high res rendering scene->setRenderingQuality(UBItem::RenderingQualityHigh); scene->setRenderingContext(UBGraphicsScene::PdfExport); QSize pageSize = scene->nominalSize(); UBGraphicsPDFItem *pdfItem = qgraphicsitem_cast<UBGraphicsPDFItem*>(scene->backgroundObject()); if (pdfItem) mHasPDFBackgrounds = true; pdfPrinter.setPaperSize(QSizeF(pageSize.width()*mScaleFactor, pageSize.height()*mScaleFactor), QPrinter::Point); if (!pdfPainter) pdfPainter = new QPainter(&pdfPrinter); if (pageIndex != 0) pdfPrinter.newPage(); //render to PDF scene->setDrawingMode(true); scene->render(pdfPainter, QRectF(), scene->normalizedSceneRect()); //restore screen rendering quality scene->setRenderingContext(UBGraphicsScene::Screen); scene->setRenderingQuality(UBItem::RenderingQualityNormal); //restore background state scene->setDrawingMode(false); scene->setBackground(isDark, isCrossed); } if (pdfPainter) delete pdfPainter; }
bool UBExportPDF::persistsDocument(UBDocumentProxy* pDocumentProxy, const QString& filename) { QPrinter pdfPrinter; qDebug() << "exporting document to PDF" << filename; pdfPrinter.setOutputFormat(QPrinter::PdfFormat); pdfPrinter.setResolution(UBSettings::settings()->pdfResolution->get().toInt()); pdfPrinter.setOutputFileName(filename); pdfPrinter.setFullPage(true); //need to calculate screen resolution QDesktopWidget* desktop = UBApplication::desktop(); int dpiCommon = (desktop->physicalDpiX() + desktop->physicalDpiY()) / 2; float scaleFactor = 72.0f / dpiCommon; QPainter pdfPainter; bool painterNeedsBegin = true; int existingPageCount = pDocumentProxy->pageCount(); for(int pageIndex = 0 ; pageIndex < existingPageCount; pageIndex++) { UBGraphicsScene* scene = UBPersistenceManager::persistenceManager()->loadDocumentScene(pDocumentProxy, pageIndex); UBApplication::showMessage(tr("Exporting page %1 of %2").arg(pageIndex + 1).arg(existingPageCount)); // set background to white, no crossing for PDF output bool isDark = scene->isDarkBackground(); bool isCrossed = scene->isCrossedBackground(); scene->setBackground(false, false); QSize pageSize = scene->nominalSize(); // set high res rendering scene->setRenderingQuality(UBItem::RenderingQualityHigh); scene->setRenderingContext(UBGraphicsScene::NonScreen); //setting page size to appropriate value pdfPrinter.setPaperSize(QSizeF(pageSize.width()*scaleFactor, pageSize.height()*scaleFactor), QPrinter::Point); if(painterNeedsBegin) painterNeedsBegin = !pdfPainter.begin(&pdfPrinter); //render to PDF scene->render(&pdfPainter, QRectF(), scene->normalizedSceneRect()); if (pageIndex < existingPageCount - 1) pdfPrinter.newPage(); //restore screen rendering quality scene->setRenderingContext(UBGraphicsScene::Screen); scene->setRenderingQuality(UBItem::RenderingQualityNormal); //restore background state scene->setBackground(isDark, isCrossed); } if(!painterNeedsBegin) pdfPainter.end(); return true; }
void HelpWindow::print() { #ifndef QT_NO_PRINTER QPrinter printer; printer.setFullPage(TRUE); if ( printer.setup() ) { QPainter p( &printer ); QPaintDeviceMetrics metrics(p.device()); int dpix = metrics.logicalDpiX(); int dpiy = metrics.logicalDpiY(); const int margin = 72; // pt QRect body(margin*dpix/72, margin*dpiy/72, metrics.width()-margin*dpix/72*2, metrics.height()-margin*dpiy/72*2 ); QFont font("times", 10); QStringList filePaths = browser->mimeSourceFactory()->filePath(); QString file; QStringList::Iterator it = filePaths.begin(); for ( ; it != filePaths.end(); ++it ) { file = QUrl( *it, QUrl( browser->source() ).path() ).path(); if ( QFile::exists( file ) ) break; else file = QString::null; } if ( file.isEmpty() ) return; QFile f( file ); if ( !f.open( IO_ReadOnly ) ) return; QTextStream ts( &f ); QSimpleRichText richText( ts.read(), font, browser->context(), browser->styleSheet(), browser->mimeSourceFactory(), body.height() ); richText.setWidth( &p, body.width() ); QRect view( body ); int page = 1; do { richText.draw( &p, body.left(), body.top(), view, colorGroup() ); view.moveBy( 0, body.height() ); p.translate( 0 , -body.height() ); p.setFont( font ); p.drawText( view.right() - p.fontMetrics().width( QString::number(page) ), view.bottom() + p.fontMetrics().ascent() + 5, QString::number(page) ); if ( view.top() >= richText.height() ) break; printer.newPage(); page++; } while (TRUE); } #endif }
void QgsComposition::doPrint( QPrinter& printer, QPainter& p ) { //QgsComposition starts page numbering at 0 int fromPage = ( printer.fromPage() < 1 ) ? 0 : printer.fromPage() - 1 ; int toPage = ( printer.toPage() < 1 ) ? numPages() - 1 : printer.toPage() - 1; if ( mPrintAsRaster ) { for ( int i = fromPage; i <= toPage; ++i ) { if ( i > fromPage ) { printer.newPage(); } QImage image = printPageAsRaster( i ); if ( !image.isNull() ) { QRectF targetArea( 0, 0, image.width(), image.height() ); p.drawImage( targetArea, image, targetArea ); } } } if ( !mPrintAsRaster ) { for ( int i = fromPage; i <= toPage; ++i ) { if ( i > fromPage ) { printer.newPage(); } renderPage( &p, i ); } } }
/*----------------------------------------------------------------------------*/ void ReportDialog::onActionExportToPdf() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "", tr("Pdf files (*.pdf)")); if(fileName.isEmpty()) return; QPrinter printer; printer.setPaperSize(QPrinter::A4); printer.setOrientation(QPrinter::Portrait); printer.setPageMargins(20.0,10.0,10.0,10.0,QPrinter::Millimeter); printer.setOutputFileName(fileName); printer.setOutputFormat(QPrinter::PdfFormat); ui->webView->print(&printer); printer.newPage(); }
bool Utils::exportAsPdf(const QString &fileName, const QJsonObject &contents) { QTextDocument doc; QString html; QTextStream stream(&html); stream << QString("<html><head><style type=\"text/css\">" "h1 {color:red;} " " " "</style></head><body>"); stream << QString("<h1>%1</h1>").arg(contents["name"].toString()); stream << QString("<p>%1 <br>").arg(contents["totaltime"].toString()); stream << QString(tr("Difficulty: %1<br>")).arg(contents["difficulty"].toDouble()); // FIXME: how can I access the array? stream << QString(tr("Restriction: %1</p>")).arg(contents["restriction"].toDouble()); stream << QString(tr("<h2>Ingredients</h2>")); stream << "<ul>"; QJsonArray ingredients = contents["ingredients"].toArray(); for (int i = 0; i < ingredients.count(); i++) { QJsonObject ingredient = ingredients[i].toObject(); stream << QString("<li>%1 %2 %3</li>").arg(ingredient["quantity"].toDouble()) .arg(ingredient["type"].toString(), ingredient["name"].toString()); } stream << "</ul>"; stream << QString(tr("<h2>Directions</h2>")); stream << QString("<p>%1</p>").arg(contents["directions"].toString()); stream << QString(tr("<h2>Photos</h2><br />")); QJsonArray photos = contents["photos"].toArray(); for (int i = 0; i < photos.count(); i++) stream << QString("<img src='%1' width=200 />").arg(photos[i].toString()); stream << QString("</body></html>"); doc.setHtml(html); QPrinter printer; printer.setOutputFileName(fileName); printer.setOutputFormat(QPrinter::PdfFormat); doc.print(&printer); printer.newPage(); return true; }
void ribi::pvdb::QtPvdbPrintRatingDialog::Print() { //Start save dialog const boost::shared_ptr<QFileDialog> print_dialog( pvdb::QtFileDialog::GetSaveFileDialog( pvdb::QtFileDialog::FileType::pdf)); print_dialog->setWindowTitle("Exporteer document naar PDF"); if (print_dialog->exec() != QDialog::Accepted || print_dialog->selectedFiles().empty() ) { return; } assert(!print_dialog->selectedFiles().empty()); assert(print_dialog->selectedFiles().size() == 1); const std::string filename = print_dialog->selectedFiles()[0].toStdString(); QPrinter printer; printer.setOrientation(QPrinter::Portrait); printer.setPaperSize(QPrinter::A4); printer.setFullPage(false); printer.setOutputFileName(filename.c_str()); //Draw the image to painter to printer (?must be done before printing) QPainter painter; painter.begin(&printer); { //Collect widgets to print const std::vector<QWidget *> widgets = CollectWidgets(); int y = 0; for (QWidget * const widget: widgets) { const int h = widget->height(); if (y+h > painter.window().height()) { printer.newPage(); y = 0; } widget->render(&painter,QPoint(0,y)); y+=h; } } painter.end(); }
/*! \param itemRow The row of the item for which to print the barcode lable. \see printLabelCurrent() */ void wndInventoryControl::printLabel( QVector<int> itemRow ) { QPrinter printer; // The labels used are 2.25"x0.75" // Set page size and margins accordingly qreal labelwidth = 2.25; qreal labelheight = 0.75; printer.setPaperSize( QSizeF( labelwidth, labelheight ), QPrinter::Inch ); printer.setPageMargins( 0, 0, 0, 0, QPrinter::Inch ); // PDF printing: //printer.setOutputFormat(QPrinter::PdfFormat); //printer.setOutputFileName("test.pdf"); // Build the painter data which is printed QPainter painter; if ( !painter.begin( &printer ) ) // Link the painter to the printer { qWarning( "Printer Error: Could not link painter to printer." ); return; } for ( int i = 0; i < itemRow.size(); i++ ) { // Get the id column of the QTableView. QString codestring = "*" + _pUI->tblInventory->model()->data( _pUI->tblInventory->model()->index( itemRow[i] ,0 ) ).toString() + "*"; // Draw the plaintext id centered at the top of the label painter.setFont( QFont( "Verdana", 10 ) ); painter.drawText( 0 ,0, (int)( labelwidth * printer.resolution() ), (int)( labelheight * printer.resolution() ), Qt::AlignHCenter, codestring ); // Switch to the barcode font and do the same painter.setFont( QFont( "Free 3 of 9 Extended", 32 ) ); painter.drawText( 0, 15, (int)( labelwidth * printer.resolution() ), (int)( labelheight * printer.resolution() ), Qt::AlignHCenter, codestring ); if ( i < itemRow.size() - 1 ) printer.newPage(); } painter.end(); // Send output }
void MainWindow::on_pushButton_clicked() { if (ui ->checkBox->checkState()== false) { ui ->checkBox->click(); } //ofstream myfile; //myfile.open ("example.txt"); //myfile << "Writing this to a file.\n"; //myfile.close(); //ui->textEdit->append(ui->lineEdit->text()); //ui->textEdit->append("Hello World"); //ui->textEdit->setHtml("<h1> Hello there "+ui->lineEdit->text()); //ui->textEdit->append("<h1> nice work! </h1>"); //ui->textEdit->setHtml("<h3>11111111112222222222333333333344444444445555555555666666666677777777778888888888999999999900000000</h3>"); ui->textEdit->setHtml(::textAt(h3,65,"ASAP Film Order")); ui->textEdit->append(::textAt(h3,40,"From C&C Special Products Co. 952-881-0073")); ui->textEdit->append(::textAt(h3,67,"Mark Robin")); ui->textEdit->append(::textAt(h3,6,"Attn: Customer Service"+::nbsp(63)+"Rip Settings:")); ui->textEdit->append(::textAt(h3,103,"1) Film Positives")); ui->textEdit->append(::textAt(h3,103,"2) DO NOT TRAP")); ui->textEdit->append(::textAt(h3,103,"3) Send Pre Separated")); ui->textEdit->append(::textAt(h3,6,"Date: "+ui->dateEdit->text())); ui->textEdit->append(::textAt(h3,6,"File Name: "+ui->lineEdit_2->text())); // Print the page #if !defined(QT_NO_PRINTER) && !defined(QT_NO_PRINTDIALOG) QPrinter printer(QPrinter::HighResolution); QPrintDialog *dlg = new QPrintDialog(&printer, this); dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); dlg->setWindowTitle(tr("Print Document")); if (dlg->exec() == QDialog::Accepted) { QPrinter printer; ui->textEdit->print(&printer); printer.newPage(); } delete dlg; #endif }
//---------------------------------------------------------------------------- void Guido2Image::writePDF( QGuidoPainter * guidoPainter, int pageIndex, const char * fname ) { QString fileName (fname); if ( !fileName.toUpper().endsWith( PDF_FORMAT.toUpper())) fileName += PDF_FORMAT; QPrinter printer; printer.setFullPage(true); printer.setOutputFileName( fileName ); printer.setOutputFormat( QPrinter::PdfFormat ); QSizeF firstPageSize = guidoPainter->pageSizeMM(1); printer.setPaperSize( firstPageSize, QPrinter::Millimeter ); QPainter painter(&printer); painter.setRenderHint( QPainter::Antialiasing ); painter.setWindow( QRect( 0 , 0 , firstPageSize.width() , firstPageSize.height() ) ); int pageCount = guidoPainter->pageCount(); int startPage = 1; int lastPage = pageCount; if ( pageIndex != 0 ) //Draw only the requested page { startPage = pageIndex; lastPage = pageIndex; } for ( int page = startPage ; page <= lastPage ; page++ ) { QSizeF paperSize = guidoPainter->pageSizeMM(page); // printer.setPaperSize( paperSize , QPrinter::Millimeter ); // painter.setWindow( QRect( 0 , 0 , paperSize.width() , paperSize.height() ) ); // paperSize = printer.paperSize( QPrinter::DevicePixel ); guidoPainter->draw(&painter,page,QRect(0,0,paperSize.width() , paperSize.height() ) ); if (page != lastPage) printer.newPage(); } painter.end(); }
void App::slotItemReadyForPrinting() { QPrinter printer; QPrintDialog *dlg = new QPrintDialog(&printer, 0); if(dlg->exec() == QDialog::Accepted) { QRectF pageRect = printer.pageRect(); QSize imgSize = m_printerImage->image().size(); int totalHeight = imgSize.height(); int yOffset = 0; qDebug() << "Page size:" << pageRect << ", image size:" << imgSize; QPainter painter(&printer); painter.setRenderHint(QPainter::Antialiasing, false); painter.setRenderHint(QPainter::SmoothPixmapTransform); QImage img = m_printerImage->image(); int actualWidth = imgSize.width(); // if the grabbed image is larger than the page, fit it to the page width if (pageRect.width() < imgSize.width()) { img = m_printerImage->image().scaledToWidth(pageRect.width(), Qt::SmoothTransformation); actualWidth = pageRect.width(); } // handle multi-page printing while(totalHeight > 0) { painter.drawImage(QPoint(0, 0), img, QRectF(0, yOffset, actualWidth, pageRect.height())); yOffset += pageRect.height(); totalHeight -= pageRect.height(); if (totalHeight > 0) printer.newPage(); } painter.end(); } m_printerImage.clear(); }
void TextEdit::filePrint() { if ( !currentEditor() ) return; #ifndef QT_NO_PRINTER QPrinter printer; printer.setFullPage(TRUE); QPaintDeviceMetrics screen( this ); printer.setResolution( screen.logicalDpiY() ); if ( printer.setup( this ) ) { QPainter p( &printer ); QPaintDeviceMetrics metrics( p.device() ); int dpix = metrics.logicalDpiX(); int dpiy = metrics.logicalDpiY(); const int margin = 72; // pt QRect body( margin * dpix / 72, margin * dpiy / 72, metrics.width() - margin * dpix / 72 * 2, metrics.height() - margin * dpiy / 72 * 2 ); QFont font( "times", 10 ); QSimpleRichText richText( currentEditor()->text(), font, currentEditor()->context(), currentEditor()->styleSheet(), currentEditor()->mimeSourceFactory(), body.height() ); richText.setWidth( &p, body.width() ); QRect view( body ); int page = 1; do { richText.draw( &p, body.left(), body.top(), view, colorGroup() ); view.moveBy( 0, body.height() ); p.translate( 0 , -body.height() ); p.setFont( font ); p.drawText( view.right() - p.fontMetrics().width( QString::number( page ) ), view.bottom() + p.fontMetrics().ascent() + 5, QString::number( page ) ); if ( view.top() >= richText.height() ) break; printer.newPage(); page++; } while (TRUE); } #endif }
void StructView::printAll() { if( !sch ) { return; } QPrinter *pr = MAINWIN->getPrinter(); if( !pr ) { qWarning() << "Printer not found!"; return; } QPrintDialog pr_dialog( pr, this ); if( ! pr_dialog.exec() ) { return; } devTp = 1; pr->setFullPage( false ); pr->newPage(); QPainter p( pr ); drawAll( p ); p.end(); }
void MainWindow::printFile() { GRPrintPagesDlg pagesdlg; if ( pagesdlg.exec() != QDialog::Accepted ) return; int rows = pagesdlg.rows(); int columns = pagesdlg.columns(); QPrintDialog pr; if ( pr.exec() == QDialog::Accepted ) { QPrinter *qp = pr.printer(); int pwidth = qp->pageRect().width(); int pheight = qp->pageRect().height(); int npages = rows * columns; int gwidth = columns * pwidth, gheight = rows * pheight; QImage img(gwidth, gheight, QImage::Format_RGB444); if ( img.isNull() ) return; // render graph QPainter gpaint; gpaint.begin(&img); gpaint.fillRect(img.rect(), Qt::white); QFont f("courier", 12); gpaint.setFont(f); QRect text_rect = gpaint.fontMetrics().boundingRect(G_title); int x = (gwidth - text_rect.width()) / 2; gpaint.drawText(x, text_rect.height(), G_title); PaintStruct ps; ps.p = &gpaint; ps.border = 60; set_drawing_rectangle(gwidth-120, gheight-120); display_complete_graph(); draw_graph(draw_line, draw_rect, draw_poly, &ps); gpaint.end(); // copy to pages QPainter prpaint; prpaint.begin(qp); QRect src; QRect dst(0, 0, pwidth, pheight); for ( int page = 0, col = 0, row = 0; page < npages; ++page ) { src.setLeft(col*pwidth); src.setTop(row*pheight); src.setWidth(pwidth); src.setHeight(pheight); prpaint.drawImage(QPoint(0, 0), img, src); // next if ( page < npages - 1 ) qp->newPage(); if ( col < columns - 1 ) ++col; else { ++row; col = 0; } } prpaint.end(); //this will reset the drawing rectangle to the canvas values canvas->viewport()->repaint(); display_complete_graph(); } }
void StitchLibraryUi::printStitchSet() { //FIXME: this only prints the visible part of the widget. QPrinter printer; QPrintDialog dialog(&printer, this); if(dialog.exec() != QDialog::Accepted) return; ui->listView->setWordWrap(true); ui->listView->setTextElideMode(Qt::ElideNone); const int rows = ui->listView->model()->rowCount(); ui->listView->resizeRowsToContents(); ui->listView->resizeColumnsToContents(); // calculate the total width/height table would need without scaling double totalWidth = 0.0; double totalHeight = 0.0; QList<int> widths; widths << 0 << 0 << 0; for (int r = 0; r < rows; ++r) { totalHeight += ui->listView->rowHeight(r); for (int c = 0; c < 3; ++c) { int temp = ui->listView->columnWidth(c); if(temp > widths.at(c)) widths[c] = temp; } } foreach(int w, widths) totalWidth += w; //QSizeF size = QSize(totalWidth, totalHeight); //printer.setPaperSize(size, QPrinter::Point); QPainter p; p.begin(&printer); int rowHeight = 35; // paint cells for (int r = 0; r < rows; ++r) { if(rowHeight + ui->listView->rowHeight(r) > (printer.pageRect().height() - 35)) { printer.newPage(); rowHeight = 35; } int startX = 0; for (int c = 0; c < 3; ++c) { QModelIndex idx = ui->listView->model()->index(r, c); QStyleOptionViewItem option;// = ui->listView->viewOptions(); option.palette.setColor(QPalette::Text, QColor(Qt::black)); option.rect.setTop(rowHeight); option.rect.setLeft(startX + 35); option.rect.setHeight(ui->listView->visualRect(idx).height()); //FIXME: this shouldn't be hard coded but oh well option.rect.setWidth(widths[c] +100); ui->listView->itemDelegate()->paint(&p, option, idx); startX += widths[c]; } rowHeight += ui->listView->rowHeight(r); } p.end(); }
bool KatePrinter::print (KateDocument *doc) { QPrinter printer; readSettings(printer); // docname is now always there, including the right Untitled name printer.setDocName(doc->documentName()); KatePrintTextSettings *kpts = new KatePrintTextSettings; KatePrintHeaderFooter *kphf = new KatePrintHeaderFooter; KatePrintLayout *kpl = new KatePrintLayout; QList<QWidget*> tabs; tabs << kpts; tabs << kphf; tabs << kpl; QWidget *parentWidget=doc->widget(); if ( !parentWidget ) parentWidget=QApplication::activeWindow(); QScopedPointer<QPrintDialog> printDialog(KdePrint::createPrintDialog(&printer, KdePrint::SystemSelectsPages, tabs, parentWidget)); if ( doc->activeView()->selection() ) { printer.setPrintRange(QPrinter::Selection); printDialog->setOption(QAbstractPrintDialog::PrintSelection, true); } if ( printDialog->exec() ) { writeSettings(printer); KateRenderer renderer(doc, doc->activeKateView()); renderer.config()->setSchema (kpl->colorScheme()); renderer.setPrinterFriendly(true); QPainter paint( &printer ); /* * We work in tree cycles: * 1) initialize variables and retrieve print settings * 2) prepare data according to those settings * 3) draw to the printer */ uint pdmWidth = printer.width(); uint pdmHeight = printer.height(); int y = 0; uint xstart = 0; // beginning point for painting lines uint lineCount = 0; uint maxWidth = pdmWidth; int headerWidth = pdmWidth; int startCol = 0; int endCol = 0; bool pageStarted = true; int remainder = 0; // remaining sublines from a wrapped line (for the top of a new page) // Text Settings Page bool selectionOnly = (printDialog->printRange() == QAbstractPrintDialog::Selection); bool useGuide = kpts->printGuide(); bool printLineNumbers = kpts->printLineNumbers(); uint lineNumberWidth( 0 ); // Header/Footer Page QFont headerFont(kphf->font()); // used for header/footer bool useHeader = kphf->useHeader(); QColor headerBgColor(kphf->headerBackground()); QColor headerFgColor(kphf->headerForeground()); uint headerHeight( 0 ); // further init only if needed QStringList headerTagList; // do bool headerDrawBg = false; // do bool useFooter = kphf->useFooter(); QColor footerBgColor(kphf->footerBackground()); QColor footerFgColor(kphf->footerForeground()); uint footerHeight( 0 ); // further init only if needed QStringList footerTagList; // do bool footerDrawBg = false; // do // Layout Page renderer.config()->setSchema( kpl->colorScheme() ); bool useBackground = kpl->useBackground(); bool useBox = kpl->useBox(); int boxWidth(kpl->boxWidth()); QColor boxColor(kpl->boxColor()); int innerMargin = useBox ? kpl->boxMargin() : 6; // Post initialization int maxHeight = (useBox ? pdmHeight-innerMargin : pdmHeight); uint currentPage( 1 ); uint lastline = doc->lastLine(); // necessary to print selection only uint firstline( 0 ); const int fontHeight = renderer.fontHeight(); KTextEditor::Range selectionRange; /* * Now on for preparations... * during preparations, variable names starting with a "_" means * those variables are local to the enclosing block. */ { if ( selectionOnly ) { // set a line range from the first selected line to the last selectionRange = doc->activeView()->selectionRange(); firstline = selectionRange.start().line(); lastline = selectionRange.end().line(); lineCount = firstline; } if ( printLineNumbers ) { // figure out the horiizontal space required QString s( QString("%1 ").arg( doc->lines() ) ); s.fill('5', -1); // some non-fixed fonts haven't equally wide numbers // FIXME calculate which is actually the widest... lineNumberWidth = renderer.currentFontMetrics().width( s ); // a small space between the line numbers and the text int _adj = renderer.currentFontMetrics().width( "5" ); // adjust available width and set horizontal start point for data maxWidth -= (lineNumberWidth + _adj); xstart += lineNumberWidth + _adj; } if ( useHeader || useFooter ) { // Set up a tag map // This retrieves all tags, ued or not, but // none of theese operations should be expensive, // and searcing each tag in the format strings is avoided. QDateTime dt = QDateTime::currentDateTime(); QMap<QString,QString> tags; KUser u (KUser::UseRealUserID); tags["u"] = u.loginName(); tags["d"] = KGlobal::locale()->formatDateTime(dt, KLocale::ShortDate); tags["D"] = KGlobal::locale()->formatDateTime(dt, KLocale::LongDate); tags["h"] = KGlobal::locale()->formatTime(dt.time(), false); tags["y"] = KGlobal::locale()->formatDate(dt.date(), KLocale::ShortDate); tags["Y"] = KGlobal::locale()->formatDate(dt.date(), KLocale::LongDate); tags["f"] = doc->url().fileName(); tags["U"] = doc->url().prettyUrl(); if ( selectionOnly ) { QString s( i18n("(Selection of) ") ); tags["f"].prepend( s ); tags["U"].prepend( s ); } QRegExp reTags( "%([dDfUhuyY])" ); // TODO tjeck for "%%<TAG>" if (useHeader) { headerDrawBg = kphf->useHeaderBackground(); headerHeight = QFontMetrics( headerFont ).height(); if ( useBox || headerDrawBg ) headerHeight += innerMargin * 2; else headerHeight += 1 + QFontMetrics( headerFont ).leading(); headerTagList = kphf->headerFormat(); QMutableStringListIterator it(headerTagList); while ( it.hasNext() ) { QString tag = it.next(); int pos = reTags.indexIn( tag ); QString rep; while ( pos > -1 ) { rep = tags[reTags.cap( 1 )]; tag.replace( (uint)pos, 2, rep ); pos += rep.length(); pos = reTags.indexIn( tag, pos ); } it.setValue( tag ); } if (!headerBgColor.isValid()) headerBgColor = Qt::lightGray; if (!headerFgColor.isValid()) headerFgColor = Qt::black; } if (useFooter) { footerDrawBg = kphf->useFooterBackground(); footerHeight = QFontMetrics( headerFont ).height(); if ( useBox || footerDrawBg ) footerHeight += 2*innerMargin; else footerHeight += 1; // line only footerTagList = kphf->footerFormat(); QMutableStringListIterator it(footerTagList); while ( it.hasNext() ) { QString tag = it.next(); int pos = reTags.indexIn( tag ); QString rep; while ( pos > -1 ) { rep = tags[reTags.cap( 1 )]; tag.replace( (uint)pos, 2, rep ); pos += rep.length(); pos = reTags.indexIn( tag, pos ); } it.setValue( tag ); } if (!footerBgColor.isValid()) footerBgColor = Qt::lightGray; if (!footerFgColor.isValid()) footerFgColor = Qt::black; // adjust maxheight, so we can know when/where to print footer maxHeight -= footerHeight; } } // if ( useHeader || useFooter ) if ( useBackground ) { if ( ! useBox ) { xstart += innerMargin; maxWidth -= innerMargin * 2; } } if ( useBox ) { if (!boxColor.isValid()) boxColor = Qt::black; if (boxWidth < 1) // shouldn't be pssible no more! boxWidth = 1; // set maxwidth to something sensible maxWidth -= ( ( boxWidth + innerMargin ) * 2 ); xstart += boxWidth + innerMargin; // maxheight too.. maxHeight -= boxWidth; } else boxWidth = 0; // now that we know the vertical amount of space needed, // it is possible to calculate the total number of pages // if needed, that is if any header/footer tag contains "%P". if ( !headerTagList.filter("%P").isEmpty() || !footerTagList.filter("%P").isEmpty() ) { kDebug(13020)<<"'%P' found! calculating number of pages..."; int pageHeight = maxHeight; if ( useHeader ) pageHeight -= ( headerHeight + innerMargin ); if ( useFooter ) pageHeight -= innerMargin; const int linesPerPage = pageHeight / fontHeight; // kDebug() << "Lines per page:" << linesPerPage; // calculate total layouted lines in the document int totalLines = 0; // TODO: right now ignores selection printing for (int i = firstline; i <= lastline; ++i) { KateLineLayoutPtr rangeptr(new KateLineLayout(doc)); rangeptr->setLine(i); renderer.layoutLine(rangeptr, (int)maxWidth, false); totalLines += rangeptr->viewLineCount(); } int totalPages = (totalLines / linesPerPage) + ((totalLines % linesPerPage) > 0 ? 1 : 0); // kDebug() << "_______ pages:" << (totalLines / linesPerPage); // kDebug() << "________ rest:" << (totalLines % linesPerPage); // TODO: add space for guide if required // if ( useGuide ) // _lt += (guideHeight + (fontHeight /2)) / fontHeight; // substitute both tag lists QString re("%P"); QStringList::Iterator it; for ( it=headerTagList.begin(); it!=headerTagList.end(); ++it ) (*it).replace( re, QString( "%1" ).arg( totalPages ) ); for ( it=footerTagList.begin(); it!=footerTagList.end(); ++it ) (*it).replace( re, QString( "%1" ).arg( totalPages ) ); } } // end prepare block /* On to draw something :-) */ while ( lineCount <= lastline ) { startCol = 0; endCol = 0; if ( y + fontHeight > maxHeight ) { kDebug(13020)<<"Starting new page,"<<lineCount<<"lines up to now."; printer.newPage(); paint.resetTransform(); currentPage++; pageStarted = true; y=0; } if ( pageStarted ) { if ( useHeader ) { paint.setPen(headerFgColor); paint.setFont(headerFont); if ( headerDrawBg ) paint.fillRect(0, 0, headerWidth, headerHeight, headerBgColor); if (headerTagList.count() == 3) { int valign = ( (useBox||headerDrawBg||useBackground) ? Qt::AlignVCenter : Qt::AlignTop ); int align = valign|Qt::AlignLeft; int marg = ( useBox || headerDrawBg ) ? innerMargin : 0; if ( useBox ) marg += boxWidth; QString s; for (int i=0; i<3; i++) { s = headerTagList[i]; if (s.indexOf("%p") != -1) s.replace("%p", QString::number(currentPage)); paint.drawText(marg, 0, headerWidth-(marg*2), headerHeight, align, s); align = valign|(i == 0 ? Qt::AlignHCenter : Qt::AlignRight); } } if ( ! ( headerDrawBg || useBox || useBackground ) ) // draw a 1 px (!?) line to separate header from contents { paint.drawLine( 0, headerHeight-1, headerWidth, headerHeight-1 ); //y += 1; now included in headerHeight } y += headerHeight + innerMargin; } if ( useFooter ) { paint.setPen(footerFgColor); if ( ! ( footerDrawBg || useBox || useBackground ) ) // draw a 1 px (!?) line to separate footer from contents paint.drawLine( 0, maxHeight + innerMargin - 1, headerWidth, maxHeight + innerMargin - 1 ); if ( footerDrawBg ) paint.fillRect(0, maxHeight+innerMargin+boxWidth, headerWidth, footerHeight, footerBgColor); if (footerTagList.count() == 3) { int align = Qt::AlignVCenter|Qt::AlignLeft; int marg = ( useBox || footerDrawBg ) ? innerMargin : 0; if ( useBox ) marg += boxWidth; QString s; for (int i=0; i<3; i++) { s = footerTagList[i]; if (s.indexOf("%p") != -1) s.replace("%p", QString::number(currentPage)); paint.drawText(marg, maxHeight+innerMargin, headerWidth-(marg*2), footerHeight, align, s); align = Qt::AlignVCenter|(i == 0 ? Qt::AlignHCenter : Qt::AlignRight); } } } // done footer if ( useBackground ) { // If we have a box, or the header/footer has backgrounds, we want to paint // to the border of those. Otherwise just the contents area. int _y = y, _h = maxHeight - y; if ( useBox ) { _y -= innerMargin; _h += 2 * innerMargin; } else { if ( headerDrawBg ) { _y -= innerMargin; _h += innerMargin; } if ( footerDrawBg ) { _h += innerMargin; } } paint.fillRect( 0, _y, pdmWidth, _h, renderer.config()->backgroundColor()); } if ( useBox ) { paint.setPen(QPen(boxColor, boxWidth)); paint.drawRect(0, 0, pdmWidth, pdmHeight); if (useHeader) paint.drawLine(0, headerHeight, headerWidth, headerHeight); else y += innerMargin; if ( useFooter ) // drawline is not trustable, grr. paint.fillRect( 0, maxHeight+innerMargin, headerWidth, boxWidth, boxColor ); } if ( useGuide && currentPage == 1 ) { // FIXME - this may span more pages... // draw a box unless we have boxes, in which case we end with a box line int _ystart = y; QString _hlName = doc->highlight()->name(); QList<KateExtendedAttribute::Ptr> _attributes; // list of highlight attributes for the legend doc->highlight()->getKateExtendedAttributeList(kpl->colorScheme(), _attributes); KateAttributeList _defaultAttributes; KateHlManager::self()->getDefaults ( renderer.config()->schema(), _defaultAttributes ); QColor _defaultPen = _defaultAttributes.at(0)->foreground().color(); paint.setPen(_defaultPen); int _marg = 0; if ( useBox ) _marg += (2*boxWidth) + (2*innerMargin); else { if ( useBackground ) _marg += 2*innerMargin; _marg += 1; y += 1 + innerMargin; } // draw a title string QFont _titleFont = renderer.config()->font(); _titleFont.setBold(true); paint.setFont( _titleFont ); QRect _r; paint.drawText( QRect(_marg, y, pdmWidth-(2*_marg), maxHeight - y), Qt::AlignTop|Qt::AlignHCenter, i18n("Typographical Conventions for %1", _hlName ), &_r ); int _w = pdmWidth - (_marg*2) - (innerMargin*2); int _x = _marg + innerMargin; y += _r.height() + innerMargin; paint.drawLine( _x, y, _x + _w, y ); y += 1 + innerMargin; int _widest( 0 ); foreach (const KateExtendedAttribute::Ptr &attribute, _attributes) _widest = qMax(QFontMetrics(attribute->font()).width(attribute->name().section(':',1,1)), _widest); int _guideCols = _w/( _widest + innerMargin ); // draw attrib names using their styles int _cw = _w/_guideCols; int _i(0); _titleFont.setUnderline(true); QString _currentHlName; foreach (const KateExtendedAttribute::Ptr &attribute, _attributes) { QString _hl = attribute->name().section(':',0,0); QString _name = attribute->name().section(':',1,1); if ( _hl != _hlName && _hl != _currentHlName ) { _currentHlName = _hl; if ( _i%_guideCols ) y += fontHeight; y += innerMargin; paint.setFont(_titleFont); paint.setPen(_defaultPen); paint.drawText( _x, y, _w, fontHeight, Qt::AlignTop, _hl + ' ' + i18n("text") ); y += fontHeight; _i = 0; } KTextEditor::Attribute _attr = *_defaultAttributes[attribute->defaultStyleIndex()]; _attr += *attribute; paint.setPen( _attr.foreground().color() ); paint.setFont( _attr.font() ); if (_attr.hasProperty(QTextFormat::BackgroundBrush) ) { QRect _rect = QFontMetrics(_attr.font()).boundingRect(_name); _rect.moveTo(_x + ((_i%_guideCols)*_cw), y); paint.fillRect(_rect, _attr.background() ); } paint.drawText(( _x + ((_i%_guideCols)*_cw)), y, _cw, fontHeight, Qt::AlignTop, _name ); _i++; if ( _i && ! ( _i%_guideCols ) ) y += fontHeight; } if ( _i%_guideCols ) y += fontHeight;// last row not full // draw a box around the legend paint.setPen ( _defaultPen ); if ( useBox ) paint.fillRect( 0, y+innerMargin, headerWidth, boxWidth, boxColor ); else { _marg -=1; paint.drawRect( _marg, _ystart, pdmWidth-(2*_marg), y-_ystart+innerMargin ); } y += ( useBox ? boxWidth : 1 ) + (innerMargin*2); } // useGuide paint.translate(xstart,y); pageStarted = false; } // pageStarted; move on to contents:)
void SpectaclesPrint::on_pushButton_Both_clicked() { LabPrint *labPrint = new LabPrint(0, thisTransaction, thisDate, thisDescription, thisType, thisFullName, thisPhone, thisAccount, thisAddress1, thisAddress2); labPrint->grab().save("C:/SQL/printLabTemp.png"); ClientPrint *clientPrint = new ClientPrint(0, thisTransaction, thisDate, thisFullName, thisPhone, thisAccount, thisAddress1, thisAddress2); clientPrint->grab().save("C:/SQL/printClientTemp.png"); QPrinter printer; QPrintDialog *dialog = new QPrintDialog(&printer); dialog->setWindowTitle("Print Document"); if (dialog->exec() != QDialog::Accepted) return; { QImage img("C:/SQL/printLabTemp.png"); qDebug() << "width: " << img.width(); qDebug() << "height: " << img.height(); //img = img.scaled(img.width(), img.height()); QPainter painter(&printer); //painter.drawImage(QPoint(0,0),img); QSize size = img.size(); painter.translate(size.height()/2,size.height()/2); // Rotate the painter 90 degrees painter.rotate(90); // Set origo back to upper left corner painter.translate(-size.height()/2,-size.height()/2); // Draw your original pixmap on it painter.drawImage(QPoint(10, 50),img); //Vertical, Horizontal painter.end(); } printer.newPage(); { QImage img("C:/SQL/printClientTemp.png"); qDebug() << "width: " << img.width(); qDebug() << "height: " << img.height(); img = img.scaled(img.width(), img.height()); QPainter painter(&printer); //painter.drawImage(QPoint(0,0),img); //painter.drawImage(QPoint(0,0),img); /*QSize size = img.size(); painter.translate(size.height()/2,size.height()/2); // Rotate the painter 90 degrees painter.rotate(90); // Set origo back to upper left corner painter.translate(-size.height()/2,-size.height()/2); // Draw your original pixmap on it painter.drawImage(QPoint(10, 50),img); //Vertical, Horizontal*/ painter.drawImage(QPoint(0, 10), img); painter.end(); } this->hide(); return; }
void SceneImageExporter::GraphicsSceneToPrinter( QGraphicsScene *scene, QPrinter& printer, QString fileName, QString documentName __attribute__((unused)), bool bSizeToOneSheet) { if (!fileName.isEmpty() && fileName != "" && fileName.endsWith(".pdf",Qt::CaseInsensitive)) { printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); } // When printing, use full page mode, IE ignore hardware margins. It's up // to users to set them as they desire. printer.setFullPage(true); printer.setPaperSize(QSizeF(PrintingPreferences::prefs().selectedMeasure().width(), PrintingPreferences::prefs().selectedMeasure().height()), QPrinter::Millimeter); printer.setPageMargins(PrintingPreferences::prefs().leftMargin(), PrintingPreferences::prefs().topMargin(), PrintingPreferences::prefs().rightMargin(), PrintingPreferences::prefs().bottomMargin(), QPrinter::Millimeter); if (!bSizeToOneSheet) { //here, I print using selected sheets and divisions. QPainter painter(&printer); qreal left,top,right,bottom; printer.getPageMargins(&left,&top,&right,&bottom,QPrinter::DevicePixel); // get the FULL PAGE RECTANGLE and adjust margins. QRectF pageRect = printer.paperRect(); pageRect.adjust(left,top,-right, -bottom); //get height/width page rect ratio double pageRatio = pageRect.width()/pageRect.height(); //get scene rectangle and calculating pages. int stepY = PrintingPreferences::prefs().yDivisions(); QRectF sceneRect = scene->sceneRect(); double scene_dy = sceneRect.height()/( (double)stepY); double scene_dx = scene_dy * pageRatio; double o_scene_dx = scene_dx * 1.1; double o_scene_dy = scene_dy * 1.1; double o_rect_dx = pageRect.width() / 1.1; double o_rect_dy = pageRect.height() / 1.1; double odx = ( pageRect.width() -o_rect_dx)/2.0; double ody = (pageRect.height() - o_rect_dy)/ 2.0; QRectF pageRectInner = QRectF (pageRect.left() + odx, pageRect.top() + ody, o_rect_dx, o_rect_dy); int stepX = 1+ (int)(sceneRect.width() / scene_dx); //ok, calculated my boxes. NOW, let's print everything out. QColor transparent(0,0,0,0); QColor transBorder (0,0,0,128); QPen pen (transBorder); pen.setStyle(Qt::DotLine); QBrush brush(transparent); bool bNewPage = false; for (int y = 0; y < stepY; y++) { for (int x = 0; x < stepX; x++) { if (bNewPage) printer.newPage(); else bNewPage = true; //I've already got my target rectangle QRectF sourceRect = QRectF ( sceneRect.left()+((double)x * scene_dx + (o_scene_dx - scene_dx)/2.0 ), sceneRect.top()+((double)y * scene_dy + (o_scene_dy - scene_dy)/2.0), o_scene_dx,o_scene_dy); scene->render(&painter,pageRect, sourceRect); QBrush oldBrush = painter.brush(); QPen oldPen = painter.pen(); //qDebug() << "pageRect " << pageRect; //qDebug() << "pageRectInner " << pageRectInner; painter.setPen(pen); painter.setBrush(brush); painter.drawRect(pageRect); painter.drawRect(pageRectInner); painter.setPen(oldPen); painter.setBrush(oldBrush); } } painter.end(); } else { QRectF sceneRect = scene->sceneRect(); //qDebug() << "scene Rect:" << sceneRect; printer.setResolution(96); printer.setPaperSize(QSizeF ( scene->sceneRect().width()+(76*2), scene->sceneRect().height()+(76*2)), QPrinter::DevicePixel); printer.setFullPage(true); printer.setPageMargins( 76.0,76.0,76.0,76.0, QPrinter::DevicePixel); QPainter painter(&printer); qreal left,top,right,bottom; printer.getPageMargins(&left,&top,&right,&bottom,QPrinter::DevicePixel); QRectF pageRect = printer.paperRect(); //qDebug() << "pageRect: " << pageRect; pageRect = pageRect.adjusted(left,top,-right,-bottom); //qDebug() << "pageRect: " << pageRect; //qDebug() << "sceneRect: " << sceneRect; scene->render(&painter,pageRect, sceneRect, Qt::IgnoreAspectRatio); //qDebug() << left << "," << right << "," << top << "," << bottom; //qDebug() << printer.paperRect().left() << "," // << printer.paperRect().width() << "," // << printer.paperRect().top() << "," // << printer.paperRect().height(); pageRect = printer.pageRect(); //qDebug() << pageRect.left() << "," // << pageRect.width() << "," // << pageRect.top() << "," // << pageRect.height(); QColor transparent(0,0,0,0); QColor transBorder (0,0,0,128); QPen pen (transBorder); pen.setStyle(Qt::DotLine); QBrush brush(transparent); painter.setPen(pen); painter.setBrush(brush); painter.drawRect(pageRect); painter.end(); } }
void SceneImageExporter::printScene(QGraphicsScene *scene, QPrinter& printer, QString fileName, QString documentName, int printingFlags) { if (!fileName.isEmpty() && fileName != "" && fileName.endsWith(".pdf",Qt::CaseInsensitive)) { printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); } else { //set page margins if I have to print on paper. printer.setPageMargins(10,10,10,10,QPrinter::Millimeter); } QPainter painter(&printer); QRectF sceneRect = scene->sceneRect(); double sceneRatio = scene->sceneRect().width()/scene->sceneRect().height(); qreal left,top,right,bottom; printer.getPageMargins(&left,&top,&right,&bottom,QPrinter::DevicePixel); QRect pageRect = QRect( printer.pageRect().top()+top, printer.pageRect().left()+left, printer.pageRect().width()-(left+right), printer.pageRect().height()-(top+bottom)); int xSize, ySize, dxSize, dySize, xPages, yPages; double fWidth, fHeight, fHeightStep, fWidthStep; double pageRectRatio = (double)pageRect.width()/(double)pageRect.height(); xSize = (int)((double)(3*pageRect.width()) * 1.0); ySize = (int)((double)(3*pageRect.height()) * .9); dxSize = (int)((double)(3*pageRect.width()) * .05); dySize = (int)((double)(3*pageRect.height()) * .05); xPages = 1+ (((int)sceneRect.width()) / xSize); yPages = 1+ (((int)sceneRect.height()) / ySize); if (SIEOptions::ScaleToSceneHeight(printingFlags)) { yPages = 1; xPages = 1+(int)( (double)yPages *sceneRatio); ySize = (int) ((double)scene->sceneRect().height()*.9); xSize = (int) ( (double)ySize * pageRectRatio); dySize = (int) (.05 * (double)scene->sceneRect().height()*.9); dxSize = (int) ( .05 *(double)ySize * pageRectRatio); } if (SIEOptions::ScaleToSceneWidth(printingFlags)) { xPages = 1; yPages = 1+(int)( (double)yPages / sceneRatio); } fWidth = 1.0* (double)pageRect.width(); fHeight = .9* (double)pageRect.height(); fHeightStep = .15* (double)pageRect.height(); fWidthStep = fHeightStep * sceneRatio; bool bNewPage = false; double fWidth2 = fWidth * .9; double fHeight2 = fHeight * .9; QPainterPath path; QRectF rectOuter; rectOuter.setLeft((double)pageRect.left()); rectOuter.setTop((double)pageRect.top()); rectOuter.setWidth(fWidth2); rectOuter.setHeight(fHeight2); path.addRect(rectOuter); QRectF rectInner(rectOuter); rectInner.setTopLeft(QPointF( rectInner.left()+fWidth2/20, rectInner.top()+fHeight2/20)); rectInner.setSize(QSizeF(fWidth2*.9,fHeight2*.9)); path.addRect(rectInner); painter.begin(&printer); QBrush shadowBrush = QBrush(QColor(192,192,192,64)); QBrush transparent = QBrush(QColor(192,192,192,16)); //QPen pen = QPen(QColor (65,65,65,192)); QPen pen = QPen(QColor (255,0,0,192)); QFont font = QFont("Droid Sans"); font.setBold(true); font.setPointSizeF(16.0); QFont fontb = QFont("Droid Sans"); fontb.setBold(false); fontb.setPointSizeF(11.0); //double fh = fHeightStep / yPages; //double fw = fWidthStep / xPages; double tinyRectXRatio = fWidthStep / scene->sceneRect().width(); double tinyRectYRatio = fHeightStep / scene->sceneRect().height(); int nCur = 0; int nMax = yPages*xPages; for (int y = 0; y < yPages; y++) { for (int x = 0; x < xPages; x++) { nCur = (y*xPages)+(x+1); if (bNewPage) printer.newPage(); else bNewPage = true; QRectF targetRect = QRectF((double)pageRect.left(),(double)pageRect.top(),fWidth2,fHeight2); QRectF sourceRect = QRectF ( (double)(x*xSize)+sceneRect.left()-(double)dxSize, (double)(y*ySize)+sceneRect.top()-(double)dySize, (double)(xSize)+2*(double)dxSize, (double)(ySize)+2*(double)dySize); QRectF targetRect2 = QRectF( (double)targetRect.left()+10, (double)targetRect.top()+ fHeight2+10, fWidthStep, fHeightStep); QRectF tinyRect; tinyRect.setLeft((sourceRect.left()-sceneRect.left()) * tinyRectXRatio+targetRect2.left()); tinyRect.setTop((sourceRect.top()-sceneRect.top()) * tinyRectYRatio+ targetRect2.top()); tinyRect.setWidth(sourceRect.width()*tinyRectXRatio); tinyRect.setHeight(sourceRect.height()*tinyRectYRatio); scene->render(&painter,targetRect, sourceRect); painter.setPen(pen); painter.setBrush(transparent); painter.drawRect(targetRect2); scene->render(&painter,targetRect2, scene->sceneRect(), Qt::IgnoreAspectRatio); painter.setPen(pen); painter.setBrush(shadowBrush); painter.drawPath(path); painter.drawRect(tinyRect); QFontMetricsF metrics(font); int nDelta = 0; painter.setFont(font); painter.setBrush(QBrush(QColor("black"))); painter.drawText( targetRect2.left()+fWidthStep+10, targetRect2.top()+metrics.height(), documentName); nDelta+= (int)metrics.height()+10; painter.setFont(fontb); QFontMetricsF metricsb(fontb); nDelta+= (int)metricsb.height(); QString txt = QString().sprintf("Folio [%d,%d] -- page %d of %d",x,y,nCur, nMax); painter.drawText( targetRect2.left()+fWidthStep+10, targetRect2.top()+nDelta, txt); } } painter.end(); }
int LuaPrinter2::newPage(lua_State *L) { QPrinter* obj = ValueInstaller<LuaPrinter2>::check( L, 1 ); lua_pushboolean( L, obj->newPage() ); return 1; }
void Matrix::print(const QString& fileName) { QPrinter printer; printer.setColorMode (QPrinter::GrayScale); if (!fileName.isEmpty()){ printer.setCreator("QtiPlot"); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); } else { QPrintDialog printDialog(&printer, applicationWindow()); if (printDialog.exec() != QDialog::Accepted) return; } printer.setFullPage( true ); QPainter p; if ( !p.begin(&printer ) ) return; // paint on printer int dpiy = printer.logicalDpiY(); const int margin = (int) ( (1/2.54)*dpiy ); // 1 cm margins if (d_view_type == ImageView){ p.drawImage (printer.pageRect(), d_matrix_model->renderImage()); return; } QHeaderView *vHeader = d_table_view->verticalHeader(); int rows = numRows(); int cols = numCols(); int height = margin; int i, vertHeaderWidth = vHeader->width(); int right = margin + vertHeaderWidth; // print header p.setFont(QFont()); QString header_label = d_matrix_model->headerData(0, Qt::Horizontal).toString(); QRect br = p.boundingRect(br, Qt::AlignCenter, header_label); p.drawLine(right, height, right, height+br.height()); QRect tr(br); for(i=0; i<cols; i++){ int w = d_table_view->columnWidth(i); tr.setTopLeft(QPoint(right,height)); tr.setWidth(w); tr.setHeight(br.height()); header_label = d_matrix_model->headerData(i, Qt::Horizontal).toString(); p.drawText(tr, Qt::AlignCenter, header_label,-1); right += w; p.drawLine(right, height, right, height+tr.height()); if (right >= printer.width()-2*margin ) break; } p.drawLine(margin + vertHeaderWidth, height, right-1, height);//first horizontal line height += tr.height(); p.drawLine(margin, height, right-1, height); // print table values for(i=0;i<rows;i++){ right = margin; QString cell_text = d_matrix_model->headerData(i, Qt::Horizontal).toString()+"\t"; tr = p.boundingRect(tr, Qt::AlignCenter, cell_text); p.drawLine(right, height, right, height+tr.height()); br.setTopLeft(QPoint(right,height)); br.setWidth(vertHeaderWidth); br.setHeight(tr.height()); p.drawText(br,Qt::AlignCenter,cell_text,-1); right += vertHeaderWidth; p.drawLine(right, height, right, height+tr.height()); for(int j=0; j<cols; j++){ int w = d_table_view->columnWidth (j); cell_text = text(i,j)+"\t"; tr = p.boundingRect(tr,Qt::AlignCenter,cell_text); br.setTopLeft(QPoint(right,height)); br.setWidth(w); br.setHeight(tr.height()); p.drawText(br, Qt::AlignCenter, cell_text, -1); right += w; p.drawLine(right, height, right, height+tr.height()); if (right >= printer.width()-2*margin ) break; } height += br.height(); p.drawLine(margin, height, right-1, height); if (height >= printer.height()-margin ){ printer.newPage(); height = margin; p.drawLine(margin, height, right, height); } } }
void Global::generatePDFs(QString dirname) { size_t pageCount = 0; for (size_t s = 0; s < getNumStudents(); s++) { Student& student = db()->getStudent(s); // Use the student name to form the file name for the repot QString clean = student.getStudentName(); // Convert all non alpha/num chars into an underscore for (QString::iterator i = clean.begin(); i != clean.end(); i++) { if (!i->isLetterOrNumber()) *i = '_'; } if (clean.length() == 0) { GINFODIALOG(QString("Cannot render PDF because student %1 does not have a name assigned").arg(s+1)); return; } QString pdfname (dirname + "/report-" + clean + ".pdf"); GDEBUG ("Generating PDF [%s] for student [%s]", qPrintable(pdfname), qPrintable(student.getStudentId())); QPrinter printer (QPrinter::HighResolution); printer.setOutputFormat (QPrinter::PdfFormat); printer.setOutputFileName (pdfname); printer.setPageSize(QPrinter::Letter); printer.setResolution(150); // DPI for the printing printer.setColorMode(QPrinter::GrayScale); QPainter painter; if (!painter.begin(&printer)) // Check for errors here GFATAL("Failed to do QPainter begin()"); // Can use this code to change the text color, but causes larger PDF files // since it must use a color output format instead. //QPen penColor(QColor("#000090")); // Change text to dark blue //painter.setPen(penColor); for (size_t p = 0; p < getNumPagesPerStudent(); p++) { pageCount++; // Add spaces at the end so the widget can resize into the reserved space without a re-layout Global::getStatusLabel()->setText(QString("Generating PDF for student %1 of %2, page %3 of %4 (%5 percent) "). arg(s+1).arg(getNumStudents()).arg(p+1).arg(getNumPagesPerStudent()).arg(rint(0.5+100.0*pageCount/(1.0*getNumPages())))); // Flush out Qt events so that the UI update occurs inside this handler Global::getQApplication()->processEvents(); GDEBUG ("Printing page %zu of %zu for report [%s]", p+1, getNumPagesPerStudent(), qPrintable(pdfname)); QPixmap pix = getPages()->getQPixmap(p+s*getNumPagesPerStudent()); // Scale the pixmap to fit the printer pix = pix.scaled(printer.pageRect().width(), printer.pageRect().height(), Qt::KeepAspectRatio); // Draw the pixmap to the printer painter.drawPixmap (0, 0, pix); // Print out the student details at the top of the page QString title = QString("Name: %1 ID: %2 Page: %3 of %4 Final Grade: %5 of %6").arg(student.getStudentName()).arg(student.getStudentId()).arg(p+1).arg(getNumPagesPerStudent()).arg(student.getTotal()).arg(db()->getTotalMaximum()); painter.drawText(0, 0, title); // Build up a results string to print onto the page QString grades ("Results:"); size_t pageTotal = 0; size_t pageMax = 0; for (size_t q = 0; q < getNumQuestions(); q++) { // See if the question is on this page GASSERT(Global::db()->getQuestionPage(q) != 0, "Cannot have page 0 assigned for question %zu", q); if (Global::db()->getQuestionPage(q) < 0) { GINFODIALOG(QString("Cannot render PDF because question %1 does not have a page assigned").arg(q+1)); return; } if (Global::db()->getQuestionPage(q) == ((int)p+1)) { if (student.getGrade(q) < 0) { GINFODIALOG(QString("Cannot render PDF for student [%1] because question %2 has no grade assigned").arg(student.getStudentName()).arg(q+1)); return; } pageTotal += student.getGrade(q); pageMax += Global::db()->getQuestionMaximum(q); grades += QString(" Q%1 = %2/%3").arg(q+1).arg(student.getGrade(q)).arg(Global::db()->getQuestionMaximum(q)); if (student.getFeedback(q) != "") grades += QString(" [%1]").arg(student.getFeedback(q)); } } grades += QString(" Totals = %1/%2").arg(pageTotal).arg(pageMax); if (pageMax == 0) grades = QString("No Results For This Page"); // Wrap the text to fit a bounding box that is the width of the page, align to the bottom of the page painter.drawText(0, 30, printer.pageRect().width(), printer.pageRect().height()-30, Qt::TextWordWrap | Qt::AlignBottom, grades); // Insert a new page except on the last one if (p < getNumPagesPerStudent()-1) if (!printer.newPage()) // Check for errors here GFATAL("Failed to do newPage() call"); } painter.end(); } Global::getStatusLabel()->setText(""); }