bool FaxGenerator::print( QPrinter& printer ) { QPainter p( &printer ); QImage image( m_img ); if ( ( image.width() > printer.width() ) || ( image.height() > printer.height() ) ) image = image.scaled( printer.width(), printer.height(), Qt::KeepAspectRatio, Qt::SmoothTransformation ); p.drawImage( 0, 0, image ); return true; }
int QPrinterProto::height() const { QPrinter *item = qscriptvalue_cast<QPrinter*>(thisObject()); if (item) return item->height(); return 0; }
void QwtPolarRenderer::renderTo( QwtPolarPlot *plot, QPrinter &printer ) const { int w = printer.width(); int h = printer.height(); QRectF rect( 0, 0, w, h ); double aspect = rect.width() / rect.height(); if ( ( aspect < 1.0 ) ) rect.setHeight( aspect * rect.width() ); QPainter p( &printer ); render( plot, &p, rect ); }
void PmChart::filePrint() { QPrinter printer; QString creator = QString("pmchart Version "); creator.append(pmGetConfig("PCP_VERSION")); printer.setCreator(creator); printer.setOrientation(QPrinter::Portrait); printer.setDocName("pmchart.pdf"); QPrintDialog print(&printer, (QWidget *)this); if (print.exec()) { QPainter qp(&printer); painter(&qp, printer.width(), printer.height(), false, false); } }
void MSPeaksWnd::handlePrintCurrentView( const QString& pdfname ) { // A4 := 210mm x 297mm (8.27 x 11.69 inch) QSizeF sizeMM( 260, 160 ); // 260x160mm int resolution = 300; const double mmToInch = 1.0 / 25.4; const QSizeF size = sizeMM * mmToInch * resolution; double margin_left = 0.2 /* inch */ * resolution; //double margin_right = ( 8.27 - 0.2 ) * resolution; //double margin_center = (margin_right - margin_left) / 2 + margin_left; QPrinter printer; printer.setColorMode( QPrinter::Color ); printer.setPaperSize( QPrinter::A4 ); printer.setFullPage( false ); printer.setOrientation( QPrinter::Landscape ); printer.setDocName( "QtPlatz MS Peaks" ); printer.setOutputFileName( pdfname ); printer.setResolution( resolution ); //-------------------- QPainter painter( &printer ); int n = 0; for ( auto& plot: plots_ ) { QRectF boundingRect; QRectF drawRect( margin_left, 0.0, printer.width() / 2.0, printer.height() ); if ( n++ & 01 ) { drawRect.moveLeft( printer.width() / 2.0 ); painter.drawText( drawRect, Qt::TextWordWrap, "Relationship between time and flight length", &boundingRect ); } else { painter.drawText( drawRect, Qt::TextWordWrap, "Relationship between time and m/z", &boundingRect ); } QwtPlotRenderer renderer; renderer.setDiscardFlag( QwtPlotRenderer::DiscardCanvasBackground, true ); renderer.setDiscardFlag( QwtPlotRenderer::DiscardCanvasFrame, true ); renderer.setDiscardFlag( QwtPlotRenderer::DiscardBackground, true ); drawRect.setTop( boundingRect.bottom() ); drawRect.setHeight( size.height() ); drawRect.setWidth( size.width() / 2 ); renderer.render( plot.get(), &painter, drawRect ); // render plot } }
void AccountsView::print( QPrinter &printer, QPrintDialog &printDialog ) { //kDebug(planDbg()); uint top, left, bottom, right; printer.margins( &top, &left, &bottom, &right ); //kDebug(planDbg())<<m.width()<<"x"<<m.height()<<" :"<<top<<","<<left<<","<<bottom<<","<<right<<" :"<<size(); QPainter p; p.begin( &printer ); p.setViewport( left, top, printer.width() - left - right, printer.height() - top - bottom ); p.setClipRect( left, top, printer.width() - left - right, printer.height() - top - bottom ); QRect preg = p.clipRegion().boundingRect(); //kDebug(planDbg())<<"p="<<preg; //p.drawRect(preg.x(), preg.y(), preg.width()-1, preg.height()-1); double scale = qMin( ( double ) preg.width() / ( double ) size().width(), ( double ) preg.height() / ( double ) ( size().height() ) ); //kDebug(planDbg())<<"scale="<<scale; if ( scale < 1.0 ) { p.scale( scale, scale ); } QPixmap labelPixmap = QPixmap::grabWidget( m_label ); p.drawPixmap( m_label->pos(), labelPixmap ); p.translate( 0, m_label->size().height() ); m_dlv->paintContents( &p ); 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 DetailledPrintStyle::print( const KABC::Addressee::List &contacts, PrintProgress *progress ) { mPrintProgress = progress; progress->addMessage( i18n( "Setting up fonts and colors" ) ); progress->setProgress( 0 ); bool useKDEFonts; QFont font; QColor foreColor = Qt::black; QColor headerColor = Qt::white; bool useHeaderColor = true; QColor backColor = Qt::black; bool useBGColor; // save, always available defaults: QFont header = QFont("Helvetica", 12, QFont::Normal); QFont headlines = QFont("Helvetica", 12, QFont::Normal, true); QFont body = QFont("Helvetica", 12, QFont::Normal); QFont fixed = QFont("Courier", 12, QFont::Normal); QFont comment = QFont("Helvetica", 10, QFont::Normal); // store the configuration settings: KConfigGroup config = KGlobal::config()->group(ConfigSectionName); useKDEFonts = mPageAppearance->cbStandardFonts->isChecked(); config.writeEntry( UseKDEFonts, useKDEFonts ); // read the font and color selections from the wizard pages: useBGColor=mPageAppearance->cbBackgroundColor->isChecked(); config.writeEntry( ColoredContactHeaders, useBGColor ); // use colored contact headers, otherwise use plain black and white): if ( useBGColor ) { headerColor = mPageAppearance->kcbHeaderTextColor->color(); backColor = mPageAppearance->kcbHeaderBGColor->color(); config.writeEntry( ContactHeaderForeColor, headerColor ); config.writeEntry( ContactHeaderBGColor, backColor ); } if ( mPageAppearance->cbStandardFonts->isChecked() ) { QFont standard = KGlobalSettings::generalFont(); header = standard; headlines = standard; body = standard; fixed = KGlobalSettings::fixedFont(); comment = standard; } else { header.setFamily( mPageAppearance->kfcHeaderFont->currentText() ); header.setPointSize( mPageAppearance->kisbHeaderFontSize->value() ); config.writeEntry( HeaderFont, header ); // headlines: headlines.setFamily( mPageAppearance->kfcHeadlineFont->currentText() ); headlines.setPointSize( mPageAppearance->kisbHeadlineFontSize->value() ); config.writeEntry( HeadlinesFont, headlines ); // body: body.setFamily( mPageAppearance->kfcBodyFont->currentText() ); body.setPointSize( mPageAppearance->kisbBodyFontSize->value() ); config.writeEntry( BodyFont, body ); // details: comment.setFamily( mPageAppearance->kfcDetailsFont->currentText() ); comment.setPointSize( mPageAppearance->kisbDetailsFontSize->value() ); config.writeEntry( DetailsFont, comment ); // fixed: fixed.setFamily( mPageAppearance->kfcFixedFont->currentText() ); fixed.setPointSize( mPageAppearance->kisbFixedFontSize->value() ); config.writeEntry( FixedFont, fixed ); } mPainter = new KABEntryPainter; mPainter->setForegroundColor( foreColor ); mPainter->setHeaderColor( headerColor ); mPainter->setBackgroundColor( backColor ); mPainter->setUseHeaderColor( useHeaderColor ); mPainter->setHeaderFont( header ); mPainter->setHeadLineFont( headlines ); mPainter->setBodyFont( body ); mPainter->setFixedFont( fixed ); mPainter->setCommentFont( comment ); // Printing "Work Address:" / "Telephones:" headlines adds // no interesting information and just take space. // So I added this setter, but I leave it true by default because // otherwise the indenting looks a bit weird -- ## TODO. mPainter->setPrintHeadLines( true ); // TODO a checkbox for it QPrinter *printer = wizard()->printer(); progress->addMessage( i18n( "Setting up margins and spacing" ) ); int marginTop = 0, marginLeft = 64, // to allow stapling, need refinement with two-side prints marginRight = 0, marginBottom = 0; register int left, top, width, height; QPainter painter( printer ); left = qMax( printer->pageRect().left() - printer->paperRect().left(), marginLeft ); top = qMax( printer->pageRect().top() - printer->paperRect().top(), marginTop ); width = printer->width() - left - qMax( printer->paperRect().right() - printer->pageRect().right(), marginRight ); height = printer->height() - top - qMax( printer->paperRect().bottom() - printer->pageRect().bottom(), marginBottom ); printer->setFullPage( true ); // use whole page painter.setViewport( left, top, width, height ); progress->addMessage( i18n( "Printing" ) ); printEntries( contacts, printer, &painter, QRect( 0, 0, printer->width(), printer->height() ) ); progress->addMessage( i18n( "Done" ) ); config.sync(); }
void Matrix::exportVector(const QString& fileName, int res, bool color, bool keepAspect, QPrinter::PageSize pageSize) { if (d_view_type != ImageView) return; if ( fileName.isEmpty() ){ QMessageBox::critical(this, tr("QtiPlot - Error"), tr("Please provide a valid file name!")); return; } QPrinter printer; printer.setCreator("QtiPlot"); printer.setFullPage(true); if (res) printer.setResolution(res); printer.setOutputFileName(fileName); if (fileName.contains(".eps")) printer.setOutputFormat(QPrinter::PostScriptFormat); if (color) printer.setColorMode(QPrinter::Color); else printer.setColorMode(QPrinter::GrayScale); int cols = numCols(); int rows = numRows(); QRect rect = QRect(0, 0, cols, rows); if (pageSize == QPrinter::Custom) printer.setPageSize(Graph::minPageSize(printer, rect)); else printer.setPageSize(pageSize); double aspect = (double)cols/(double)rows; if (aspect < 1) printer.setOrientation(QPrinter::Portrait); else printer.setOrientation(QPrinter::Landscape); if (keepAspect){// export should preserve aspect ratio double page_aspect = double(printer.width())/double(printer.height()); if (page_aspect > aspect){ int margin = (int) ((0.1/2.54)*printer.logicalDpiY()); // 1 mm margins int height = printer.height() - 2*margin; int width = int(height*aspect); int x = (printer.width()- width)/2; rect = QRect(x, margin, width, height); } else if (aspect >= page_aspect){ int margin = (int) ((0.1/2.54)*printer.logicalDpiX()); // 1 mm margins int width = printer.width() - 2*margin; int height = int(width/aspect); int y = (printer.height()- height)/2; rect = QRect(margin, y, width, height); } } else { int x_margin = (int) ((0.1/2.54)*printer.logicalDpiX()); // 1 mm margins int y_margin = (int) ((0.1/2.54)*printer.logicalDpiY()); // 1 mm margins int width = printer.width() - 2*x_margin; int height = printer.height() - 2*y_margin; rect = QRect(x_margin, y_margin, width, height); } QPainter paint(&printer); paint.drawImage(rect, d_matrix_model->renderImage()); paint.end(); }
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); } } }
bool Screenshot::SaveScreenShotToPdf(QPixmap screenShot, QString fileName, QPrinter::Orientation orientation, QPrinter::PageSize pageSize, QPrinter::ColorMode colorMode) { QByteArray encodedString; QTextCodec* codec = QTextCodec::codecForName("Windows-1251");; QString appendText, titleMessage; Qt::WindowFlags flag = 0; flag |= Qt::Tool;// Удаление значка с taskbar и кнопок максимум, минимум размера окна flag |= Qt::WindowStaysOnTopHint;// Всегда поверх других flag |= Qt::FramelessWindowHint; flag |= Qt::WindowTitleHint; QDateTime date_time = QDateTime::currentDateTime(); QMessageBox msgBox; msgBox.setWindowTitle(date_time.toString() + " " + QApplication::applicationName() + ":" + QApplication::applicationVersion()); msgBox.setWindowFlags(flag); // Step 1. Убедится, что screenshot не пустой if(screenShot.isNull()){ encodedString = "Сообщение"; titleMessage = codec->toUnicode(encodedString); encodedString = "В буфере обмена ничего нет"; msgBox.setText(titleMessage); // Заголовок сообщения msgBox.setIcon(QMessageBox::Information); // Тип иконки сообщения msgBox.setInformativeText(appendText); // Основное сообщение Message Box msgBox.setDefaultButton(QMessageBox::Save); // На какой кнопке фокусироваться по умолчанию msgBox.exec(); return 0; }//if // Step 2. Убедится, что fileName не пустой if (fileName.isEmpty()){ encodedString = "Сообщение"; titleMessage = codec->toUnicode(encodedString); encodedString = "Имя файла не указано"; appendText = codec->toUnicode(encodedString); msgBox.setText(titleMessage); // Заголовок сообщения msgBox.setIcon(QMessageBox::Information); // Тип иконки сообщения msgBox.setInformativeText(appendText); // Основное сообщение Message Box msgBox.setDefaultButton(QMessageBox::Save); // На какой кнопке фокусироваться по умолчанию msgBox.exec(); return 0; }//if // Расширение файла fileName += ".pdf"; // Step 3. Проверка существования файла. Если файл существует, то решить, нужно ли его перезаписывать if (QFile::exists(fileName)){ encodedString = "Процедура сохранения"; titleMessage = codec->toUnicode(encodedString); encodedString = " \nуже существует. Заменить?"; appendText = codec->toUnicode(encodedString); msgBox.setText(titleMessage); // Заголовок сообщения msgBox.setIcon(QMessageBox::Information); // Тип иконки сообщения msgBox.setInformativeText(fileName + appendText); // Основное сообщение Message Box msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel); // Добавление реагирования на софт клавиши msgBox.setDefaultButton(QMessageBox::Save); // На какой кнопке фокусироваться по умолчанию int ret = msgBox.exec(); // Запускаем QMessageBox. После выполнения, в ret будет лежать значение кнопки, на которую нажали - это необходимо для дальнейшей обработки событий if(ret == QMessageBox::Cancel) return 0; }//if // Step 4. Объявление экземпляра класса QPrinter и определение его настроек QPrinter printer; printer.setOutputFileName(fileName); printer.setFullPage(true); printer.setOutputFormat(QPrinter::PdfFormat); printer.setPaperSize(pageSize); printer.setOrientation(orientation); printer.setColorMode(colorMode); printer.newPage(); // Step 5. Проверка на возможные ошибки QPainter painter; if (! painter.begin(&printer)){ encodedString = "Ошибка открытия файла"; titleMessage = codec->toUnicode(encodedString); encodedString = "Убедитесь, что запись в файл разрешена"; appendText = codec->toUnicode(encodedString); msgBox.setText(titleMessage); // Заголовок сообщения msgBox.setIcon(QMessageBox::Warning); // Тип иконки сообщения msgBox.setInformativeText(appendText); // Основное сообщение Message Box msgBox.setDefaultButton(QMessageBox::Save); // На какой кнопке фокусироваться по умолчанию msgBox.show(); return 0; }//if /* if (! printer.newPage()){ encodedString = "Ошибка при добавлении новой страницы"; titleMessage = codec->toUnicode(encodedString); encodedString = "Убедитесь, что на диске есть место"; appendText = codec->toUnicode(encodedString); msgBox.setText(titleMessage); // Заголовок сообщения msgBox.setIcon(QMessageBox::Warning); // Тип иконки сообщения msgBox.setInformativeText(appendText); // Основное сообщение Message Box msgBox.setDefaultButton(QMessageBox::Save); // На какой кнопке фокусироваться по умолчанию msgBox.show(); return 0; }//if */ // Step 6. Сохранение painter.drawPixmap(0, 0, printer.width(), printer.height(), screenShot); painter.end(); /* QFile file("c://test.txt"); file.open(QIODevice::Append | QIODevice::Text); QTextStream out(&file); out << temp; out << "\n"; file.close(); */ return 1; }
void inputRZImpl::print() { QString fname = EGSdir + EGSfileName; QPrinter* printer = new QPrinter; printer->setPageSize( QPrinter::Letter ); const int Margin = 20; const int MarginY = 30; int pageNo = 1; QPrintDialog pdialog(printer,this); if ( pdialog.exec()) { cout << "let's print !!!" << endl; QPainter paint( printer ); //if( !paint.begin( printer ) ) // paint on printer // return; static const char *fonts[] = { "Helvetica", "Courier", "Times", 0 }; static int sizes[] = { 10, 12, 18, 24, 36, 0 }; int yPos = 0; QFont fontNormal( fonts[1], sizes[0] ); QFont fontBold( fonts[0], sizes[0] ); fontBold.setWeight( QFont::Black); paint.setFont( fontBold ); QFontMetrics fmBold = paint.fontMetrics(); paint.setFont( fontNormal ); QFontMetrics fm = paint.fontMetrics(); //qt3to4 -- BW //Q3PaintDeviceMetrics metrics( printer ); // need width/height QFile fi( fname ); //qt3to4 -- BW //Q3TextStream ts( &fi ); QTextStream ts( &fi ); QString t; int StepsPerPage = 500; int LinesPerPage = (printer->height() - 2* MarginY) / fm.lineSpacing(); if ( fi.open( QIODevice::ReadOnly ) ) { int NumOfPages = 1 + TotalTextLines( fname ) / LinesPerPage; int totalSteps = StepsPerPage * NumOfPages; QString msg( "Printing (page " ); msg += QString::number( pageNo ); msg += ")..."; //qt3to4 -- BW //Q3ProgressDialog* dialog = new Q3ProgressDialog(msg, "Cancel", // totalSteps, this, "progress", true); QProgressDialog* dialog = new QProgressDialog(msg, "Cancel",0,totalSteps); //dialog->setTotalSteps( totalSteps ); //dialog->setProgress( 0 ); dialog->setValue(0); dialog->setMinimumDuration( 0 ); int progress_count = 0; QString gui = "EGSnrc GUI for RZ Geometries: " + EGSfileName; QDate currDate = QDate::currentDate(); QString date = currDate.toString ( "dd.MM.yyyy" ); paint.setFont( fontBold ); paint.drawText( Margin, 0, printer->width() - 2*Margin, fmBold.lineSpacing(), Qt::AlignLeft | Qt::RichText, gui ); paint.drawText( Margin, 0, printer->width() - 2*Margin, fmBold.lineSpacing(), Qt::AlignRight, date ); paint.drawLine( Margin, MarginY - 10, printer->width() - Margin, MarginY - 10 ); paint.drawLine( Margin, printer->height() - MarginY + 10, printer->width() - Margin, printer->height() - MarginY + 10 ); paint.drawText( Margin, printer->height() - fmBold.lineSpacing(), printer->width(), fmBold.lineSpacing(), Qt::AlignHCenter, QString::number( pageNo ) ); paint.setFont( fontNormal ); do { progress_count++; qApp->processEvents(); if ( dialog->wasCanceled() ) dialog->close(); t = ts.readLine(); if ( MarginY + yPos + fm.lineSpacing() > printer->height() - MarginY ) { do{ //dialog->setProgress( ++progress_count ); dialog->setValue(++progress_count ); }while ( progress_count < StepsPerPage*pageNo ); msg = "Printing (page " + QString::number( ++pageNo ) + ")..."; dialog->setLabelText( msg ); printer->newPage(); // no more room on this page yPos = 0; // back to top of page paint.setFont( fontBold ); paint.drawText( Margin, 0, printer->width() - 2*Margin, fmBold.lineSpacing(), Qt::AlignLeft | Qt::RichText, gui ); paint.drawText( Margin, 0, printer->width() - 2*Margin, fmBold.lineSpacing(), Qt::AlignRight, date ); paint.drawLine( Margin, MarginY - 10, printer->width() - Margin, MarginY - 10 ); paint.drawLine( Margin, printer->height() - MarginY + 10, printer->width() - Margin, printer->height() - MarginY + 10 ); paint.drawText( Margin, printer->height() - fmBold.lineSpacing(), printer->width(), fmBold.lineSpacing(), Qt::AlignHCenter, QString::number( pageNo ) ); paint.setFont( fontNormal ); } paint.drawText( Margin, MarginY + yPos, printer->width(), fm.lineSpacing(), Qt::TextExpandTabs | Qt::TextDontClip, t ); yPos = yPos + fm.lineSpacing(); dialog->setValue( progress_count ); //qt3to4 -- BW //} while ( !ts.eof() ); } while ( !ts.atEnd() ); do{ dialog->setValue( ++progress_count ); }while ( progress_count < totalSteps ); dialog->setValue( totalSteps ); zap(dialog); } else { QMessageBox::critical( 0, tr("Error printing "), tr("Couldn't open file %1").arg(fname), tr("Quit") ); } fi.close(); } else { QMessageBox::information( this, "Printing status", "Printing aborted"); } delete printer; }