void MultiLayer::exportToEPS(const QString& fname, int res, QPrinter::Orientation o, 
						QPrinter::PageSize pageSize, QPrinter::ColorMode col)
{	
QPrinter printer;
printer.setResolution(res);
printer.setPageSize(pageSize);
printer.setColorMode(col);
printer.setOrientation(o);
	
printer.setFullPage(TRUE);
printer.setOutputToFile (TRUE);
printer.setOutputFileName(fname);

QPainter paint(&printer);
QPaintDeviceMetrics pdmTo(&printer);

int dpiy = pdmTo.logicalDpiY();
int margin = (int) ( (0.5/2.54)*dpiy ); // 5 mm margins
	
QSize size = canvas->size();

double scaleFactorX=(double)(pdmTo.width() - 2*margin)/(double)size.width();
double scaleFactorY=(double)(pdmTo.height() - 2*margin)/(double)size.height();
	
for (int i=0;i<(int)graphsList->count();i++)
		{
		Graph *gr=(Graph *)graphsList->at(i);
		Plot *myPlot= (Plot *)gr->plotWidget();
			
		PrintFilter  filter(myPlot); 
	    filter.setOptions(QwtPlotPrintFilter::PrintAll | QwtPlotPrintFilter::PrintTitle 
						| QwtPlotPrintFilter::PrintCanvasBackground);

		QPoint pos=gr->pos();
		pos=QPoint(int(margin + pos.x()*scaleFactorX),int(margin + pos.y()*scaleFactorY));
	
		int width=int(myPlot->frameGeometry().width()*scaleFactorX);
		int height=int(myPlot->frameGeometry().height()*scaleFactorY);

		QRect rect = QRect(pos,QSize(width,height));

		if (myPlot->paletteBackgroundColor() != QColor(white))
			paint.fillRect(rect, myPlot->paletteBackgroundColor());

		int lw = myPlot->lineWidth();
		if ( lw > 0)
			{			
			myPlot->printFrame(&paint, rect);
				
			rect.moveBy ( lw, lw);
			rect.setWidth(rect.width() - 2*lw);
			rect.setHeight(rect.height() - 2*lw);
			}
		
		myPlot->print(&paint, rect, filter);
		}

if (hasOverlapingLayers())		
	updateTransparency();
}
示例#2
1
int Printer::setPageSize(lua_State * L) // (  PageSize newPageSize  )
{
	QPrinter* lhs = ValueBinding<MyQPrinter>::check( L, 1 );
	QPrinter::PageSize f=(QPrinter::PageSize)Util::toInt( L, 2 );
	lhs->setPageSize( f );
	return 0;
}
示例#3
1
// --------------------------------------------------------------------------------
void QmvFormTool::buildBackgroundPixmap( )
{
        // Determine page size using a QPinter object

    QPrinter* prt;
    QSize ps;

        // Set the page size
    prt = new QPrinter();
    prt->setFullPage(true);
    prt->setPageSize( (QPrinter::PageSize) fh->form_pagesize.toInt() );
    prt->setOrientation( (QPrinter::Orientation) fh->form_orientation.toInt() );

        // Get the page metrics
    QPaintDeviceMetrics pdm(prt);
    ps.setWidth(pdm.width());
    ps.setHeight(pdm.height());

    delete prt;

    background.resize( ps );
    pagesize = ps;
    
    background.fill( getTransparentColor() );

        // clear the canvas event index
    canvas_details.setAutoDelete(FALSE);
    canvas_details.clear();

}
QRectF M_PagesizeMake( QPrinter::PageSize psize , bool landscape)
{
    QPrinter *print = new QPrinter(QPrinter::HighResolution);
    print->setFullPage(true);
    print->setPageSize(psize);
    if (landscape)
    {
        print->setOrientation(QPrinter::Landscape);
    }
    else
    {
        print->setOrientation(QPrinter::Portrait);
    }

    const QRectF pa = print->pageRect(QPrinter::Point);
    const qreal faktor = qMax(pa.width(),pa.height()) / qMin(pa.width(),pa.height());

    const qreal smaller = qMin(pa.width(),pa.height());
    const qreal biger = smaller * faktor;
    delete print;

    if ( landscape )
    {
        return QRectF(0,0,biger,smaller);
    }
    else
    {
        return QRectF(0,0,smaller,biger);
    }
}
示例#5
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
    }

}
void OpenInfraPlatform::UserInterface::Alignment2DScene::exportToFile(QWidget* parent)
{
	QString filter;
	QString fn = QFileDialog::getSaveFileName(parent, tr("Save Vertical Alignment as..."), QString(), tr("PNG File (*.png);; JPG File (*.jpg);; PDF File (*.pdf);; SVG File (*.svg)"), &filter);
	if(fn.isEmpty())
		return;

	if(filter == "PNG File (*.png)" || filter == "JPG File (*.jpg)")
	{
		QImage image(sceneRect().size().toSize(), QImage::Format::Format_ARGB32);
		image.fill(Qt::darkGray);

		QPainter painter(&image);
		painter.setRenderHints(QPainter::Antialiasing);
		render(&painter);
		image.save(fn);
	}
	else
	{
		QPrinter printer;
		QSvgGenerator svgGen;

		QPaintDevice* device;
		if(filter == "PDF File (*.pdf)")
		{
			printer.setResolution(QPrinter::HighResolution);
			printer.setPageSize( QPrinter::A4 );
			printer.setOrientation( QPrinter::Landscape );
			printer.setOutputFormat( QPrinter::PdfFormat );
			printer.setOutputFileName(fn);

			device = &printer;
		}
		else if(filter == "SVG File (*.svg)")
		{
			QRectF rect = sceneRect(); 

			svgGen.setFileName(fn);
			svgGen.setSize(QSize(rect.width(),rect.height()));
			svgGen.setViewBox(QRect(0,0,rect.width(),rect.height()));
			svgGen.setTitle("Vertical Alignment");			
			
			device = &svgGen;
		}
		else
		{
			return;
		}

		QPainter painter(device);

		configureColors(A2D_DrawState::A2D_Print);
		render(&painter);
		configureColors(A2D_DrawState::A2D_Draw);
	}
}
示例#7
0
void Document::print()
{
	QPrinter printer;
	printer.setPageSize(QPrinter::Letter);
	printer.setPageMargins(0.5, 0.5, 0.5, 0.5, QPrinter::Inch);
	QPrintDialog dialog(&printer, this);
	if (dialog.exec() == QDialog::Accepted) {
		m_text->print(&printer);
	}
}
示例#8
0
/** Gets the metrics for the selected page size & orientation */
QSize MReportEngine::getPageMetrics( int size, int orientation ) {

  QSize ps;

  // Set the page size

  if (( QPrinter::PageSize ) size == QPrinter::Custom ) {
    ps.setWidth( customWidthMM / 25.4 * 78. );
    ps.setHeight( customHeightMM / 25.4 * 78. );
    return ps;
  }

#if defined(Q_OS_WIN32)
  if ( !printToPos ) {
    PSPrinter *printer = new PSPrinter( PSPrinter::HighResolution );
    printer->setFullPage( true );
    printer->setPageSize(( PSPrinter::PageSize ) size );
    printer->setOrientation(( PSPrinter::Orientation ) orientation );
    QPaintDeviceMetrics pdm( printer );
    ps.setWidth( pdm.widthMM() / 25.4 * 78. );
    ps.setHeight( pdm.heightMM() / 25.4 * 78. );
    delete printer;
  } else {
    FLPosPrinter * printer = new FLPosPrinter();
    QPaintDeviceMetrics pdm( printer );
    ps.setWidth( pdm.widthMM() / 25.4 * 78. );
    ps.setHeight( pdm.heightMM() / 25.4 * 78. );
    delete printer;
  }

#else
  if ( !printToPos ) {
    QPrinter * printer = new QPrinter( QPrinter::HighResolution );
    printer->setFullPage( true );
    printer->setPageSize(( QPrinter::PageSize ) size );
    printer->setOrientation(( QPrinter::Orientation ) orientation );
    QPaintDeviceMetrics pdm( printer );
    ps.setWidth( pdm.widthMM() / 25.4 * 78. );
    ps.setHeight( pdm.heightMM() / 25.4 * 78. );
    delete printer;
  } else {
    FLPosPrinter * printer = new FLPosPrinter();
    QPaintDeviceMetrics pdm( printer );
    ps.setWidth( pdm.widthMM() / 25.4 * 78. );
    ps.setHeight( pdm.heightMM() / 25.4 * 78. );
    delete printer;
  }

#endif

  return ps;
}
示例#9
0
void Document::print()
{
	QPrinter printer;
	printer.setPageSize(QPrinter::Letter);
	printer.setPageMargins(0.5, 0.5, 0.5, 0.5, QPrinter::Inch);
	QPrintDialog dialog(&printer, this);
	if (dialog.exec() == QDialog::Accepted) {
		bool enabled = m_highlighter->enabled();
		m_highlighter->setEnabled(false);
		m_text->print(&printer);
		if (enabled) {
			m_highlighter->setEnabled(true);
		}
	}
}
示例#10
0
void SvgCanvas::export_to_pdf_ps(int width, int height, QString filename)
{
	QPainter plot;
	QPrinter p;
	p.setFullPage(true);
	p.setPageSize(QPrinter::Custom);
	if( filename.endsWith(".pdf") )
		p.setOutputFormat(QPrinter::PdfFormat);
	else
		p.setOutputFormat(QPrinter::PostScriptFormat);
	p.setOutputFileName(filename);
	plot.begin(&p);
	svg_plot->renderer()->render(&plot);
	plot.end();
}
示例#11
0
//dugme za stampu uputa
void Uput::on_pushButton_clicked()
{


    QPrinter *printer = new QPrinter;


    QPrintDialog *printDialog = new QPrintDialog(printer, this);
    if (printDialog->exec() == QDialog::Accepted)
    {
        ui->pushButton->setVisible(false);
        ui->lineEdit->setReadOnly(true);
        ui->textEdit->setReadOnly(true);
        printer->setPageSize(printer->Letter);
        Uput::setVisible(false);
        Uput::setGeometry(0,0,769,400);
        this->render(printer);
        Uput::close();
    }
}
bool ReportGenerator::generatePDF(QString templateFilename, QString outputAbsolutePath)
{
    QFile templateFile(":/reports/Reports/"+templateFilename);

    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return false;
    }

    QTextStream templateStream(&templateFile);

    QTextDocument document;
    document.setHtml(templateStream.readAll());

    QList<QString> keys = this->vars.keys();
    QList<QString>::iterator keysIt;

    for(keysIt = keys.begin(); keysIt != keys.end(); ++keysIt)
    {
        QTextCursor cursor(&document);
        while(!cursor.isNull())
        {
            cursor = document.find("%"+(*keysIt)+"%", cursor);
            cursor.insertHtml(this->vars[(*keysIt)]);
        }
    }

    QPrinter* printer = new QPrinter(QPrinter::HighResolution);
    printer->setPageSize(QPrinter::A4);
    printer->setOutputFormat(QPrinter::PdfFormat);

    printer->setOutputFileName(outputAbsolutePath);

    WebViewPrinter* wv = new WebViewPrinter();
    wv->printer = printer;

    wv->setHtml(document.toHtml());

    return true;

}
示例#13
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();
	}
示例#14
0
int LuaPrinter2::setPageSize(lua_State *L)
{
	QPrinter* obj = ValueInstaller<LuaPrinter2>::check( L, 1 );
	obj->setPageSize( (QPrinter::PageSize)(int)luaL_checknumber( L, 2 ) );
	/*
		A0 (841 x 1189 mm) 
		A1 (594 x 841 mm) 
		A2 (420 x 594 mm) 
		A3 (297 x 420 mm) 
		A4 (210x297 mm, 8.26x11.7 inches) 
		A5 (148 x 210 mm) 
		A6 (105 x 148 mm) 
		A7 (74 x 105 mm) 
		A8 (52 x 74 mm) 
		A9 (37 x 52 mm) 
		B0 (1030 x 1456 mm) 
		B1 (728 x 1030 mm) 
		B10 (32 x 45 mm) 
		B2 (515 x 728 mm) 
		B3 (364 x 515 mm) 
		B4 (257 x 364 mm) 
		B5 (182x257 mm, 7.17x10.13 inches) 
		B6 (128 x 182 mm) 
		B7 (91 x 128 mm) 
		B8 (64 x 91 mm) 
		B9 (45 x 64 mm) 
		C5E (163 x 229 mm) 
		Comm10E (105 x 241 mm, US Common #10 Envelope) 
		DLE (110 x 220 mm) 
		Executive (7.5x10 inches, 191x254 mm) 
		Folio (210 x 330 mm) 
		Ledger (432 x 279 mm) 
		Legal (8.5x14 inches, 216x356 mm) 
		Letter (8.5x11 inches, 216x279 mm) 
		Tabloid (279 x 432 mm) 
	*/
	return 0;
}
示例#15
0
void GL_widget_2::export_to_vector(QString file_name) {
	QPrinter printer;
	printer.setOutputFileName(file_name);
	printer.setResolution(72);
	printer.setPageSize(QPrinter::A0);
	//	printer.setOrientation(QPrinter::Landscape); //ps would be not correct
	printer.setFullPage(true);
	printer.setColorMode(QPrinter::Color);


	QPainter painter;
	set_renderer_type(GL_widget_2::QT_PAINTER);
	set_painter(&painter);
	painter.begin(&printer);
	paint_to_painter();
	painter.end();
	set_painter(0);
	set_renderer_type(GL_widget_2::OPEN_GL);

	if (printer.printerState() < 2) // idle or active
		std::cout << "Image written to " << file_name.toStdString() << std::endl;
	else
		std::cout << "Could not write image to " << file_name.toStdString() << std::endl;
}
示例#16
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();
}
void SchedulePrintDialog::setupPrinter( QPrinter & printer )
{
	printer.setPageSize( QPrinter::PageSize(mPageSizeCombo->currentIndex()) );
	printer.setOrientation( mOrientationCombo->currentText() == "Landscape" ? QPrinter::Landscape : QPrinter::Portrait );
}
示例#18
0
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();
}
示例#19
0
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;
}
示例#20
0
void dController::printWithTemplate (int RowId)
{

    qDebug()<<Q_FUNC_INFO;
    //TODO это должно быть в отдельном классе !!!
    QGraphicsScene * scene = new QGraphicsScene();

    bool page_orient= false;
    int margin_top = MM_TO_POINT(15);
    int margin_bottom=MM_TO_POINT(15);
    int margin_left=MM_TO_POINT(35);
    int margin_right=MM_TO_POINT(15);

    int page_width=210;
    int page_height=297;
    scene->clear();
    scene->setSceneRect(0, 0, MM_TO_POINT(page_width),MM_TO_POINT(page_height));

QGraphicsRectItem *border_rect = new QGraphicsRectItem (QRectF(margin_left, margin_top, MM_TO_POINT(page_width)-margin_left-margin_right,MM_TO_POINT(page_height)-margin_top-margin_bottom));
    qDebug() <<"margin_rect"<< margin_left << margin_top << margin_left<<margin_right;
    border_rect->setPen(QPen(Qt::black,2,Qt::DotLine));
    border_rect->setBrush(QBrush(Qt::white));
    border_rect->setOpacity(0.5);
    border_rect->setZValue(0);
    //border_rect->setData(ObjectName, "Border");
    scene->addItem(border_rect);


	    SimpleItem* Gritem = new SimpleItem;
	    Gritem->setPos(MM_TO_POINT(180), MM_TO_POINT(0));
	    Gritem->setPrintFrame(false);
	    Gritem->setText(QStringList()<<QString("Секретно")<<QString("Пункт 12"));

	    Gritem->setFlag(QGraphicsItem::ItemIsMovable);

	    Gritem->setParentItem(border_rect);

	    SimpleItem* MBitem = new SimpleItem;
	    MBitem->setPos(MM_TO_POINT(5), MM_TO_POINT(280));
	    MBitem->setPrintFrame(false);
	    MBitem->setText(QStringList()<<QString("МБ №-%1"));//.arg(templ));
	    MBitem->setFlag(QGraphicsItem::ItemIsMovable);

	    scene->addItem(MBitem);//->setParentItem(border_rect);

	scene->update();

    QPrinter printer;
    QString with_t;
    with_t.append(spoolDIR).append("compl_teml2.pdf");

     printer.setOutputFormat(QPrinter::PdfFormat);
     printer.setOutputFileName(with_t);
     printer.setPageSize(QPrinter::A4);
     QPainter painter(&printer);
     scene->render(&painter);

     //QString in_file =mainPDF;
     //in_file.arg(QString(SID));
     qDebug() <<Q_FUNC_INFO<< mainPDF << outPDF;
     this->mergeTwoPDF(mainPDF,with_t,outPDF);
     // Рисуем последнюю страничку
     scene->clear();
    border_rect = new QGraphicsRectItem (QRectF(margin_left, margin_top, MM_TO_POINT(page_width)-margin_left-margin_right,MM_TO_POINT(page_height)-margin_top-margin_bottom));
    qDebug() <<"margin_rect"<< margin_left << margin_top << margin_left<<margin_right;
    border_rect->setPen(QPen(Qt::black,2,Qt::DotLine));
    border_rect->setBrush(QBrush(Qt::white));
    border_rect->setOpacity(0.5);
    border_rect->setZValue(0);
    //border_rect->setData(ObjectName, "Border");
    scene->addItem(border_rect);


	    SimpleItem* Lastitem = new SimpleItem;
	    Lastitem->setPos(MM_TO_POINT(40), MM_TO_POINT(200));
	    Lastitem->setPrintFrame(true);
	    Lastitem->setText(QStringList()<<QString("Секретно")
							 <<QString("Пункт 12")
							 <<QString("Исполнитель:ФИО исполнителя")
							 <<QString("Отпечатал:ФИО кто печатал")
							 <<QString("Телефон:2-63-15")
							 <<QString("Инв.№ 12/13")
							 <<QString("Дата: 09.09.09'")
							 <<QString("МБ №-%1"));//.arg(templ)
							//);

	    Lastitem->setFlag(QGraphicsItem::ItemIsMovable);

	    scene->addItem(Lastitem);//->setParentItem(border_rect);
     QPrinter printer2;

     printer2.setOutputFormat(QPrinter::PdfFormat);
     QString last_p;
     last_p.append(spoolDIR).append("last_page.pdf");
     printer2.setOutputFileName(last_p);
     printer2.setPageSize(QPrinter::A4);
     QPainter painter2(&printer2);
     scene->render(&painter2);

    // emit sayMeGood();
}
示例#21
0
void HeliCanvas::save(QString streamID, QString headline, QString date,
                      QString filename, int xres, int yres, int dpi) {
	std::cerr << "Printing..." << std::flush;

	QPainter *painter;
	QFileInfo fi(filename);
	QPrinter *printer = NULL;
	QImage *pixmap = NULL;

	if ( fi.suffix().toLower() == "ps" ) {
		printer = new QPrinter(QPrinter::HighResolution);
		printer->setOutputFileName(filename);
		printer->setResolution(dpi);
		printer->setPageSize(QPrinter::A4);
		painter = new QPainter(printer);
	}
	else {
		pixmap = new QImage(xres,yres,QImage::Format_RGB32);
		painter = new QPainter(pixmap);
		painter->fillRect(painter->window(), _palette.color(QPalette::Base));
	}

	painter->setFont(SCScheme.fonts.base);

	int fontHeight = painter->fontMetrics().height();
	int headerHeight = fontHeight*120/100;
	if ( !headline.isEmpty() )
		headerHeight += fontHeight*120/100;

	painter->translate(0, headerHeight);

	int offset = draw(
		*painter,
		QSize(painter->viewport().width(),
		      painter->viewport().height()-headerHeight)
		);

	painter->translate(0, -headerHeight);
	painter->drawText(offset, 0, painter->viewport().width()-offset, fontHeight,
	                  Qt::AlignLeft | Qt::AlignTop, streamID);
	painter->drawText(offset, 0, painter->viewport().width()-offset, fontHeight,
	                  Qt::AlignRight | Qt::AlignTop, date);

	if ( !headline.isEmpty() )
		painter->drawText(offset, fontHeight*120/100, painter->viewport().width()-offset, fontHeight,
		                  Qt::AlignLeft | Qt::AlignTop, headline);

	painter->drawLine(0, headerHeight, painter->viewport().width(), headerHeight);

	if ( pixmap )
		pixmap->save(filename);

	painter->end();

	// Clean up
	if ( printer ) delete printer;
	if ( pixmap ) delete pixmap;
	if ( painter ) delete painter;

	std::cerr << "finished" << std::endl;
}
示例#22
0
qint8 FaxToMailModule::Process()
{
        qDebug()<<"FaxToMailProcess Start\n";
        this->FIFolder.setPath(this->SysS->faxInfoFolderPath);//FaxInfoFolder
        this->FDFolder.setPath(this->SysS->faxDataFolderPath);//FaxDateFolder
        this->FileFilter.clear();
        this->FileFilter.append("*.FI");
        this->FIFolder.setNameFilters(this->FileFilter);
        qint32 FileCount=this->FIFolder.count();
        qDebug()<<"FileCount="<<FileCount<<"\n";
        QStringList FIFileList = this->FIFolder.entryList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot);

        while (!FIFileList.isEmpty())
            {
                QString FIFilePath,qcode;
                //qDebug()<<FIFileList.first();
                FIFilePath.clear();
                FIFilePath.append(this->FIFolder.absolutePath()+"/"+FIFileList.first());
                qDebug()<<FIFilePath;

                QFile FIfile(FIFilePath);
                if (!FIfile.open(QIODevice::ReadWrite|QIODevice::Text)) return -1;
                QByteArray tmp;
                tmp=FIfile.readLine();
                qDebug()<<"Identify code="<<QString(tmp);
                //qcode=QString(tmp);
                tmp=FIfile.readLine();
                qDebug()<<"Identify Mailaddr="<<QString(tmp);
                this->MailTo=QString(tmp);
                tmp=FIfile.readLine();
                while(!QString(tmp).isEmpty())
                {
                    //qDebug()<<QString(tmp);
                    FDFilePath.clear();
                    FDFilePath.append(tmp);
                    FDFilePath.remove("\n");
                    //qDebug()<<FDFilePath;
                    //Re=FaxIdentify(qcode,MailTo);
                    if (Re==true)
                    {
                       qDebug()<<"begin to print\n";

                       QPrinter printer;
                       printer.setOutputFormat(QPrinter::PdfFormat);
                       printer.setOrientation(QPrinter::Landscape);
                       printer.setPageSize(QPrinter::B0);
                       printer.setOutputFileName("/tmp/nonwritable.pdf");
                       QPainter painter;
                       QImage Image;
                       Image.load(FDFilePath);
                       qDebug()<<Image.size();
                       if (! painter.begin(&printer))
                       { // failed to open file
                            qWarning("failed to open file, is it writable?");
                            return -1;
                       }
                       painter.drawImage(0,0,Image);
                       /*
                       QFont font("Times",50);
                       QString text = tr("Hello World");
                       painter.setPen(Qt::blue);
                       painter.setFont(font);
                       painter.drawText(QRect(0,0, 1000, 100), text);
                        */
                       painter.end();

                        QFile PDFFile("/tmp/nonwritable.pdf");
                        if(PDFFile.open(QIODevice::ReadOnly))
                        {


                            QByteArray ls;
                            ls=PDFFile.readAll();
                            PDFFile.close();
                            //qDebug()<<"File Size="<<ls.size();
                            this->MailAttachment=ls.toBase64();
                            //qDebug()<<ls.toBase64();
                            if (this->CheckMailServerInfo()<0)
                            {
                                qDebug()<<"Error:MailServerInfo="<<this->CheckMailServerInfo();
                            }
                            else
                            {
                                QList<QString> bcc;
                                bcc<<"*****@*****.**";

                                Smtp *mail=new Smtp(this->MailServer,this->MailFrom,this->MailTo,bcc,"You have a fax !!!!!","You got a fax!!!",true,this->MailAttachment);
                                mail->current_user_name=this->MailUsername;
                                mail->current_password=this->MailPassword;
                                //qDebug()<<"ready,begin to sent mail";
                                mail->send();
                                //mail->~Smtp();

                            }


                        }
                        else
                        {
                            qFatal("Can Not find the PDF file!!!");
                        }

                    }
                    else
                    {

                    }

                    tmp=FIfile.readLine();
                }
                FIfile.close();
                FIfile.remove(FIfile.fileName());
                FIFileList.removeFirst();
            }
    //}
    FaxToMailTimer.start(3*1000);
    qDebug()<<"FaxToMailProcess End\n";
    return true;
}
void Data_analysis_gui::save_as_image( const QString& filename, 
                                       const QString& format,
                                       bool show_stats, bool show_grid ) {
  // get a file name and the name of the filter to use to save the image.
  // 3 filters are available: PNG, BMP, and Postscript. Postscript is not
  // available on Windows (Qt limitation).


  // Create a blank image of the correct dimensions
  int extra_width = 15;
  int min_height = 0;
  if( show_stats ) {
    extra_width = 200;
    min_height = 250;
  }
  QSize total_size( plot_->size().width() + extra_width, 
                    std::max( min_height, plot_->size().height()+10 ) );
  QPixmap pix( total_size );
  pix.fill();
  QPainter painter( &pix );
  

  // draw the content of the plot

  QwtPlotPrintFilter filter;
  if( show_grid )
    filter.setOptions( QwtPlotPrintFilter::PrintTitle | QwtPlotPrintFilter::PrintGrid );
  else
    filter.setOptions( QwtPlotPrintFilter::PrintTitle );

  QRect rect = plot_->rect();
  rect.setY( rect.y() + 10 );
  plot_->print( &painter, rect, filter );


  // Add the summary statistics to the image if requested

  if( show_stats ) {
    QFont font = plot_->axisFont( QwtPlot::xBottom );
    painter.setFont( font );
    int text_y_start = std::max( 40, total_size.height()/2 - 100 );
    painter.translate( plot_->size().width()+15 , text_y_start );
    paint_stats( painter );
  }


  // Finally, save the pixmap in the required format

  if( format == "Postscript" || format == "PS" ) {
    /*
#if defined(WIN32) || defined(_WIN32)
    if (show_stats)
		build_stats();
    SimplePs ps(filename,plot_, _stats,show_stats);
	if (!ps.isopen()){
		QMessageBox::warning(this,"Unable to save file",
		"Failed to save ps file",QMessageBox::Ok,
		Qt::NoButton);
		return;
	}
	savePostScript(ps);

#else
    */
    QPrinter printer;
    
    printer.setOutputFormat(QPrinter::PostScriptFormat);
    printer.setOutputFileName( filename );
    printer.setPageSize( QPrinter::A6 );
    printer.setFullPage( true );
    printer.setOrientation( QPrinter::Landscape );
    plot_->print(printer, filter);

    QPainter P(&printer);
    //P.begin(&printer);
    //paint_stats(P);
    P.drawPixmap(QPoint(0,0),pix);

    //#endif
  }
  else {
    QByteArray tmp = format.toLatin1();
    pix.save( filename, tmp.constData() );
  }

}
示例#24
0
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("");
}
示例#25
0
void CutyCapt::saveSnapshot() {
  QWebFrame *mainFrame = mPage->mainFrame();
  QPainter painter;
  const char* format = NULL;

  for (int ix = 0; CutyExtMap[ix].id != OtherFormat; ++ix) {
    if (CutyExtMap[ix].id == mFormat) {
      format = CutyExtMap[ix].identifier;
    }
  }

  // TODO: sometimes contents/viewport can have size 0x0 in which case saving
  // them will fail. This is likely the result of the method being called too
  // early. So far I've been unable to find a workaround, except using --delay
  // with some substantial wait time. I've tried to resize multiple time, make
  // a fake render, check for other events... This is primarily a problem under
  // my Ubuntu virtual machine.

  mPage->setViewportSize( mainFrame->contentsSize() );

  switch (mFormat) {
    case SvgFormat: {
      QSvgGenerator svg;
      svg.setFileName(mOutput);
      svg.setSize(mPage->viewportSize());
      painter.begin(&svg);
      mainFrame->render(&painter);
      painter.end();
      break;
    }
    case PdfFormat:
    case PsFormat: {
      QPrinter printer;
      printer.setPageSize(QPrinter::A4);
      printer.setOutputFileName(mOutput);
      // TODO: change quality here?
      mainFrame->print(&printer);
      break;
    }
#if QT_VERSION < 0x050000
    case RenderTreeFormat:
      QFile file(mOutput);
      file.open(QIODevice::WriteOnly | QIODevice::Text);
      QTextStream s(&file);
      s.setCodec("utf-8");
      s << mainFrame->renderTreeDump();
      break;
    }
#endif
    case InnerTextFormat:
    case HtmlFormat: {
      QFile file(mOutput);
      file.open(QIODevice::WriteOnly | QIODevice::Text);
      QTextStream s(&file);
      s.setCodec("utf-8");
      s << (mFormat == InnerTextFormat ? mainFrame->toPlainText() : (mFormat == HtmlFormat ? mainFrame->toHtml() : "bug"));
      break;
    }
    default: {
      QImage image(mPage->viewportSize(), QImage::Format_ARGB32);
      painter.begin(&image);
      mainFrame->render(&painter);
      painter.end();
      // TODO: add quality
      image.save(mOutput, format);
    }
  };
示例#26
0
//-----------------------------------------------------------
void CenaObjetos::definirGrade(unsigned tam)
{
 if(tam >= 20 || grade.style()==Qt::NoBrush)
 {
  QImage img_grade;
  float larg, alt, x, y;
  QSizeF tam_aux;
  QPrinter printer;
  QPainter painter;
  QPen pen;

  //Caso o tamanho do papel não seja personalizado
  if(tam_papel!=QPrinter::Custom)
  {
   //Configura um dispositivo QPrinter para obter os tamanhos de página
   printer.setPageSize(tam_papel);
   printer.setOrientation(orientacao_pag);
   printer.setPageMargins(margens_pag.left(), margens_pag.top(),
                          margens_pag.right(), margens_pag.bottom(), QPrinter::Millimeter);
   tam_aux=printer.pageRect(QPrinter::DevicePixel).size();
  }
  //Caso o tipo de papel seja personalizado, usa as margens como tamanho do papel
  else
   tam_aux=margens_pag.size();


  larg=fabs(roundf(tam_aux.width()/static_cast<float>(tam)) * tam);
  alt=fabs(roundf(tam_aux.height()/static_cast<float>(tam)) * tam);

  //Cria uma instância de QImage para ser a textura do brush
  tam_grade=tam;
  img_grade=QImage(larg, alt, QImage::Format_ARGB32);

  //Aloca um QPaointer para executar os desenhos sobre a imagem
  painter.begin(&img_grade);

  //Limpa a imagem
  painter.fillRect(QRect(0,0,larg,alt), QColor(255,255,255));

  if(exibir_grade)
  {
   //Cria a grade
   pen.setColor(QColor(225, 225, 225));
   painter.setPen(pen);

   for(x=0; x < larg; x+=tam)
    for(y=0; y < alt; y+=tam)
     painter.drawRect(QRectF(QPointF(x,y),QPointF(x + tam,y + tam)));
  }

  //Cria as linhas que definem o limite do papel
  if(exibir_lim_pagina)
  {
   pen.setColor(QColor(75,115,195));
   pen.setStyle(Qt::DashLine);
   pen.setWidthF(1.85f);
   painter.setPen(pen);
   painter.drawLine(larg-1, 0,larg-1,alt-1);
   painter.drawLine(0, alt-1,larg-1,alt-1);
  }

  painter.end();
  grade.setTextureImage(img_grade);
 }
}
void PrintAPI::PrintA4(QString title, QString type, QList<QString> columnNames, QList<int> columnWidths,
                       QStringList content)
{
    //计算行数列数
    int columnCount = columnNames.count();
    int rowCount = content.count();

    //清空原有数据,确保每次都是新的数据
    html.clear();

    //表格开始
    html.append("<table border='0.5' cellspacing='0' cellpadding='3'>");

    //标题占一行,居中显示
    html.append(QString("<tr><td colspan='%1'>").arg(columnCount));
    html.append("<p align='center' style='vertical-align:middle;font-weight:bold;font-size:15px;'>");
    html.append(title);
    html.append("</p></td></tr>");

    //循环写入字段名,字段名占一行,居中显示
    html.append("<tr>");
    for (int i = 0; i < columnCount; i++) {
        html.append(QString("<td width='%1' bgcolor='lightgray'>").arg(columnWidths.at(i)));
        html.append("<p align='center' style='vertical-align:middle;'>");
        html.append(columnNames.at(i));
        html.append("</p></td>");
    }
    html.append("</tr>");

    //循环一行行构建数据
    for (int i = 0; i < rowCount; i++) {
        QStringList value = content.at(i).split(";");
        html.append("<tr>");
        for (int j = 0; j < columnCount; j++) {
            html.append(QString("<td width='%1'>").arg(columnWidths.at(j)));
            html.append(value.at(j));
            html.append("</td>");
        }
        html.append("</tr>");
    }

    html.append("</table>");

    //调用打印机打印
    QPrinter printer;
    //设置输出格式
    printer.setOutputFormat(QPrinter::NativeFormat);
    //设置纸张规格
    printer.setPageSize(QPrinter::A4);
    //设置横向纵向及页边距
    if (type == "横向") {
        printer.setOrientation(QPrinter::Landscape);
        printer.setPageMargins(10, 10, 10, 12, QPrinter::Millimeter);
    } else {
        printer.setOrientation(QPrinter::Portrait);
        printer.setPageMargins(10, 10, 10, 16, QPrinter::Millimeter);
    }

    QPrintPreviewDialog preview(&printer);
    preview.setWindowTitle("打印预览");
    connect(&preview, SIGNAL(paintRequested(QPrinter *)), this, SLOT(printView(QPrinter *)));
    preview.showMaximized();
    preview.exec();
}