impresoras en python

Alvaro Abraham Colunga Rodriguez drg_alvaro en yahoo.com
Mie Sep 22 17:57:07 CEST 2004


Aqui esta el codigo pegado. Espero que no haya
problema con la indentacion, incluso biene como usar
reportlab para hacer pdfs, que tambien te puede
servir.

Saludos.


from wxPython.wx import *
#from pyPgSQL import PgSQL
from wxPython.lib.mixins.listctrl import
wxColumnSorterMixin,wxListCtrlAutoWidthMixin
from datetime import date

#from reportlab.pdfgen import canvas
#from reportlab.lib.units import cm
#from reportlab.lib.pagesizes import letter

import common
from wx.html import HtmlEasyPrinting

class MyPrintout(wxPrintout):
	#def __init__(self, frame,datos,lista):
	def __init__(self,canvas):
		wxPrintout.__init__(self)
		#self.frame = frame
		self.pages = 1
		self.canvas=canvas
		#self.datos=datos
		#self.lista=lista

	def OnBeginDocument(self, start, end):
		return self.base_OnBeginDocument(start, end)

	def OnEndDocument(self):
		self.base_OnEndDocument()

	def OnBeginPrinting(self):
		self.base_OnBeginPrinting()

	def OnEndPrinting(self):
		self.base_OnEndPrinting()

	def OnPreparePrinting(self):
		self.base_OnPreparePrinting()		
	
	def HasPage(self, page):
		if page < self.pages:
			return true
        #else:
        #    return false

	def GetPageInfo(self):
		return (1, self.pages, 1, self.pages)

	def OnPrintPage(self, page):
		dc = self.GetDC()

		# One possible method of setting scaling factors...
		#print dir(self.canvas)
		#maxX = self.canvas.getWidth()
		#maxY = self.canvas.getHeight()
		maxX=900
		maxY=900

		# Let's have at least 50 device units margin
		marginX = 10
		marginY = 10

		# Add the margin to the graphic size
		maxX = maxX + (2 * marginX)
		maxY = maxY + (2 * marginY)

		# Get the size of the DC in pixels
		(w, h) = dc.GetSizeTuple()

		# Calculate a suitable scaling factor
		scaleX = float(w) / maxX
		scaleY = float(h) / maxY

		# Use x or y scaling factor, whichever fits on the
DC
		actualScale = min(scaleX, scaleY)

		# Calculate the position on the DC for centring the
graphic
		#posX = (w - (self.canvas.getWidth() * actualScale))
/ 2.0
		#posY = (h - (self.canvas.getHeight() *
actualScale)) / 2.0
		posX = (w - (900 * actualScale)) / 2.0
		posY = (h - (900 * actualScale)) / 2.0

		# Set the scale and origin
		dc.SetUserScale(actualScale, actualScale)
		#dc.SetDeviceOrigin(int(posX), int(posY))
		dc.SetDeviceOrigin(0,0)

		#-------------------------------------------

		#x= 25
		#y=15
		
		#if not self.IsPreview():
		#	y *=4
      #-------------------------------------------
		#line_count = 1
		#for item in self.datos:
		#	dc.DrawText(item, x, y*line_count)
		#	line_count+=1

		
		#for i in self.lista:
		#	x2=25
		#	for item in i:
		#		dc.DrawText(item, x2, y*line_count)
		#		x2*=2
		#	line_count+=1
		
		#self.canvas.DoDrawing(dc,self.datos,self.lista)
		self.canvas.DoDrawing(dc)
		#dc.DrawText("Page: %d" % page, 100,100)
		
		return True

#------------------------------------------------------
class TextValidator(wxPyValidator):
     """ This validator is used to ensure that the
user has entered something
         into the text object editor dialog's text
field.
     """
     def __init__(self):
         """ Standard constructor.
         """
         wxPyValidator.__init__(self)



     def Clone(self):
         """ Standard cloner.

             Note that every validator must implement
the Clone() method.
         """
         return TextValidator()


     def Validate(self, win):
         """ Validate the contents of the given text
control.
         """
         textCtrl = self.GetWindow()
         text = textCtrl.GetValue()

         if len(text) == 0:
             wxMessageBox("Los datos estan
incompletos", "Error")
             textCtrl.SetBackgroundColour("red")
             textCtrl.SetFocus()
             textCtrl.Refresh()
             return False
         else:
             textCtrl.SetBackgroundColour(
                
wxSystemSettings_GetColour(wxSYS_COLOUR_WINDOW))
             textCtrl.Refresh()
             return True


     def TransferToWindow(self):
         """ Transfer data from validator to window.

             The default implementation returns False,
indicating that an error
             occurred.  We simply return True, as we
don't do any data transfer.
         """
         return True # Prevent wxDialog from
complaining.


     def TransferFromWindow(self):
         """ Transfer data from window to validator.

             The default implementation returns False,
indicating that an error
             occurred.  We simply return True, as we
don't do any data transfer.
         """
         return True # Prevent wxDialog from
complaining.


#---------------------------------------------------------
class MyList2(wxListCtrl,wxListCtrlAutoWidthMixin):
	def
__init__(self,parent,ID,pos=wxDefaultPosition,size=wxDefaultSize,style=0):
		wxListCtrl.__init__(self,parent,ID,pos,size,style)
		wxListCtrlAutoWidthMixin.__init__(self)
#---------------------------------------------------------

class Imprime(wxFrame):
	def __init__(self,ID,parent):
	
		wxFrame.__init__(self,ID,parent,"Impresion")
		panel=wxPanel(self,-1,style=wxTAB_TRAVERSAL)

		ID_PRN_PRN=wxNewId()
		ID_PRN_PRV=wxNewId()
		ID_PRN_CFG=wxNewId()
		ID_AGREGA=wxNewId()
		ID_PRN_PDF=wxNewId()

		ID_EXIT=wxNewId()
		self.menuArchivo = wxMenu()
		#agrega una opcion al menu
		self.menuArchivo.Append(ID_AGREGA,
"A&gregar\tF2","Agrega elementos")
		self.menuArchivo.Append(ID_PRN_PRN, "Imprimir")
		self.menuArchivo.Append(ID_PRN_CFG, "Configurar
impresion")
		self.menuArchivo.Append(ID_PRN_PRV, "Vista
preliminar")
		self.menuArchivo.Append(ID_PRN_PDF, "Crear PDF")
		self.menuArchivo.AppendSeparator()
		self.menuArchivo.Append(ID_EXIT, "&Salir\tF10",
"Salir del programa")
		
		EVT_MENU(self,ID_PRN_PRN,self.OnDoPrint)
		EVT_MENU(self,ID_PRN_PRV,self.OnPrintPreview)
		EVT_MENU(self,ID_PRN_CFG,self.OnPrintSetup)
		EVT_MENU(self,ID_PRN_PDF,self.OnPrintPDF)
		EVT_MENU(self,ID_AGREGA,self.OnAgregar)

		menuBar = wxMenuBar()
		#agrega el menu a la barra de menu
		menuBar.Append(self.menuArchivo, "&Archivo")

		#establece como barra de menu el que se creo
		self.SetMenuBar(menuBar)

		EVT_MENU(self, ID_EXIT,  self.OnArchivoSalir)

		label1=wxStaticText(panel,-1,"Numero de cliente")
		label2=wxStaticText(panel,-1,"Fecha")
		#label3=wxStaticText(panel,-1,"Direccion")
		#label4=wxStaticText(panel,-1,"Telefono")
		#label5=wxStaticText(panel,-1,"Ciudad")
		#label6=wxStaticText(panel,-1,"Estado")
		#label7=wxStaticText(panel,-1,"RFC")
	
self.textocliente=wxTextCtrl(panel,-1,"",size=wxSize(200,100),style=wxTE_MULTILINE|wxTE_READONLY)

		ID_TEXT_ENTER=wxNewId()
	
self.txt1=wxTextCtrl(panel,ID_TEXT_ENTER,"",size=(200,-1),style=wxTE_PROCESS_ENTER,validator=TextValidator())
	
self.txt2=wxTextCtrl(panel,-1,"",validator=TextValidator())
	
#self.txt3=wxTextCtrl(panel,-1,"",validator=TextValidator())
	
#self.txt4=wxTextCtrl(panel,-1,"",validator=TextValidator())
	
#self.txt5=wxTextCtrl(panel,-1,"",validator=TextValidator())
	
#self.txt6=wxTextCtrl(panel,-1,"",validator=TextValidator())
	
#self.txt7=wxTextCtrl(panel,-1,"",validator=TextValidator())

		EVT_TEXT_ENTER(self,ID_TEXT_ENTER,self.OnTextEnter)

		fe=date
	
fecha=str(fe.today().day)+'/'+str(fe.today().month)+'/'+str(fe.today().year)
		self.txt2.SetValue(fecha)

		ID_LISTA=wxNewId()
	
#self.lista=wxListCtrl(panel,ID_LISTA,wxDefaultPosition,wxSize(640,280),wxLC_REPORT)
	
self.lista=MyList2(panel,ID_LISTA,wxDefaultPosition,wxSize(640,280),wxLC_REPORT)

		self.lista.InsertColumn(0,"Cantidad")
		self.lista.InsertColumn(1,"Concepto")
		self.lista.InsertColumn(2,"Precio unitario")
		self.lista.InsertColumn(3,"Subtotal")

		box1=wxBoxSizer(wxHORIZONTAL)
		box1.Add(label1,0)
		box1.Add(self.txt1,0)
		box1.Add(label2,0)
		box1.Add(self.txt2,0)
		#grid1=wxGridSizer(9,2,0,0)
		#grid1.Add(label1,0)
		#grid1.Add(self.txt1,0,wxEXPAND)
		#grid1.Add(label2,0)
		#grid1.Add(self.txt2,0,wxEXPAND)
		#grid1.Add(label3,0)
		#grid1.Add(self.txt3,0,wxEXPAND)
		#grid1.Add(label4,0)
		#grid1.Add(self.txt4,0,wxEXPAND)
		#grid1.Add(label5,0)
		#grid1.Add(self.txt5,0,wxEXPAND)
		#grid1.Add(label6,0)
		#grid1.Add(self.txt6,0,wxEXPAND)
		#grid1.Add(label7,0)
		#grid1.Add(self.txt7,0,wxEXPAND)

		#ID_BTN_PRN=wxNewId()
		#ID_BTN_PRNPRV=wxNewId()
		#ID_BTN_PRNCFG=wxNewId()

		#btn1=wxButton(panel,wxID_OK,"Guardar")
#		btn2=wxButton(panel,wxID_CANCEL,"Cancelar")
		#btn3=wxButton(panel,ID_BTN_PRN,"Imprimr")
		#btn4=wxButton(panel,ID_BTN_PRNPRV,"Vista
preliminar")
		#btn5=wxButton(panel,ID_BTN_PRNCFG,"Conf impresion")

#		EVT_BUTTON(self,wxID_CANCEL,self.OnSalir)
		#EVT_BUTTON(self,wxID_OK,self.OnGuardar)
		#EVT_BUTTON(self,ID_BTN_PRN,self.OnDoPrint)
		#EVT_BUTTON(self,ID_BTN_PRNPRV,self.OnPrintPreview)
		#EVT_BUTTON(self,ID_BTN_PRNCFG,self.OnPrintSetup)

		#box2=wxBoxSizer(wxHORIZONTAL)
		#box2.Add(btn1,0,wxALIGN_CENTER|wxALL,5)
		#box2.Add(btn2,0,wxALIGN_CENTER|wxALL,5)
		#box2.Add(btn3,0,wxALIGN_CENTER|wxALL,5)
		#box2.Add(btn4,0,wxALIGN_CENTER|wxALL,5)
		#box2.Add(btn5,0,wxALIGN_CENTER|wxALL,5)

		
		sizer=wxBoxSizer(wxVERTICAL)
		sizer.Add(box1,0,wxALIGN_CENTER_HORIZONTAL|wxALL,5)
	
#sizer.Add(grid1,0,wxALIGN_CENTER_HORIZONTAL|wxALL,5)
	
sizer.Add(self.textocliente,0,wxALIGN_CENTER_HORIZONTAL|wxEXPAND,5)
	
sizer.Add(self.lista,0,wxALIGN_CENTER_HORIZONTAL|wxEXPAND,5)
		#sizer.Add(box2,0,wxALIGN_CENTER_HORIZONTAL|wxALL,5)

		panel.SetSizer(sizer)
		panel.SetAutoLayout(True)
		sizer.Fit(self)

		self.printData = wxPrintData()
		self.printData.SetPaperId(wxPAPER_LETTER)
		self.frame=self
		#dc=wxClientDC(self)
		#dc.DrawRectangle(5, 5, 50, 50)
		#self.canvas=MyCanvas(self)		
		
#------------------------------------------------------
	def OnTextEnter(self,event):
		valores=[self.txt1.GetValue()]

		conexion=PgSQL.connect(common.cadconexion())
		cursor=conexion.cursor()
		query="select
num,nombre,direccion,telefono,ciudad,estado,rfc from
cliente where num='%s'" % valores[0]
		cursor.execute(query)
		resultado=cursor.fetchone()
		if not resultado:
			wxMessageBox("El cliente %s no existe" %
(valores[0]), "Error",wxICON_EXCLAMATION)
		else:
			#self.txt2.SetValue(resultado[1])
			#self.txt3.SetValue(resultado[2])
			#self.txt4.SetValue(resultado[3])
			#self.txt5.SetValue(resultado[4])
			#self.txt6.SetValue(resultado[5])
			#self.txt7.SetValue(resultado[6])
			texto=str(resultado[1])+"\n"
			texto=texto + str(resultado[2])+"\n"
			texto=texto + str(resultado[3])+"\n"
			texto=texto + str(resultado[4])+"\n"
			texto=texto + str(resultado[5])+"\n"
			texto=texto + str(resultado[6])
			self.textocliente.SetValue(texto)
		conexion.close()
#------------------------------------------------------
	def OnArchivoSalir(self,event):
		self.Close(True)
#------------------------------------------------------
	def OnGuardar(self,event):
		print ""
#------------------------------------------------------
	def OnAgregar(self,event):
		dlg=wxDialog(self,-1,"Agregar")
		
		label1=wxStaticText(dlg,-1,"Catidad")
		label2=wxStaticText(dlg,-1,"Concepto")
		label3=wxStaticText(dlg,-1,"Precio unitario")

	
txt1=wxTextCtrl(dlg,-1,"",size=wxSize(200,-1),validator=TextValidator())
	
txt2=wxTextCtrl(dlg,-1,"",size=wxSize(200,-1),validator=TextValidator())
	
txt3=wxTextCtrl(dlg,-1,"",size=wxSize(200,-1),validator=TextValidator())

		btn1=wxButton(dlg,wxID_OK,"Aceptar")
		btn2=wxButton(dlg,wxID_CANCEL,"Cancelar")

		box2=wxBoxSizer(wxHORIZONTAL)
		box2.Add(btn1,0,wxALIGN_CENTER|wxALL,5)
		box2.Add(btn2,0,wxALIGN_CENTER|wxALL,5)

		grid1=wxGridSizer(9,2,0,0)
		grid1.Add(label1,0)
		grid1.Add(txt1,0,wxEXPAND)
		grid1.Add(label2,0)
		grid1.Add(txt2,0,wxEXPAND)
		grid1.Add(label3,0)
		grid1.Add(txt3,0,wxEXPAND)

		sizer=wxBoxSizer(wxVERTICAL)
		sizer.Add(grid1,0,wxALIGN_CENTER_HORIZONTAL|wxALL,5)
		sizer.Add(box2,0,wxALIGN_CENTER_HORIZONTAL|wxALL,5)

		dlg.SetSizer(sizer)
		dlg.SetAutoLayout(True)
		sizer.Fit(dlg)

		opc=dlg.ShowModal()
		if opc == wxID_OK:
			pos=self.lista.GetItemCount()
		
self.lista.InsertStringItem(pos,str(txt1.GetValue()))
		
self.lista.SetStringItem(pos,1,str(txt2.GetValue()))
		
self.lista.SetStringItem(pos,2,str(txt3.GetValue()))

		
subtotal=float(txt1.GetValue())*float(txt3.GetValue())
			self.lista.SetStringItem(pos,3,str(subtotal))
		dlg.Destroy()
#------------------------------------------------------
	def OnPrintSetup(self, event):
		printerDialog = wx.wxPrintDialog(self)
	
printerDialog.GetPrintDialogData().SetPrintData(self.printData)
	
printerDialog.GetPrintDialogData().SetSetupDialog(True)
		printerDialog.ShowModal();
		self.printData =
printerDialog.GetPrintDialogData().GetPrintData()
		printerDialog.Destroy()
#------------------------------------------------------
	def OnPrintPreview(self, event):

		datos=self.textocliente.GetValue().split("\n")
		cant=self.lista.GetItemCount()
		lista=[]
		for num in range(cant):
			t1=self.lista.GetItemText(num)
			t2=self.lista.GetItem(num,1).GetText()
			t3=self.lista.GetItem(num,2).GetText()
			t4=self.lista.GetItem(num,3).GetText()
			lista.append([t1,t2,t3,t4])
		
		#printout = MyPrintout(self,datos,lista)
		#printout2 = MyPrintout(self,datos,lista)
		printout = MyPrintout(self)
		printout2 = MyPrintout(self)
		self.preview = wxPrintPreview(printout, printout2,
self.printData)
		if not self.preview.Ok():
			return

		frame = wxPreviewFrame(self.preview, self.frame,
"Vista preliminar")

		frame.Initialize()
		frame.SetPosition(self.frame.GetPosition())
		frame.SetSize(self.frame.GetSize())
		frame.Show(True)
#------------------------------------------------------
	def OnDoPrint(self, event):

		datos=self.textocliente.GetValue().split("\n")
		cant=self.lista.GetItemCount()
		lista=[]
		for num in range(cant):
			t1=self.lista.GetItemText(num)
			t2=self.lista.GetItem(num,1).GetText()
			t3=self.lista.GetItem(num,2).GetText()
			t4=self.lista.GetItem(num,3).GetText()
			lista.append([t1,t2,t3,t4])
		
		pdd = wxPrintDialogData()
		pdd.SetPrintData(self.printData)
		printer = wxPrinter(pdd)
		#printout = MyPrintout(self,datos,lista)
		printout = MyPrintout(self)
		printer.Print(self.frame, printout)
		
		
		#if not printer.Print(self.frame,
printout,prompt=True):
		#	wxMessageBox("There was a problem
printing.\nPerhaps your current printer is not set
correctly?", "Printing", wxOK)
		#else:
		#	self.printData =
printer.GetPrintDialogData().GetPrintData()
		
		#printout.Destroy()
#-------------------------------------------------------
	def OnPrintPDF(self,event):
	
c=canvas.Canvas("factura.pdf",bottomup=0,pagesize=letter)
		font="Helvetica"
		font_size= 12
		width,height=letter
		c.setFont(font,font_size)

		datos=self.textocliente.GetValue().split("\n")
		cant=self.lista.GetItemCount()
		lista=[]
		for num in range(cant):
			t1=self.lista.GetItemText(num)
			t2=self.lista.GetItem(num,1).GetText()
			t3=self.lista.GetItem(num,2).GetText()
			t4=self.lista.GetItem(num,3).GetText()
			lista.append([t1,t2,t3,t4])

		linea=1
		for item in datos:
			c.drawString(0,cm+linea*15,item)
			linea+=1
		
		linea+=2
		for i in lista:
			for item in i:
				c.drawString(0,cm+linea*15,item)
				linea+=1
		linea+=2

		c.showPage()
		c.save()

	def DoDrawing(self,dc):
		datos=self.textocliente.GetValue().split("\n")
		cant=self.lista.GetItemCount()
		lista=[]
		for num in range(cant):
			t1=self.lista.GetItemText(num)
			t2=self.lista.GetItem(num,1).GetText()
			t3=self.lista.GetItem(num,2).GetText()
			t4=self.lista.GetItem(num,3).GetText()
			lista.append([t1,t2,t3,t4])

		dc.BeginDrawing()

		#dc.SetPen(wxPen('RED'))
		#dc.DrawRectangle(5, 5, 50, 50)
		#dc.DrawRectangle(50, 50, 100, 150)

		#dc.SetBrush(wxLIGHT_GREY_BRUSH)
		#dc.SetPen(wxPen('BLUE', 4))
		#dc.DrawRectangle(15, 15, 50, 50)

		font = wxFont(14, wxROMAN, wxNORMAL, wxNORMAL)
		dc.SetFont(font)

		x=10
		y=1
      #-------------------------------------------
		line_count = 1
		for item in datos:
			dc.DrawText(item, x, y*line_count)
			line_count+=10

		
		for i in lista:
			x2=0
			for item in i:
				w,h=dc.GetTextExtent(item)
				dc.DrawText(item, x2, y*line_count)
				x2+=(w+2)
			line_count+= (h+10)

		dc.EndDrawing()




class Printer(HtmlEasyPrinting):
    def __init__(self):
        HtmlEasyPrinting.__init__(self)

    def GetHtmlText(self,text):
        "Simple conversion of text.  Use a more
powerful version"
        html_text = text.replace('\n\n','<P>')
        html_text = text.replace('\n', '<BR>')
        return html_text

    def Print(self, text, doc_name):
        self.SetHeader(doc_name)
       
self.PrintText(self.GetHtmlText(text),doc_name)

    def PreviewText(self, text, doc_name):
        self.SetHeader(doc_name)
        HtmlEasyPrinting.PreviewText(self,
self.GetHtmlText(text))

class Imprime2(wxFrame):
	def __init__(self,ID,parent):
	
		wxFrame.__init__(self,ID,parent,"Impresion")

		self.printer=Printer()
		
		ID_BTN_PRN=wxNewId()
		ID_BTN_PRNPRV=wxNewId()
		ID_BTN_PRNCFG=wxNewId()

		btn3=wxButton(self,ID_BTN_PRN,"Imprimr")
		btn4=wxButton(self,ID_BTN_PRNPRV,"Vista preliminar")
		btn5=wxButton(self,ID_BTN_PRNCFG,"Conf impresion")

		EVT_BUTTON(self,ID_BTN_PRN,self.OnDoPrint)
		EVT_BUTTON(self,ID_BTN_PRNPRV,self.OnPrintPreview)
		EVT_BUTTON(self,ID_BTN_PRNCFG,self.OnPrintSetup)

		box2=wxBoxSizer(wxHORIZONTAL)
		box2.Add(btn3,0,wxALIGN_CENTER|wxALL,5)
		box2.Add(btn4,0,wxALIGN_CENTER|wxALL,5)
		box2.Add(btn5,0,wxALIGN_CENTER|wxALL,5)

		sizer=wxBoxSizer(wxVERTICAL)
		sizer.Add(box2,0,wxALIGN_CENTER_HORIZONTAL|wxALL,5)

		self.SetSizer(sizer)
		self.SetAutoLayout(True)
		sizer.Fit(self)


	def OnPrintPreview(self,event):
		self.printer.PreviewText("hola mundo","Prueba")

	def OnPrintSetup(self,event):
		self.printer.PageSetup()

	def OnDoPrint(self,event):
		self.printer.Print("hola mundo","Prueba")



class MyCanvas(wxScrolledWindow):
	def __init__(self, parent, id = -1, size =
wxDefaultSize):
		wxScrolledWindow.__init__(self, parent, id,
wxPoint(0, 0), size, wxSUNKEN_BORDER)

#-----------------------------------------------------
	def DoDrawing(self,dc):
		

		dc.BeginDrawing()

		dc.SetPen(wxPen('RED'))
		dc.DrawRectangle(5, 5, 50, 50)

		dc.SetBrush(wxLIGHT_GREY_BRUSH)
		dc.SetPen(wxPen('BLUE', 4))
		dc.DrawRectangle(15, 15, 50, 50)
		dc.SetTextForeground(wxBLACK)
		dc.DrawText("kjhamnbfdjgjhgfs",50,100)


		x= 25
		y=15
      #-------------------------------------------
		#line_count = 1
		#for item in datos:
			#dc.DrawText(item, x, y*line_count)
			#line_count+=1

		
		#for i in lista:
			#x2=25
			#for item in i:
				#dc.DrawText(item, x2, y*line_count)
				#x2*=2
			#line_count+=1

		dc.EndDrawing()


_________________________________________________________
Do You Yahoo!?
Información de Estados Unidos y América Latina, en Yahoo! Noticias.
Visítanos en http://noticias.espanol.yahoo.com




Más información sobre la lista de distribución Python-es