Foros del Web » Programando para Internet » Python »

Como imprimir TEXTO con la impresora(fisica) con Python en Windows

Estas en el tema de Como imprimir TEXTO con la impresora(fisica) con Python en Windows en el foro de Python en Foros del Web. Saludos, me preguntaba como imprimir texto por medio de la impresora como lo hacen muchos programas, es mas no es necesario poner la ventana en ...
  #1 (permalink)  
Antiguo 21/10/2009, 16:16
 
Fecha de Ingreso: septiembre-2009
Mensajes: 22
Antigüedad: 14 años, 7 meses
Puntos: 0
Como imprimir TEXTO con la impresora(fisica) con Python en Windows

Saludos, me preguntaba como imprimir texto por medio de la impresora como
lo hacen muchos programas, es mas no es necesario poner la ventana en la
que se configura cuantas copias y de que manera imprimir. Solo quiero
imprimir texto plano como el que se optiene de un Raw-Input().
Espero se tan facil como:
Código:
print "Programa para IMPRIMIR"
texto=raw_input()
imprimir_comando(texto)
Como obio mi codigo esta mal, me podrian ayudar poniendo los comandos
corretos.

De antemano GRACIAS.
  #2 (permalink)  
Antiguo 21/10/2009, 20:15
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Como imprimir TEXTO con la impresora(fisica) con Python en Windows

Bueno lo único que conozco para imprimir es una parte del modulo wxpython

Aquí un ejemplo sencillo.

No olvides hacer un pequeño archivo llamado sample-text.txt que contenga el texto a imprimir.

Ejemplo sacado del libro: "wxpython in action"
Código python:
Ver original
  1. import wx
  2.  
  3. import os
  4.  
  5.  
  6.  
  7. FONTSIZE = 10
  8.  
  9.  
  10.  
  11. class TextDocPrintout(wx.Printout):
  12.  
  13.     """
  14.  
  15.    A printout class that is able to print simple text documents.
  16.  
  17.    Does not handle page numbers or titles, and it assumes that no
  18.  
  19.    lines are longer than what will fit within the page width.  Those
  20.  
  21.    features are left as an exercise for the reader. ;-)
  22.  
  23.    """
  24.  
  25.     def __init__(self, text, title, margins):
  26.  
  27.         wx.Printout.__init__(self, title)
  28.  
  29.         self.lines = text.split('\n')
  30.  
  31.         self.margins = margins
  32.  
  33.  
  34.  
  35.  
  36.  
  37.     def HasPage(self, page):
  38.  
  39.         return page <= self.numPages
  40.  
  41.  
  42.  
  43.     def GetPageInfo(self):
  44.  
  45.         return (1, self.numPages, 1, self.numPages)
  46.  
  47.  
  48.  
  49.  
  50.  
  51.     def CalculateScale(self, dc):
  52.  
  53.         # Scale the DC such that the printout is roughly the same as
  54.  
  55.         # the screen scaling.
  56.  
  57.         ppiPrinterX, ppiPrinterY = self.GetPPIPrinter()
  58.  
  59.         ppiScreenX, ppiScreenY = self.GetPPIScreen()
  60.  
  61.         logScale = float(ppiPrinterX)/float(ppiScreenX)
  62.  
  63.  
  64.  
  65.         # Now adjust if the real page size is reduced (such as when
  66.  
  67.         # drawing on a scaled wx.MemoryDC in the Print Preview.)  If
  68.  
  69.         # page width == DC width then nothing changes, otherwise we
  70.  
  71.         # scale down for the DC.
  72.  
  73.         pw, ph = self.GetPageSizePixels()
  74.  
  75.         dw, dh = dc.GetSize()
  76.  
  77.         scale = logScale * float(dw)/float(pw)
  78.  
  79.  
  80.  
  81.         # Set the DC's scale.
  82.  
  83.         dc.SetUserScale(scale, scale)
  84.  
  85.  
  86.  
  87.         # Find the logical units per millimeter (for calculating the
  88.  
  89.         # margins)
  90.  
  91.         self.logUnitsMM = float(ppiPrinterX)/(logScale*25.4)
  92.  
  93.  
  94.  
  95.  
  96.  
  97.     def CalculateLayout(self, dc):
  98.  
  99.         # Determine the position of the margins and the
  100.  
  101.         # page/line height
  102.  
  103.         topLeft, bottomRight = self.margins
  104.  
  105.         dw, dh = dc.GetSize()
  106.  
  107.         self.x1 = topLeft.x * self.logUnitsMM
  108.  
  109.         self.y1 = topLeft.y * self.logUnitsMM
  110.  
  111.         self.x2 = dc.DeviceToLogicalXRel(dw) - bottomRight.x * self.logUnitsMM
  112.  
  113.         self.y2 = dc.DeviceToLogicalYRel(dh) - bottomRight.y * self.logUnitsMM
  114.  
  115.  
  116.  
  117.         # use a 1mm buffer around the inside of the box, and a few
  118.  
  119.         # pixels between each line
  120.  
  121.         self.pageHeight = self.y2 - self.y1 - 2*self.logUnitsMM
  122.  
  123.         font = wx.Font(FONTSIZE, wx.TELETYPE, wx.NORMAL, wx.NORMAL)
  124.  
  125.         dc.SetFont(font)
  126.  
  127.         self.lineHeight = dc.GetCharHeight()
  128.  
  129.         self.linesPerPage = int(self.pageHeight/self.lineHeight)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.     def OnPreparePrinting(self):
  136.  
  137.         # calculate the number of pages
  138.  
  139.         dc = self.GetDC()
  140.  
  141.         self.CalculateScale(dc)
  142.  
  143.         self.CalculateLayout(dc)
  144.  
  145.         self.numPages = len(self.lines) / self.linesPerPage
  146.  
  147.         if len(self.lines) &#37; self.linesPerPage != 0:
  148.  
  149.             self.numPages += 1
  150.  
  151.  
  152.  
  153.  
  154.  
  155.     def OnPrintPage(self, page):
  156.  
  157.         dc = self.GetDC()
  158.  
  159.         self.CalculateScale(dc)
  160.  
  161.         self.CalculateLayout(dc)
  162.  
  163.  
  164.  
  165.         # draw a page outline at the margin points
  166.  
  167.         dc.SetPen(wx.Pen("black", 0))
  168.  
  169.         dc.SetBrush(wx.TRANSPARENT_BRUSH)
  170.  
  171.         r = wx.RectPP((self.x1, self.y1),
  172.  
  173.                       (self.x2, self.y2))
  174.  
  175.         dc.DrawRectangleRect(r)
  176.  
  177.         dc.SetClippingRect(r)
  178.  
  179.  
  180.  
  181.         # Draw the text lines for this page
  182.  
  183.         line = (page-1) * self.linesPerPage
  184.  
  185.         x = self.x1 + self.logUnitsMM
  186.  
  187.         y = self.y1 + self.logUnitsMM
  188.  
  189.         while line < (page * self.linesPerPage):
  190.  
  191.             dc.DrawText(self.lines[line], x, y)
  192.  
  193.             y += self.lineHeight
  194.  
  195.             line += 1
  196.  
  197.             if line >= len(self.lines):
  198.  
  199.                 break
  200.  
  201.         return True
  202.  
  203.  
  204.  
  205.  
  206.  
  207. class PrintFrameworkSample(wx.Frame):
  208.  
  209.     def __init__(self):
  210.  
  211.         wx.Frame.__init__(self, None, size=(640, 480),
  212.  
  213.                           title="Print Framework Sample")
  214.  
  215.         self.CreateStatusBar()
  216.  
  217.  
  218.  
  219.         # A text widget to display the doc and let it be edited
  220.  
  221.         self.tc = wx.TextCtrl(self, -1, "",
  222.  
  223.                               style=wx.TE_MULTILINE|wx.TE_DONTWRAP)
  224.  
  225.         self.tc.SetFont(wx.Font(FONTSIZE, wx.TELETYPE, wx.NORMAL, wx.NORMAL))
  226.  
  227.         filename = os.path.join(os.path.dirname(__file__), "sample-text.txt")
  228.  
  229.         self.tc.SetValue(open(filename).read())
  230.  
  231.         self.tc.Bind(wx.EVT_SET_FOCUS, self.OnClearSelection)
  232.  
  233.         wx.CallAfter(self.tc.SetInsertionPoint, 0)
  234.  
  235.  
  236.  
  237.         # Create the menu and menubar
  238.  
  239.         menu = wx.Menu()
  240.  
  241.         item = menu.Append(-1, "Page Setup...\tF5",
  242.  
  243.                            "Set up page margins and etc.")
  244.  
  245.         self.Bind(wx.EVT_MENU, self.OnPageSetup, item)
  246.  
  247.         item = menu.Append(-1, "Print Setup...\tF6",
  248.  
  249.                            "Set up the printer options, etc.")
  250.  
  251.         self.Bind(wx.EVT_MENU, self.OnPrintSetup, item)
  252.  
  253.         item = menu.Append(-1, "Print Preview...\tF7",
  254.  
  255.                            "View the printout on-screen")
  256.  
  257.         self.Bind(wx.EVT_MENU, self.OnPrintPreview, item)
  258.  
  259.         item = menu.Append(-1, "Print...\tF8", "Print the document")
  260.  
  261.         self.Bind(wx.EVT_MENU, self.OnPrint, item)
  262.  
  263.         menu.AppendSeparator()
  264.  
  265.         item = menu.Append(-1, "E&xit", "Close this application")
  266.  
  267.         self.Bind(wx.EVT_MENU, self.OnExit, item)
  268.  
  269.        
  270.  
  271.         menubar = wx.MenuBar()
  272.  
  273.         menubar.Append(menu, "&File")
  274.  
  275.         self.SetMenuBar(menubar)
  276.  
  277.  
  278.  
  279.         # initialize the print data and set some default values
  280.  
  281.         self.pdata = wx.PrintData()
  282.  
  283.         self.pdata.SetPaperId(wx.PAPER_LETTER)
  284.  
  285.         self.pdata.SetOrientation(wx.PORTRAIT)
  286.  
  287.         self.margins = (wx.Point(15,15), wx.Point(15,15))
  288.  
  289.  
  290.  
  291.  
  292.  
  293.     def OnExit(self, evt):
  294.  
  295.         self.Close()
  296.  
  297.  
  298.  
  299.  
  300.  
  301.     def OnClearSelection(self, evt):
  302.  
  303.         evt.Skip()
  304.  
  305.         wx.CallAfter(self.tc.SetInsertionPoint,
  306.  
  307.                      self.tc.GetInsertionPoint())
  308.  
  309.  
  310.  
  311.  
  312.  
  313.     def OnPageSetup(self, evt):
  314.  
  315.         data = wx.PageSetupDialogData()
  316.  
  317.         data.SetPrintData(self.pdata)
  318.  
  319.  
  320.  
  321.         data.SetDefaultMinMargins(True)
  322.  
  323.         data.SetMarginTopLeft(self.margins[0])
  324.  
  325.         data.SetMarginBottomRight(self.margins[1])
  326.  
  327.  
  328.  
  329.         dlg = wx.PageSetupDialog(self, data)
  330.  
  331.         if dlg.ShowModal() == wx.ID_OK:
  332.  
  333.             data = dlg.GetPageSetupData()
  334.  
  335.             self.pdata = wx.PrintData(data.GetPrintData()) # force a copy
  336.  
  337.             self.pdata.SetPaperId(data.GetPaperId())
  338.  
  339.             self.margins = (data.GetMarginTopLeft(),
  340.  
  341.                             data.GetMarginBottomRight())
  342.  
  343.         dlg.Destroy()
  344.  
  345.  
  346.  
  347.  
  348.  
  349.     def OnPrintSetup(self, evt):
  350.  
  351.         data = wx.PrintDialogData(self.pdata)
  352.  
  353.         dlg = wx.PrintDialog(self, data)
  354.  
  355.         dlg.GetPrintDialogData().SetSetupDialog(True)
  356.  
  357.         dlg.ShowModal();
  358.  
  359.         data = dlg.GetPrintDialogData()
  360.  
  361.         self.pdata = wx.PrintData(data.GetPrintData()) # force a copy
  362.  
  363.         dlg.Destroy()
  364.  
  365.  
  366.  
  367.  
  368.  
  369.     def OnPrintPreview(self, evt):
  370.  
  371.         data = wx.PrintDialogData(self.pdata)
  372.  
  373.         text = self.tc.GetValue()
  374.  
  375.         printout1 = TextDocPrintout(text, "title", self.margins)
  376.  
  377.         printout2 = None #TextDocPrintout(text, "title", self.margins)
  378.  
  379.         preview = wx.PrintPreview(printout1, printout2, data)
  380.  
  381.         if not preview.Ok():
  382.  
  383.             wx.MessageBox("Unable to create PrintPreview!", "Error")
  384.  
  385.         else:
  386.  
  387.             # create the preview frame such that it overlays the app frame
  388.  
  389.             frame = wx.PreviewFrame(preview, self, "Print Preview",
  390.  
  391.                                     pos=self.GetPosition(),
  392.  
  393.                                     size=self.GetSize())
  394.  
  395.             frame.Initialize()
  396.  
  397.             frame.Show()
  398.  
  399.  
  400.  
  401.  
  402.  
  403.     def OnPrint(self, evt):
  404.  
  405.         data = wx.PrintDialogData(self.pdata)
  406.  
  407.         printer = wx.Printer(data)
  408.  
  409.         text = self.tc.GetValue()
  410.  
  411.         printout = TextDocPrintout(text, "title", self.margins)
  412.  
  413.         useSetupDialog = True
  414.  
  415.         if not printer.Print(self, printout, useSetupDialog) \
  416.  
  417.            and printer.GetLastError() == wx.PRINTER_ERROR:
  418.  
  419.             wx.MessageBox(
  420.  
  421.                 "There was a problem printing.\n"
  422.  
  423.                 "Perhaps your current printer is not set correctly?",
  424.  
  425.                 "Printing Error", wx.OK)
  426.  
  427.         else:
  428.  
  429.             data = printer.GetPrintDialogData()
  430.  
  431.             self.pdata = wx.PrintData(data.GetPrintData()) # force a copy
  432.  
  433.         printout.Destroy()
  434.  
  435.        
  436.  
  437.    
  438.  
  439. app = wx.PySimpleApp()
  440.  
  441. frm = PrintFrameworkSample()
  442.  
  443. frm.Show()
  444.  
  445. app.MainLoop()
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 15:13.