 |
Club Builder Foro de C++Builder en español
|
| Ver tema anterior :: Ver tema siguiente |
| Autor |
Mensaje |
Cesar C. Salazar Gonzalez Master


Registrado: 01 Oct 2002Mensajes: 2155Ubicación: San Cristóbal de Las Casas, Chiapas
|
Publicado: Vie 09 Abr, 2004 3:33 am Asunto: Impresion en Matriz de Puntos |
|
|
bueno, despues de mucho trabajo, he podido generar esta sencilla funcion, para imprimir el contenido de una memo, o de un arreglo de lineas, (strignlist), esta funcion permite imprimir linea por linea, el contenido tal y como se presenta en un TMemo, ideal para Facturas, o Ticktes, espero que les Sirva y se aceptan Criticas... Saludos
| Código: |
//-----------------------------------------------------------------------------
////////////Impresion EN MODO TEXTO PARA EVITAR EL SPOOLER DE WINDOW
// PARA IMPRESORAS DE MATRIZ TAMBIEN SIRVE PARA IMPRESORA FISCAL
// O MINIPRINTER
// REALIZADA POR:
// CESAR CUAUHTEMOC SALAZAR GONZALEZ.
// 06/04/04, ESPERO LES SIRVA..
//
// PARAMETROS DE LA FUNCION
//
// LINEAS ->lo que se desea imprimir, ARREGLO DE LINEAS.
// INICIO -> HABILITAR TIPO LETRAS EN MATRIZ, "\xF"-CONDENSADO "\xE"-EXPAND
// FIN -> DESHABILITAR TIPO LETRAS "\X12" IMPRESION NORMAL
// EJECT -> EXPULSAR HOJA O PONER MAS LINEAS "\xC"-EXPL "\N\N\N"-MAS LINEAS
// IMPRESORA -> A DONDE? LOCAL "EPSON" O RED "\\EPSON" // BAJO WINDOS.
// TITULO -> TITULO DE IMPRESION.
//
// POR EJEMPLO
// TStringList* MyList = new TStringList();
// MyList->AddStrings(this->Memo1->Lines);
// ImprimirLineas(MyList,"\xF","\x12","\xC","HP DeskJet 420","PRUEBA");
//----------
// ANEXO ("\x0d\x0a" Fin y nueva linea)
////////////////////////////////////////////////////////////////////////////
void __fastcall ImprimirLineas( TStringList *LINEAS,char *INICIO,char *FIN,
char *EJECT,AnsiString IMPRESORA,
AnsiString TITULO){
struct {
char *DocName;
char *OutputFile;
char *DataType;
} DocInfo;
DocInfo.DocName = TITULO.c_str();
DocInfo.OutputFile = 0;
DocInfo.DataType = "RAW";
// Obtener un handle de impresora
HANDLE hPrinter;
if (! OpenPrinter(IMPRESORA.c_str(), &hPrinter, 0))
throw Exception("Operación inválida con la impresora");
try {
// Informar al spooler del comienzo de impresión
if (StartDocPrinter(hPrinter, 1, LPBYTE(&DocInfo)) == 0)
throw Exception("Operación inválida con la impresora");
try {
// Iniciar una página
if (! StartPagePrinter(hPrinter))
throw Exception("Operación inválida con la impresora");
try {
// Enviar los datos directamente
///////////////////////
// PREPARAR LA ULTIMA LINEA
for(int i=0;i < LINEAS->Count;i++){
// INICIO CADENA \R\N FIN
AnsiString vLinea=INICIO+LINEAS->Strings[i]+FIN+"\x0d\x0a";
char* lineToPrint;
DWORD numBytesWritten;
lineToPrint=vLinea.c_str(); // convertir linea a cadena
WritePrinter(hPrinter,(LPVOID)lineToPrint,(DWORD) strlen(lineToPrint), &numBytesWritten);
}
char* lineToPrint;
DWORD numBytesWritten;
lineToPrint=EJECT; // si lleva se expulas "\xC"
WritePrinter(hPrinter,(LPVOID)lineToPrint,(DWORD) strlen(lineToPrint), &numBytesWritten);
////////////////////
}
__finally {
// Terminar la página
if (! EndPagePrinter(hPrinter))
throw Exception("Operación inválida con la impresora");
}
}
__finally {
// Informar al spooler del fin de impresión
if (! EndDocPrinter(hPrinter))
throw Exception("Operación inválida con la impresora");
}
}
__finally {
// Devolver el handle de impresora
ClosePrinter(hPrinter);
}
} |
saludos... _________________

Ultima edición por Cesar C. Salazar Gonzalez el Lun 24 Oct, 2005 6:38 am, editado 1 vez |
|
| Volver arriba |
|
 |
Rigoberto Martínez Ramíre Cdt

Registrado: 19 May 2004Mensajes: 16
|
Publicado: Mie 19 May, 2004 1:04 am Asunto: Re: Impresion en Matriz de Puntos |
|
|
César ... he probado el código que compartes y es sumamente eficiente .. y me he tomado el atrevimiento de ponerlo en una clase ... espero te sea y les sea de utilidad a los que quieran implementar tu rutina de impresion ...
| Código: |
//-----------------------------------------------------------------------------
////////////Impresion EN MODO TEXTO PARA EVITAR EL SPOOLER DE WINDOW
// PARA IMPRESORAS DE MATRIZ TAMBIEN SIRVE PARA IMPRESORA FISCAL
// O MINIPRINTER
// REALIZADA POR:
// CESAR CUAUHTEMOC SALAZAR GONZALEZ.
// 06/04/04, ESPERO LES SIRVA..
//
// LINEAS ->lo que se desea imprimir, ARREGLO DE LINEAS.
// INICIO -> HABILITAR TIPO LETRAS EN MATRIZ, "\xF"-CONDENSADO "\xE"-EXPAND
// FIN -> DESHABILITAR TIPO LETRAS "\X12" IMPRESION NORMAL
// EJECT -> EXPULSAR HOJA O PONER MAS LINEAS "\xC"-EXPL "\N\N\N"-MAS LINEAS
// IMPRESORA -> A DONDE? LOCAL "EPSON" O RED "\\EPSON" // BAJO WINDOS.
// TITULO -> TITULO DE IMPRESION.
//
// POR EJEMPLO
// TStringList* MyList = new TStringList();
// MyList->AddStrings(this->Memo1->Lines);
// ImprimirLineas(MyList,"\xF","\x12","\xC","HP DeskJet 420","PRUEBA");
//----------
// ANEXO ("\x0d\x0a" Fin y nueva linea)
////////////////////////////////////////////////////////////////////////////
//TU EJEMPLO QUEDARIA ASI
TPrintText *aptPrinter = NULL;
try{
TPrintText *aptPrinter = new TPrintText();
aptPrinter->SetMarcas("\xF", "\x12", "\xC");
aptPrinter->SetPrinterName("HP DeskJet 420");
aptPrinter->Print((TStringList *)Memo1->Lines, "PRUEBA");
delete aptPrinter;
aptPrinter = NULL;
}
catch(Exception &err){
//catch(...){
if (aptPrinter != NULL) {delete aptPrinter; aptPrinter = NULL;}
throw Exception(err.Message);
}
//ESTO VA EN EL HEADER
//---------------------------------------------------------------------------
class TPrintText : public TObject{
private:
char *ptrBegin, *ptrEnd, *prtEject;
DWORD dwLevel;
DOC_INFO_1 Doc_Info_1; //winspool.h
DOC_INFO_2 Doc_Info_2; //winspool.h
AnsiString stPrinterName;
bool boIsWin95;
public:
__fastcall TPrintText();
__fastcall ~TPrintText();
void __fastcall Clear();
void __fastcall SetMarcas(char *_ptrBegin, char *_ptrEnd, char *_prtEject);
void __fastcall SetPrinterName(const AnsiString _stPrinterName);
void __fastcall Print(TStringList *_Strings, const AnsiString _stTitulo);
__property char *Inicio = {read = ptrBegin};
__property char *Fin = {read = ptrEnd};
__property char *Expulsar = {read = prtEject};
__property AnsiString Impresora = {read = stPrinterName};
};
//---------------------------------------------------------------------------
//ESTO VA EN EL CPP
__fastcall TPrintText::TPrintText(){
Clear();
//VER_PLATFORM_WIN32s System is Win32s.
//VER_PLATFORM_WIN32_WINDOWS System is Windows 95.
//VER_PLATFORM_WIN32_NT System is Windows NT.
switch(Win32Platform){
case VER_PLATFORM_WIN32s :
case VER_PLATFORM_WIN32_WINDOWS : boIsWin95 = true; break;
case VER_PLATFORM_WIN32_NT : boIsWin95 = false; break;
}
if (!boIsWin95){
Doc_Info_1.pOutputFile = "";
Doc_Info_1.pDatatype = "RAW";
dwLevel = 1;
}
else{
Doc_Info_2.pOutputFile = "";
Doc_Info_2.pDatatype = "RAW";
dwLevel = 2;
}
}
__fastcall TPrintText::~TPrintText(){}
void __fastcall TPrintText::Clear(){
ptrBegin = "";
ptrEnd = "";
prtEject = "";
stPrinterName = "";
}
void __fastcall TPrintText::SetMarcas(char *_ptrBegin, char *_ptrEnd,
char *_prtEject)
{
ptrBegin = _ptrBegin;
ptrEnd = _ptrEnd;
prtEject = _prtEject;
}
void __fastcall TPrintText::SetPrinterName(const AnsiString _stPrinterName)
{
stPrinterName = _stPrinterName.Trim();
}
void __fastcall TPrintText::Print(TStringList *_Strings,
const AnsiString _stTitulo)
{
HANDLE hPrinter;
AnsiString stMsgException = "";
bool boOpen, boStartDoc, boStartPage;
boOpen = false;
boStartDoc = false;
boStartPage = false;
try{
//Obtener un handle de impresora
boOpen = OpenPrinter(stPrinterName.c_str(), &hPrinter, 0);
if (!boOpen) stMsgException = "No se pudo Obtener un handle de impresora";
if (boOpen){//Informar al spooler del comienzo de impresión
if (!boIsWin95){
Doc_Info_1.pDocName = _stTitulo.c_str();
boStartDoc = StartDocPrinter(hPrinter, dwLevel, LPBYTE(&Doc_Info_1)) != 0;
}
else{
Doc_Info_2.pDocName = _stTitulo.c_str();
boStartDoc = StartDocPrinter(hPrinter, dwLevel, LPBYTE(&Doc_Info_2)) != 0;
}
if (!boStartDoc) stMsgException = "No se pudo Informar al spooler del comienzo de impresión";
}
if (boStartDoc){// Iniciar una página
boStartPage = StartPagePrinter(hPrinter);
if (!boStartPage) stMsgException = "No se pudo Iniciar una página";
}
if (!boOpen || !boStartDoc || !boStartPage){
if (boStartPage) boStartPage = !EndPagePrinter(hPrinter);
if (boStartDoc) boStartDoc = !EndDocPrinter(hPrinter);
if (boOpen) boOpen = !ClosePrinter(hPrinter);
throw Exception(stMsgException);
//El trhow envia al catch ... y si alguno no se pudo cerrar adecuadamente
//ahi se intenta nuevamente
}
AnsiString stLinea;
int iCount;
DWORD dwNumBytesWritten;
stLinea = "";
iCount = _Strings->Count;
for(int iIdx = 0; iIdx < iCount; iIdx++){
stLinea = ptrBegin + _Strings->Strings[iIdx] + ptrEnd + "\x0d\x0a";
WritePrinter(hPrinter,(LPVOID)stLinea.c_str(),(DWORD)stLinea.Length(), &dwNumBytesWritten);
}
stLinea = prtEject; // si lleva se expulas "\xC"
WritePrinter(hPrinter,(LPVOID)stLinea.c_str(),(DWORD)stLinea.Length(), &dwNumBytesWritten);
EndPagePrinter(hPrinter);
EndDocPrinter(hPrinter);
ClosePrinter(hPrinter);
}
catch(Exception &err){
if (boStartPage) EndPagePrinter(hPrinter);
if (boStartDoc) EndDocPrinter(hPrinter);
if (boOpen) ClosePrinter(hPrinter);
throw Exception(err.Message);
}
}
//--------------------------------------------------------------------------
|
el codigo fue realizado por varios usuarios del foro, pero a todos los que reconozcan parte de su codigo, le envio un saludo, ahora si estoy seguro que imprime y muy bien... |
|
| Volver arriba |
|
 |
Cesar C. Salazar Gonzalez Master


Registrado: 01 Oct 2002Mensajes: 2155Ubicación: San Cristóbal de Las Casas, Chiapas
|
Publicado: Mie 19 May, 2004 3:58 am Asunto: |
|
|
un poco larga, pero sigue siendo funcional... gracias.. _________________
 |
|
| Volver arriba |
|
 |
ikis Master


Registrado: 28 Dic 2002Mensajes: 703Ubicación: Madrid, España
|
Publicado: Sab 19 Jun, 2004 4:06 am Asunto: |
|
|
| César, probaste este código con una impresora fiscal EPSON TM-2000 AF ? |
|
| Volver arriba |
|
 |
Cesar C. Salazar Gonzalez Master


Registrado: 01 Oct 2002Mensajes: 2155Ubicación: San Cristóbal de Las Casas, Chiapas
|
Publicado: Lun 21 Jun, 2004 11:08 pm Asunto: |
|
|
lo que puedo decirte, es que si, funciona... para impresiones rapidas.. no importa en que impresora la uses... te recomiendo probarla... _________________
 |
|
| Volver arriba |
|
 |
gsllamas Cdt

Registrado: 26 Jun 2004Mensajes: 5Ubicación: Ensenada, B.C. Mexico
|
Publicado: Sab 26 Jun, 2004 7:16 pm Asunto: Re: Impresion en Matriz de Puntos |
|
|
Cesar, he probado tu codigo en WindowsXP y funciona muy bien, sin embargo la aplicacion que estoy haciendo la quise utilizar en Windows98 y simplemente no imprime nada, ni siquiera se observa algun trabajo en espera de ser impreso ni nada.
Sabes cual es la diferencia o por que no "me funciona" en Windows98?
Gracias.
Gabriel Santillan Llamas
| César C. Salazar González escribió: | | bueno, despues de mucho trabajo, he podido generar esta sencilla funcion, para imprimir el contenido de una memo, o de un arreglo de lineas, (strignlist), esta funcion permite imprimir l... |
|
|
| Volver arriba |
|
 |
Cesar C. Salazar Gonzalez Master


Registrado: 01 Oct 2002Mensajes: 2155Ubicación: San Cristóbal de Las Casas, Chiapas
|
Publicado: Lun 28 Jun, 2004 8:41 am Asunto: |
|
|
te he contestado en el foro, esto es solo para tips & Tricks _________________
 |
|
| Volver arriba |
|
 |
jotny Master


Registrado: 17 Feb 2004Mensajes: 226Ubicación: santiago
|
Publicado: Vie 01 Dic, 2006 5:28 pm Asunto: No comprendo lo de los saltos de linea |
|
|
Estimado CESAR.
he probado el codigo y funciona, el problema es que la factura que quiero imprimir puedo posicionar con espacios y los textos.... pero al poner un enter adicional en las lineas del memo... no alinea bien y quedan corridas.
Como se puede ver en tu codigo los CM o MM que debe quedar al momento del salto?....los ENTER en el memo son mas de lo que necesito para imprimir la proxima linea, e imprimir inmediatamente la linea siguiente con la informacion es demasiado poro el espacio que deja entre lineas... osea sin ENTER quedan corridas para arriba, y con ENTER quedan corridas mas abajo.
Como se puede solucionar esto?... a lo mejor en tu codigo se puede pero no entiendo en que parametro o que opcion...
Gracias y espero no sea muy complicado lo que he expuesto. |
|
| Volver arriba |
|
 |
rockman2003 Master

Registrado: 27 Ene 2004Mensajes: 202Ubicación: Madrid
|
Publicado: Mar 30 Mar, 2010 8:01 pm Asunto: |
|
|
Hola Cesar,
Llevaba usando la función durante 3 años lo menos.
El problema, es que ahora en RAD2010, me salta el error
Return statement not allowed in __finally block
He estado mirando en internet y no encuentro una respuesta clara.
Voy a ver si doy con la solución. |
|
| Volver arriba |
|
 |
rockman2003 Master

Registrado: 27 Ene 2004Mensajes: 202Ubicación: Madrid
|
Publicado: Mar 30 Mar, 2010 8:21 pm Asunto: |
|
|
Estooo.... olvidad ese mensaje.
Debe ser que yo he utilizado alguna derivacion del codigo de Cesar, ya que éste no tiene ningun return dentro de los bloques finally. |
|
| Volver arriba |
|
 |
|
|
No puedes publicar temas nuevos en este foro No puedes responder a temas en este foro No puedes editar tus mensajes en este foro No puedes borrar tus mensajes en este foro No puedes votar en las encuestas de este foro
|
© 2002–2026 Club Builder · Funciona con phpBB.
|