Esempio n. 1
0
void MultiLayer::exportVector(const QString &fileName, int res, bool color,
                              bool keepAspect, QPrinter::PageSize pageSize,
                              QPrinter::Orientation orientation) {
  Q_UNUSED(res);
  if (fileName.isEmpty()) {
    QMessageBox::critical(this, tr("Error"),
                          tr("Please provide a valid file name!"));
    return;
  }

  QPrinter printer;
  printer.setDocName(this->name());
  printer.setCreator("AlphaPlot");
  printer.setFullPage(true);
  printer.setOutputFileName(fileName);
  if (fileName.contains(".eps"))
    printer.setOutputFormat(QPrinter::PostScriptFormat);

  if (color)
    printer.setColorMode(QPrinter::Color);
  else
    printer.setColorMode(QPrinter::GrayScale);

  if (pageSize == QPrinter::Custom)
    printer.setPaperSize(canvas->size(), QPrinter::Point);
  else {
    printer.setOrientation(orientation);
    printer.setPaperSize(pageSize);
  }

  exportPainter(printer, keepAspect);
}
Esempio n. 2
0
void MainWindow::showPrintDialog() {
    QPrinter printer;
    printer.setDocName("Maze");
    QPrintDialog dialog(&printer);
    if (dialog.exec() == QDialog::Accepted)
        print(printer);
}
Esempio n. 3
0
/**
 * Methode permettant d'imprimer un document
 */
void ValidDocument::print(){

    QWebView webView;
    QPrinter printer ;

    printer.setPageSize(QPrinter::A4);
    printer.setFullPage(true);
    QString type=(docType==Document::Facture)?QObject::trUtf8("Facture"):QObject::trUtf8("Devis");
    printer.setDocName(type+"_"+QString::number(id) );
    printer.setCreator(QObject::trUtf8("QFacturation"));
    printer.setOutputFormat(QPrinter::NativeFormat);

    webView.setHtml(view);
    webView.show();
    QPrintDialog printDialog(&printer);
    if(printDialog.exec() == QDialog::Accepted) {
        qDebug("Ne fonctionne pas sous windows")<<" Hack ....";

        #if defined(Q_WS_WIN)
            QTextDocument text;
            text.setHtml(view);
            text.print(&printer);
        #endif
        #if defined(Q_WS_QWS)
            webView.print(&printer);
        #endif
        #if defined(Q_WS_X11)
            webView.print(&printer);
        #endif
    }

}
Esempio n. 4
0
void ProRataGraphPane::print()
{
	if ( !(qtwGraphTab->currentWidget()) )
	{
		return ;
	}

/*
	QString qsSaveFileName = QFileDialog::getSaveFileName(
                    this,
                    "ProRata - Choose a file name to save",
                    ".",
                    "Images (*.png *.jpg)");

	if (qsSaveFileName.isEmpty())
	{
		return;
	}
	*/

	ProRataGraph *clickedGraph = (ProRataGraph *)qtwGraphTab->currentWidget();

	QPrinter printer;
    //printer.setOutputToFile(true);
    //printer.setOutputFileName(qsSaveFileName);
    printer.setDocName(QString("ProRata_Graph"));

    printer.setCreator("ProRata Graph");
    printer.setOrientation(QPrinter::Landscape);

	QPrintDialog dialog(&printer);
    if ( dialog.exec() )
    {
		QwtPlotPrintFilter filter;
		if ( printer.colorMode() == QPrinter::GrayScale )
        {
            filter.setOptions(QwtPlotPrintFilter::PrintAll 
                & ~QwtPlotPrintFilter::PrintCanvasBackground);
        }
		clickedGraph->print( printer, filter );
	}
	
	

/*
	//QPixmap *qpPic = new QPixmap( qsSaveFileName );
	//QPainter * qpntrPainter = new QPainter( qpPic );
	QPixmap qpPic( qsSaveFileName );
	qpPic.save( qsSaveFileName );
	//QPainter * qpntrPainter = new QPainter( qpPic );

	//clickedGraph->print( qpntrPainter, clickedGraph->frameGeometry() );
	clickedGraph->print( qpPic );
*/
	//QMessageBox::information( this, "Printing done.", QString( "Saved \"") + qsSaveFileName + QString( "\"" ) );

}
Esempio n. 5
0
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);
    }
}
Esempio n. 6
0
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
    }
}
Esempio n. 7
0
/*
*Function: Print
*Inputs:none
*Outputs:none
*Returns:none
*/
void GraphPaneData::Print()
{
	IT_IT("GraphPaneData::Print");
	
	QPrinter prt; 
	prt.setDocName(tr("Pen Trace"));
	prt.setCreator(tr(SYSTEM_NAME));
	prt.setOrientation(QPrinter::Landscape);
	prt.setOutputFileName("~out.ps");
	prt.setOutputToFile(false);
	//
	if(prt.setup(this))
	{
		//
		// Handle the case of no printer being selected
		//
		if(!prt.printerName().isEmpty())
		{
			QPainter p;
			p.begin(&prt);
			QPaintDeviceMetrics metrics(p.device());
			//
			int dpix = metrics.logicalDpiX() ; //  inch border
			int dpiy = metrics.logicalDpiY() ;
			//
			QRect body(dpix, dpiy,	metrics.width()  -  dpix*6,	metrics.height() -  dpiy*2);
			TheGraph.Plot(p,body,Qt::white);
			//
			QFont font("times", 8); 
			p.setFont(font);
			//
			p.drawText( body.left() ,body.top(), Title);
			//
			p.end();
			//
		}
		else
		{
			QMessageBox::information(this,tr("Print Graph Error"),tr("No Printer Selected!"));
		};
	};
};
Esempio n. 8
0
void PlotWindow::printPlot()
{
  QPrinter printer;

  QString docName = mpPlot->title().text();

  if (docName.isEmpty())
    {
      //docName.replace (QRegExp (QString::fromLatin1 ("\n")), tr (" -- "));
      docName = QString::fromLatin1("A plot of selected COPASI output");
      printer.setDocName(docName);
    }

  printer.setCreator("COPASI");
  printer.setOrientation(QPrinter::Landscape);

  QPrintDialog dialog(&printer);

  if (dialog.exec())
    mpPlot->print(printer, PrintFilter());
}
Esempio n. 9
0
/**
   Impression du livre des recettes
  */
void DialogInvoiceList::on_pushButton_print_clicked() {
	//Si on est pas connecte on sort
	if((!m_data->isConnected()) || (ui->tableWidget_Invoices->rowCount()<=0) )return;

	QPrinter printer;
	printer.setPageSize(QPrinter::A4);
	QString name = tr("LIVRERECETTES-")+ m_date.toString(tr("yyyyMM")) ;
	printer.setOutputFileName( name + ".pdf");
	printer.setDocName( name );
	printer.setCreator("mcercle");

	DialogPrintChoice *m_DialogPrintChoice = new DialogPrintChoice(&printer);
	m_DialogPrintChoice->setModal(true);
	m_DialogPrintChoice->exec();

	if(m_DialogPrintChoice->result() == QDialog::Accepted) {
		QWidget fenetre;
		QPrintPreviewDialog m_PreviewDialog(&printer,  &fenetre, Qt::Widget | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint);
		connect(&m_PreviewDialog, SIGNAL(paintRequested(QPrinter *)), this, SLOT(on_paintPrinter(QPrinter *)));
		m_PreviewDialog.setWindowState(Qt::WindowMaximized);
		m_PreviewDialog.exec();
	}
Esempio n. 10
0
void WebTab::printFrame()
{
    if (page()->isOnRekonqPage())
    {
        // trigger print part action instead of ours..
        KParts::ReadOnlyPart *p = part();
        if (p)
        {
            KParts::BrowserExtension *ext = p->browserExtension();
            if (ext)
            {
                KParts::BrowserExtension::ActionSlotMap *actionSlotMap = KParts::BrowserExtension::actionSlotMapPtr();

                connect(this, SIGNAL(triggerPartPrint()), ext, actionSlotMap->value("print"));
                emit triggerPartPrint();

                return;
            }
        }
    }

    QWebFrame *printFrame = page()->currentFrame();
    if (printFrame == 0)
    {
        printFrame = page()->mainFrame();
    }

    QPrinter printer;
    printer.setDocName(printFrame->title());
    QPrintDialog *printDialog = KdePrint::createPrintDialog(&printer, this);

    if (printDialog) //check if the Dialog was created
    {
        if (printDialog->exec())
            printFrame->print(&printer);

        delete printDialog;
    }
}
Esempio n. 11
0
void Clamp::print() {
#if 1
	QPrinter printer;
#else
	QPrinter printer(QPrinter::HighResolution);
#if QT_VERSION < 0x040000
	printer.setOutputToFile(true);
	printer.setOutputFileName("/tmp/FI.ps");
	printer.setColorMode(QPrinter::Color);
#else
	printer.setOutputFileName("/tmp/FI.pdf");
#endif
#endif

	QString docName = splot->title().text();
	if (!docName.isEmpty()) {
		docName.replace(QRegExp(QString::fromLatin1("\n")), tr(" -- "));
		printer.setDocName(docName);
	}

	printer.setCreator("RTXI");
	printer.setOrientation(QPrinter::Landscape);

#if QT_VERSION >= 0x040000
	QPrintDialog dialog(&printer);
	if ( dialog.exec() ) {
#else
		if (printer.setup())	{
#endif 
/*
		RTXIPrintFilter filter;
		if (printer.colorMode() == QPrinter::GrayScale) {
		 int options = QwtPlotPrintFilter::PrintAll;
		 filter.setOptions(options);
		 filter.color(QColor(29, 100, 141),
			  QwtPlotPrintFilter::CanvasBackground);
		 filter.color(Qt::white, QwtPlotPrintFilter::CurveSymbol);
		}
*/
//	splot->print(printer, filter);
	QwtPlotRenderer *renderer = new QwtPlotRenderer;
	renderer->renderTo(splot, printer);
	}
}

void Clamp::exportSVG() {
	QString fileName = "FI.svg";

std::cout<<"flag 0"<<std::endl;

#if QT_VERSION < 0x040000
std::cout<<"flag 1"<<std::endl;

#ifndef QT_NO_FILEDIALOG
std::cout<<"flag 2"<<std::endl;
	fileName = QFileDialog::getSaveFileName("FI.svg", "SVG Documents (*.svg)",	this);
#endif
std::cout<<"flag 3"<<std::endl;
	if (!fileName.isEmpty()) {
		// enable workaround for Qt3 misalignments
		QwtPainter::setSVGMode(true);
		QPicture picture;
		QPainter p(&picture);
//		splot->print(&p, QRect(0, 0, 800, 600));
		QwtPlotRenderer *renderer = new QwtPlotRenderer;
		renderer->renderTo(splot, p, QRect(0, 0, 800, 600));
		p.end();
		picture.save(fileName, "svg");
	}

#elif QT_VERSION >= 0x040300
std::cout<<"flag 4"<<std::endl;
#ifdef QT_SVG_LIB
std::cout<<"flag 5"<<std::endl;
#ifndef QT_NO_FILEDIALOG
std::cout<<"flag 6"<<std::endl;
		fileName = QFileDialog::getSaveFileName(this, "Export File Name", 
		                                        QString(), "SVG Documents (*.svg)");
#endif
std::cout<<"flag 7"<<std::endl;
	if ( !fileName.isEmpty() ) {
		QSvgGenerator generator;
		generator.setFileName(fileName);
		generator.setSize(QSize(800, 600));
//		splot->print(generator);
	}
#endif
#endif
}
Esempio n. 12
0
void CustRegister::printRegister()
{
    QDate       theDate;
    QPrinter    prn;
    QPainter    p;
    QRect       rect;
    ADBTable    cust;
    ADBTable    cont;
    ADB         DB;
    QString     tmpSt;
    char        tStr[1024];
    int         yPos;
    int         pageNo = 1;
    float       Balance = 0.00;
    float       EndingBalance;
    CustomersDB CDB;
    AddressesDB addrDB;
    
    CDB.get(myCustID);
    addrDB.get(REF_CUSTOMER, myCustID, "Billing");
    
    theDate = QDate::currentDate();
    
    // prn.setPrintProgram("ghostview");
    prn.setPrinterName("PostScript");
    // prn.setOutputFileName("/home/marc/test.ps");
    // prn.setOutputToFile(TRUE);
    prn.setPageSize(QPrinter::Letter);
    
    prn.setDocName("Register Listing");
    prn.setCreator("Blarg! Online Services, Inc.");
    
    if (!prn.setup()) return;
    
    p.begin(&prn);
    
    EndingBalance = DB.sumFloat("select SUM(Amount) from AcctsRecv where CustomerID = %ld", myCustID);
    
    // Put the Blarg header and contact information on the page.
    printHeader(&p, &CDB, &addrDB, EndingBalance);
    
    // Put the register header on the page.
    registerHeader(&p);
    
    // Now, get the register information from the database.
    DB.query("select TransDate, DueDate, LoginID, Memo, Amount from AcctsRecv where CustomerID = %ld order by TransDate, LoginID", myCustID);
    
    yPos = 165;
    p.setFont(QFont("courier", 8, QFont::Normal));
    while (DB.getrow()) {
        int Lines = (int) (strlen(DB.curRow["Memo"]) / 52) + 1;
        int RowHeight = 15 * Lines;
        
        // Check to see if we have enough room on the page left for this
        // line.
        if (yPos+RowHeight >= 740) {
            printFooter(&p, pageNo++);
            prn.newPage();
            printHeader(&p, &CDB, &addrDB, EndingBalance);
            registerHeader(&p);
            yPos = 165;
            p.setFont(QFont("courier", 8, QFont::Normal));
        } 
    
        // The transaction date.
        rect.setCoords(20, yPos, 79, yPos + RowHeight);
        p.drawRect(rect);
        p.drawText(rect, AlignVCenter|AlignHCenter, DB.curRow["TransDate"]);
        
        // The Due Date
        rect.setCoords(80, yPos, 139, yPos + RowHeight);
        p.drawRect(rect);
        p.drawText(rect, AlignVCenter|AlignHCenter, DB.curRow["DueDate"]);
        
        // The Login ID
        rect.setCoords(140, yPos, 199, yPos + RowHeight);
        p.drawRect(rect);
        p.drawText(rect, AlignVCenter|AlignHCenter, DB.curRow["LoginID"]);
        
        // The description...
        rect.setCoords(200, yPos, 419, yPos + RowHeight);
        p.drawRect(rect);
        rect.setCoords(203, yPos, 419, yPos + RowHeight);
        p.drawText(rect, WordBreak|AlignLeft|AlignVCenter, DB.curRow["Memo"]);
        
        // The amount.
        rect.setCoords(420, yPos, 479, yPos + RowHeight);
        p.drawRect(rect);
        p.drawText(rect, AlignRight|AlignVCenter, DB.curRow["Amount"]);
        
        // The balance.
        Balance += atof(DB.curRow["Amount"]);
        sprintf(tStr, "%.2f", Balance);
        if (Balance == 0.0) strcpy(tStr, "0.00");
        rect.setCoords(480, yPos, 539, yPos + RowHeight);
        p.drawRect(rect);
        p.drawText(rect, AlignRight|AlignVCenter, tStr);
        
        yPos += RowHeight;
    }

    // Put the footer on the page.
    printFooter(&p, pageNo);
    
    // prn.newPage();
    
    // p.drawText(300, 600, "Page 2");
    
    p.end();
}
Esempio n. 13
0
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:)
Esempio n. 14
0
/*!
  Render a plot to a file

  Supported formats are:

  - pdf\n
  - ps\n
  - svg\n
  - all image formats supported by Qt, see QImageWriter::supportedImageFormats()

  \param plot Plot widget
  \param fileName Path of the file, where the document will be stored
  \param format Format for the document
  \param sizeMM Size for the document in millimeters.
  \param resolution Resolution in dots per Inch (dpi)

  \sa renderTo(), render(), QwtPainter::setRoundingAlignment()
*/
void QwtPolarRenderer::renderDocument( QwtPolarPlot *plot,
    const QString &fileName, const QString &format,
    const QSizeF &sizeMM, int resolution )
{
    if ( plot == NULL || sizeMM.isEmpty() || resolution <= 0 )
        return;

    QString title = plot->title().text();
    if ( title.isEmpty() )
        title = "Plot Document";

    const double mmToInch = 1.0 / 25.4;
    const QSizeF size = sizeMM * mmToInch * resolution;

    const QRectF documentRect( 0.0, 0.0, size.width(), size.height() );

    const QString fmt = format.toLower();
    if ( format == "pdf" || format == "ps" )
    {
        QPrinter printer;
        printer.setFullPage( true );
        printer.setPaperSize( sizeMM, QPrinter::Millimeter );
        printer.setDocName( title );
        printer.setOutputFileName( fileName );
        printer.setOutputFormat( ( format == "pdf" )
            ? QPrinter::PdfFormat : QPrinter::PostScriptFormat );
        printer.setResolution( resolution );

        QPainter painter( &printer );
        render( plot, &painter, documentRect );
    }
#ifndef QWT_NO_POLAR_SVG
#ifdef QT_SVG_LIB
#if QT_VERSION >= 0x040500
    else if ( format == "svg" )
    {
        QSvgGenerator generator;
        generator.setTitle( title );
        generator.setFileName( fileName );
        generator.setResolution( resolution );
        generator.setViewBox( documentRect );

        QPainter painter( &generator );
        render( plot, &painter, documentRect );
    }
#endif
#endif
#endif
    else
    {
        if ( QImageWriter::supportedImageFormats().indexOf(
            format.toLatin1() ) >= 0 )
        {
            const QRect imageRect = documentRect.toRect();
            const int dotsPerMeter = qRound( resolution * mmToInch * 1000.0 );

            QImage image( imageRect.size(), QImage::Format_ARGB32 );
            image.setDotsPerMeterX( dotsPerMeter );
            image.setDotsPerMeterY( dotsPerMeter );
            image.fill( QColor( Qt::white ).rgb() );

            QPainter painter( &image );
            render( plot, &painter, imageRect );
            painter.end();

            image.save( fileName, format.toLatin1() );
        }
    }
}
Esempio n. 15
0
void QPrinterProto::setDocName(const QString & name)
{
  QPrinter *item = qscriptvalue_cast<QPrinter*>(thisObject());
  if (item)
    item->setDocName(name);
}
Esempio n. 16
0
int LuaPrinter2::setDocName(lua_State *L)
{
	QPrinter* obj = ValueInstaller<LuaPrinter2>::check( L, 1 );
	obj->setDocName( luaL_checkstring( L, 2 ) );
	return 0;
}
Esempio n. 17
0
int Printer::setDocName(lua_State * L) // ( const QString & name )
{
	QPrinter* lhs = ValueBinding<MyQPrinter>::check( L, 1 );
	lhs->setDocName( QtValueBase::toString( L, 2 ));
	return 0;
}