Print from WEB / Imprimir desde WEB

Print from WEB / Imprimir desde WEB

Postby Daniel Garcia-Gil » Sun Mar 04, 2012 5:42 pm

Dejo un ejemplo que podemos imprimor desde la WEB en formato RAW sin pasar por el dialogo de impresion del navegador, solo trabaja en navegadores con websocket

i leave a sample to print from WEB in RAW format without call the print dialog, only work with browser with websocket

Descargar ejecutable / Download exe

Ejecutar desde consola / run from console

test NONE

con ESC sale del programa / exit with ESC

abrir la siguiente url / open the url

http://danielgarciagil.com/print (no funciona si el ejecutable no esta corriendo / no work if exe is not running )

PRG

Code: Select all  Expand view

#include "hbclass.ch"
#include "FileIO.ch"
#include "hbwin.ch"

#define CRLF Chr(13)+Chr(10)

#xcommand REPEAT        => while .t.
#xcommand DO            => while .t.
#xcommand UNTIL <uExpr> => if <uExpr>; exit; end; end

#xcommand DEFAULT <uVar1> := <uVal1> ;
               [, <uVarN> := <uValN> ] => ;
                  If( <uVar1> == nil, <uVar1> := <uVal1>, ) ;;
                [ If( <uVarN> == nil, <uVarN> := <uValN>, ); ]

function main( cMode )

  LOCAL oSrv
  LOCAL oPrn

  DEFAULT cMode := "S"


  oSrv := WebSocketServer():New( "8080", cMode, {| oServer | OnInit( oServer ) } )
 
  if ! oSrv:lBackground
     oSrv:Activate()
  endif

 
return nil  

//-----------------------------------------//

function OnInit( oSrv )

  oSrv:bOnNewClient = {| oClient | NewClient( oSrv, oClient ) }
  oSrv:bOnHandleEvent = {| nEvent, wParam, lParam, cParam, oClient | HandleEvent( nEvent, wParam, lParam, cParam, oClient ) }  

return nil

//-----------------------------------------//

function printTexto( hBuffer )

   local oPrn
   local hLine
   local cBuffer := ""
   local cPrinter
 
   oPrn := TRawPrint():New()
 
   for each hLine in hBuffer[ "texto" ]
      oPrn:say( hLine["row"], hLine["col"], hLine["text"] )
   next
   
   oPrn:Print( hBuffer[ "printer" ] )


return nil

//-----------------------------------------//

function getPrinterList( oClient )

   local aPrinter := Win_PrinterList()
   local hJson := { => }
   local nLen, cJSon
   
   hJSon[ "ACTION" ] = "PRINTERS"

   hJson[ "PARAMETERS" ] = { aPrinter, WIN_PrinterGetDefault() }

   cJSon := hb_JSonEncode( hJson, @nlen, .T. )
   
   oClient:SendData( cJSon )

return nil


//-----------------------------------------//


function HandleEvent( nEvent, wParam, lParam, cParam, oClient )

   local hJSon, nTipo
   local nJson
   nJSon = hb_jsonDecode( cParam, @hJSon )
   
   switch nEvent
      case 1
         getPrinterList( oClient )
         exit
      case 2
         printTexto( hJSon )
         exit      
   endswitch

return nil

//-----------------------------------------//

function NewClient( oSrv, oClient )

   local nLen
   local nPos
   local o

   //accept only one connection (only for test)
   //if there are a new conection, will kill old
   
   nLen = Len( oSrv:hClients )
   if nLen > 1
      nPos := hb_HScan( oSrv:hClients, {|k| k  != oClient:nID } )
      if nPos > 0
         o = hb_HValueAt( oSrv:hClients, nPos )
         oSrv:KillClient( o )
      endif      
   endif
   
RETURN NIL


#xtranslate nTrim( <n>, <i>, <d> )  => AllTrim( Str( <n>, <i>, <d> ) )

//----------------------------------------------------------------------------//

CLASS TRawPrint
   
   DATA hRow, hCol HIDDEN
   
   DATA hDC, nRow, nCol, nLeftMargin, nTopMargin      AS NUMERIC
   DATA lFile                                         AS LOGICAL
   DATA onNewPage
   DATA nPage                                         AS NUMERIC
   DATA onEndPage
   DATA onClose
   DATA aBuffer                                       AS ARRAY
   DATA lAnsiToOem                                    AS LOGICAL

   METHOD New( lFile, onNewPage, onEndPage, onClose ) CONSTRUCTOR
   
   METHOD Print( cPrinter )
   
   METHOD Say( nRow, nCol, cText, lInsert )
   
ENDCLASS

//----------------------------------------------------------------------------//

METHOD New( lFile, onNewPage, onEndPage, onClose  ) CLASS TRawPrint

   DEFAULT lFile := .F.

   ::nLeftMargin  = 0
   ::nTopMargin   = 0
   ::nRow         = 0
   ::nCol         = 0
   ::lAnsiToOem   = .T.
   ::hDC          = -1  
   ::lFile        = lFile
   ::onNewPage    = onNewPage
   ::onEndPage    = onEndPage
   ::onClose      = onClose
   ::nPage        = 1
   ::aBuffer      = {}

RETURN Self

//----------------------------------------------------------------------------//

METHOD Print( cPrinter ) CLASS TRawPrint
   
   local cBuffer := ""
   local cLine
   
   DEFAULT cPrinter := WIN_PrinterGetDefault()

   for each cLine in ::aBuffer
      cBuffer += cLine + CRLF
   next

   WIN_PrintBufferRaw( cPrinter , cBuffer )  

RETURN NIL



//----------------------------------------------------------------------------//

METHOD Say( nRow, nCol, cText, lInsert ) CLASS TRawPrint
   local nLen := Len( ::aBuffer )
   local n
   local nLenStr, nLenSub
   local cStr, cSubstr
   local cNewLine := ""
   
   DEFAULT lInsert := .F.
   
   if nRow > nLen
      for n = nLen + 1 to nRow
         AAdd( ::aBuffer, "" )
      next
   endif
   
   cStr    = ::aBuffer[ nRow ]
   cSubstr = PadR( cStr, nCol, " " )
   
   if lInsert
      cNewLine = Stuff( cSubstr, nCol, 0, cText )
   else
      cNewLine = Stuff( cSubstr, nCol, Len( cText ), cText )
   endif
   
   ::aBuffer[ nRow ] = cNewLine
   
RETURN NIL


 
User avatar
Daniel Garcia-Gil
 
Posts: 2365
Joined: Wed Nov 02, 2005 11:46 pm
Location: Isla de Margarita

Re: Print from WEB / Imprimir desde WEB

Postby karinha » Thu Jul 12, 2012 4:25 pm

Daniel, el link no funciona más.
João Santos - São Paulo - Brasil - Phone: +55(11)95150-7341
User avatar
karinha
 
Posts: 7154
Joined: Tue Dec 20, 2005 7:36 pm
Location: São Paulo - Brasil

Re: Print from WEB / Imprimir desde WEB

Postby pablovidal » Sat Jul 14, 2012 6:36 pm

Hola Daniel,

Estoy usando xHarbour y la funcion WIN_PrintBufferRaw no la encuentro ???
Es propia de harbour o es propia tuya ???
Saludos,

Pablo Alberto Vidal
/*
------------------------------------------------------
Harbour 3.2.0, Fivewin 17.02, BCC7
------------------------------------------------------
*/
User avatar
pablovidal
 
Posts: 401
Joined: Thu Oct 06, 2005 10:15 pm
Location: Republica Dominicana

Re: Print from WEB / Imprimir desde WEB

Postby Daniel Garcia-Gil » Sat Jul 14, 2012 7:37 pm

karinha wrote:Daniel, el link no funciona más.


Hola a la brevedad activo el link nuevamente

pablovidal wrote:Hola Daniel,

Estoy usando xHarbour y la funcion WIN_PrintBufferRaw no la encuentro ???
Es propia de harbour o es propia tuya ???


si es propia...
aqi esta el fuente

Code: Select all  Expand view

HB_FUNC( WIN_PRINTBUFFERRAW )
{
   int iResult = -1;

#if ! defined( HB_OS_WIN_CE )
   if( HB_ISCHAR( 1 ) && HB_ISCHAR( 2 ) )
   {
      const char * pszSource = hb_parc( 2 );
      HB_SIZE length = hb_parclen( 2 );

      HANDLE hPrinter;
      void * hDeviceName;
      LPCTSTR lpDeviceName = HB_PARSTR( 1, &hDeviceName, NULL );

      if( OpenPrinter( ( LPTSTR ) lpDeviceName, &hPrinter, NULL ) != 0 )
      {
         void * hDocName;

         DOC_INFO_1 DocInfo;
         DocInfo.pDocName = ( LPTSTR ) HB_PARSTR( HB_ISCHAR( 3 ) ? 3 : 2, &hDocName, NULL );
         DocInfo.pOutputFile = NULL;
         DocInfo.pDatatype = ( LPTSTR ) TEXT( "RAW" );
         if( StartDocPrinter( hPrinter, 1, ( LPBYTE ) &DocInfo ) != 0 )
         {
            if( StartPagePrinter( hPrinter ) != 0 )
            {
                 
                  HB_SIZE nMaxLen = min( HB_PRINT_BUFFER_SIZE, length ), nRead;
                  HB_BYTE * pbyBuffer = ( HB_BYTE * ) hb_xgrab( nMaxLen );

                  iResult = 1;
                  nRead = nMaxLen;
                  memcpy( pbyBuffer,  ( BYTE * ) pszSource,  nRead );
                  while( nRead > 0 )
                  {
                     DWORD nWritten = 0;

                     while( nWritten < nRead )
                     {
                        DWORD dwWritten = 0;
                        if( !WritePrinter( hPrinter, &pbyBuffer[ nWritten ],
                                           ( DWORD ) ( nRead - nWritten ),
                                           &dwWritten ) )
                        {
                           iResult = -7;
                           break;
                        }
                        else if( dwWritten == 0 )
                        {
                           iResult = -8;
                           break;
                        }
                        nWritten += dwWritten;
                     }
//                     if( nWritten < nRead )
//                        break;
                       
                     pszSource += nRead;
                     nRead = min( HB_PRINT_BUFFER_SIZE,  strlen( pszSource ) ) ;
                     if( nRead > 0 ){
                        memcpy( pbyBuffer,  ( BYTE * ) pszSource,  nRead );                    
                        if( nRead < nMaxLen ){
                           *(pbyBuffer+nRead + 1) = '\0';
                        }
                     }
                     else
                        break;
                  }

                  hb_xfree( pbyBuffer );
               EndPagePrinter( hPrinter );
            }
            else
               iResult = -4;
            EndDocPrinter( hPrinter );
         }
         else
            iResult = -3;

         ClosePrinter( hPrinter );

         hb_strfree( hDocName );
      }
      else
         iResult = -2;

      hb_strfree( hDeviceName );
   }
#endif
   
   hb_retni( iResult );
}
 
User avatar
Daniel Garcia-Gil
 
Posts: 2365
Joined: Wed Nov 02, 2005 11:46 pm
Location: Isla de Margarita

Re: Print from WEB / Imprimir desde WEB

Postby Bayron » Fri Apr 05, 2013 4:25 am

Hola Daniel,

PrintFileRaw() imprime un Archivo, quisiera imprimir sin tener que grabar en disco...
Existe alguna función parecida para imprimir una variable desde una aplicacion desktop... o puede ésta misma ser usada????

Intenté usar ésta, pero me dió los siguiente errores:

Code: Select all  Expand view
--------------------Configuration: Violetas - Release--------------------
Harbour 3.2.0dev (Rev. 18754)
Copyright (c) 1999-2013, http://harbour-project.org/
Embarcadero C++ 6.50 for Win32 Copyright (c) 1993-2012 Embarcadero Technologies, Inc.
MayaPOS.c:
Embarcadero C++ 6.50 for Win32 Copyright (c) 1993-2012 Embarcadero Technologies, Inc.
util.c:
Warning W8065 L:\\Violetas\\prg\\util.prg 323: Call to function 'HB_PARSTR' with no prototype in function HB_FUN_WIN_PRINTBUFFERRAW
Warning W8069 L:\\Violetas\\prg\\util.prg 323: Nonportable pointer conversion in function HB_FUN_WIN_PRINTBUFFERRAW
Warning W8065 L:\\Violetas\\prg\\util.prg 330: Call to function 'HB_PARSTR' with no prototype in function HB_FUN_WIN_PRINTBUFFERRAW
Error E2451 L:\\Violetas\\prg\\util.prg 338: Undefined symbol 'HB_PRINT_BUFFER_SIZE' in function HB_FUN_WIN_PRINTBUFFERRAW
Warning W8065 L:\\Violetas\\prg\\util.prg 392: Call to function 'hb_strfree' with no prototype in function HB_FUN_WIN_PRINTBUFFERRAW
Warning W8065 L:\\Violetas\\prg\\util.prg 397: Call to function 'hb_strfree' with no prototype in function HB_FUN_WIN_PRINTBUFFERRAW
Warning W8004 L:\\Violetas\\prg\\util.prg 398: 'length' is assigned a value that is never used in function HB_FUN_WIN_PRINTBUFFERRAW
*** 1 errors in Compile ***
Turbo Incremental Link 6.30 Copyright (c) 1997-2012 Embarcadero Technologies, Inc.
Violetas.exe - 1 error(s), 6 warning(s)
 

Si se puede usar esta función,
Que libreria me faltaría compilar???
y cual sería el valor de HB_PRINT_BUFFER_SIZE???
=====>

Bayron Landaverry
(215)2226600 Philadelphia,PA, USA
+(502)46727275 Guatemala
MayaBuilders@gMail.com

FWH12.04||Harbour 3.2.0 (18754)||BCC6.5||UEstudio 10.10||
Windows 7 Ultimate

FiveWin, One line of code and it's done...
User avatar
Bayron
 
Posts: 815
Joined: Thu Dec 24, 2009 12:46 am
Location: Philadelphia, PA

Re: Print from WEB / Imprimir desde WEB

Postby Daniel Garcia-Gil » Fri Apr 05, 2013 8:03 am

Hola

la idea la tome de la funcion original WIN_PRINTFILERAW() de harbour ubicada en contrib/hbwin/win_prn2.c

lo que te hace falta esta alli, incluso las cabeceras

Code: Select all  Expand view
#include "hbwin.h"
#include "hbwapi.h"
#include "hbapifs.h"
#include "hbapiitm.h"

#define HB_PRINT_BUFFER_SIZE  ( 32 * 1024 )
User avatar
Daniel Garcia-Gil
 
Posts: 2365
Joined: Wed Nov 02, 2005 11:46 pm
Location: Isla de Margarita

Re: Print from WEB / Imprimir desde WEB

Postby Bayron » Fri Apr 05, 2013 2:07 pm

Gracias Daniel,
Aparentemente funciona bien...
Por ahona no tengo una impresora que acepte la impresion RAW, pero puedo notar que la impresora que tengo recibe la Data...

Si alguien que tenga una impresora de matriz, pudiera hacer el favor de probarla, lo agradecería...

http://www.mayapos.com/FiveWin/rawprint.zip

Code: Select all  Expand view
#INCLUDE "FiveWin.ch"

Function Main()
        LOCAL CFILE, nHandle, Ntext
        //Printing on a Raw printer... Con o sin archivo...
       
        //Con archivo
        CFILE := "P.TXT"
        nHandle := fCreate( cFile )
        Ntext := "Hello to everyone" + CRLF
        Ntext += "Hello to everyone" + CRLF
        Ntext += "Hello to everyone" + CRLF
        Ntext += "Hello to everyone" + CRLF
        Ntext += "Hello to everyone" + CRLF
        FWRITE( nHandle, Ntext)
        fClose( nHandle )
        PrintFileRaw(getdefaultPrinter(),CFILE)
        FERASE(CFILE)
       
        //Sin archivo
        WIN_PRINTBUFFERRAW(getdefaultPrinter(),Ntext)

Return NIL


#pragma BEGINDUMP

#include <hbwin.h>
#include <hbwapi.h>
#include <hbapifs.h>
#include <hbapiitm.h>

#define HB_PRINT_BUFFER_SIZE  ( 32 * 1024 )

HB_FUNC( WIN_PRINTBUFFERRAW )
{
   int iResult = -1;

#if ! defined( HB_OS_WIN_CE )
   if( HB_ISCHAR( 1 ) && HB_ISCHAR( 2 ) )
   {
      const char * pszSource = hb_parc( 2 );
      HB_SIZE length = hb_parclen( 2 );

      HANDLE hPrinter;
      void * hDeviceName;
      LPCTSTR lpDeviceName = HB_PARSTR( 1, &hDeviceName, NULL );

      if( OpenPrinter( ( LPTSTR ) lpDeviceName, &hPrinter, NULL ) != 0 )
      {
         void * hDocName;

         DOC_INFO_1 DocInfo;
         DocInfo.pDocName = ( LPTSTR ) HB_PARSTR( HB_ISCHAR( 3 ) ? 3 : 2, &hDocName, NULL );
         DocInfo.pOutputFile = NULL;
         DocInfo.pDatatype = ( LPTSTR ) TEXT( "RAW" );
         if( StartDocPrinter( hPrinter, 1, ( LPBYTE ) &DocInfo ) != 0 )
         {
            if( StartPagePrinter( hPrinter ) != 0 )
            {
                 
                  HB_SIZE nMaxLen = min( HB_PRINT_BUFFER_SIZE, length ), nRead;
                  HB_BYTE * pbyBuffer = ( HB_BYTE * ) hb_xgrab( nMaxLen );

                  iResult = 1;
                  nRead = nMaxLen;
                  memcpy( pbyBuffer,  ( BYTE * ) pszSource,  nRead );
                  while( nRead > 0 )
                  {
                     DWORD nWritten = 0;

                     while( nWritten < nRead )
                     {
                        DWORD dwWritten = 0;
                        if( !WritePrinter( hPrinter, &pbyBuffer[ nWritten ],
                                           ( DWORD ) ( nRead - nWritten ),
                                           &dwWritten ) )
                        {
                           iResult = -7;
                           break;
                        }
                        else if( dwWritten == 0 )
                        {
                           iResult = -8;
                           break;
                        }
                        nWritten += dwWritten;
                     }
//                     if( nWritten < nRead )
//                        break;
                       
                     pszSource += nRead;
                     nRead = min( HB_PRINT_BUFFER_SIZE,  strlen( pszSource ) ) ;
                     if( nRead > 0 ){
                        memcpy( pbyBuffer,  ( BYTE * ) pszSource,  nRead );                    
                        if( nRead < nMaxLen ){
                           *(pbyBuffer+nRead + 1) = '\0';
                        }
                     }
                     else
                        break;
                  }

                  hb_xfree( pbyBuffer );
               EndPagePrinter( hPrinter );
            }
            else
               iResult = -4;
            EndDocPrinter( hPrinter );
         }
         else
            iResult = -3;

         ClosePrinter( hPrinter );

         hb_strfree( hDocName );
      }
      else
         iResult = -2;

      hb_strfree( hDeviceName );
   }
#endif
   
   hb_retni( iResult );
}

#pragma ENDDUMP
=====>

Bayron Landaverry
(215)2226600 Philadelphia,PA, USA
+(502)46727275 Guatemala
MayaBuilders@gMail.com

FWH12.04||Harbour 3.2.0 (18754)||BCC6.5||UEstudio 10.10||
Windows 7 Ultimate

FiveWin, One line of code and it's done...
User avatar
Bayron
 
Posts: 815
Joined: Thu Dec 24, 2009 12:46 am
Location: Philadelphia, PA


Return to Utilities / Utilidades

Who is online

Users browsing this forum: No registered users and 5 guests