Ejemplo n.º 1
0
JNIEXPORT jboolean JNICALL Java_org_apache_harmony_x_print_GDIClient_writePrinter
(JNIEnv *env, jclass owner, jbyteArray array, jint size, jint printerID) {
    HANDLE hPrinter = *((HANDLE *)&printerID);
    if (hPrinter != NULL) {
        signed char *data;
        data = (signed char *)env->GetByteArrayElements(array, NULL);
#ifdef PRINTING_DEBUG
        if (file != NULL) {
            fwrite(data, sizeof(signed char), size, file);
        }
#endif /* PRINTING_DEBUG */
        DWORD written = 0;
        if (WritePrinter(hPrinter, data, size, &written) != 0) {
            env->ReleaseByteArrayElements(array, (jbyte *)data, JNI_ABORT);
            return JNI_TRUE;
        }
    }
#ifdef PRINTING_DEBUG
    if (res == JNI_FALSE) {
        DWORD error = GetLastError();
        printf("Error occurred while transfering data to printer: %d.\n", error);
    }
#endif /* PRINTING_DEBUG */
    return JNI_FALSE;
}
Ejemplo n.º 2
0
BOOL SendFile(HANDLE hOutput, const TCHAR * filename, bool bPrinter)
{
	HANDLE hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, 
						NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

	if ( hFile==INVALID_HANDLE_VALUE )
		return FALSE;

	char buffer[1024];

	for (int size = GetFileSize(hFile, NULL); size; )
	{
		DWORD dwRead = 0, dwWritten = 0;

		if ( ! ReadFile(hFile, buffer, min(size, sizeof(buffer)), & dwRead, NULL) )
			break;

		if ( bPrinter )
			WritePrinter(hOutput, buffer, dwRead, & dwWritten);
		else
			WriteFile(hOutput, buffer, dwRead, & dwWritten, NULL);
		
		size -= dwRead;
	}

	return TRUE;
}
Ejemplo n.º 3
0
void mswin_printer_thread(void *arg)
{
    int fd = (int)arg;
    char pname[gp_file_name_sizeof];
    char data[4096];
    HANDLE hprinter = INVALID_HANDLE_VALUE;
    int count;
    DWORD written;
    DOC_INFO_1 di;

    /* Read from pipe and write to Windows printer.
     * First gp_file_name_sizeof bytes are name of the printer.
     */
    if (read(fd, pname, sizeof(pname)) != sizeof(pname)) {
	/* Didn't get the printer name */
	close(fd);
	return;
    }

    while ( (count = read(fd, data, sizeof(data))) > 0 ) {
	if (hprinter == INVALID_HANDLE_VALUE) {
	    if (!OpenPrinter(pname, &hprinter, NULL)) {
		close(fd);
		return;
	    }
	    di.pDocName = (LPTSTR)gs_product;
	    di.pOutputFile = NULL;
	    di.pDatatype = "RAW";
	    if (!StartDocPrinter(hprinter, 1, (LPBYTE) & di)) {
		AbortPrinter(hprinter);
		close(fd);
		return;
	    }
	}
	if (!StartPagePrinter(hprinter)) {
		AbortPrinter(hprinter);
		close(fd);
		return;
	}
	if (!WritePrinter(hprinter, (LPVOID) data, count, &written)) {
	    AbortPrinter(hprinter);
	    close(fd);
	    return;
	}
    }
    if (hprinter != INVALID_HANDLE_VALUE) {
	if (count == 0) {
	    /* EOF */
	    EndPagePrinter(hprinter);
	    EndDocPrinter(hprinter);
	    ClosePrinter(hprinter);
	}
	else {
	    /* Error */
	    AbortPrinter(hprinter);
	}
    }
    close(fd);
}
Ejemplo n.º 4
0
void
printer_write(void *data, uint len)
{
  if (printer) {
    DWORD written;
    WritePrinter(printer, data, len, &written);
  }
}
Ejemplo n.º 5
0
BOOL ClosePrinter( VOID )
    {
    if( DataInPrinterBuffer )
	WritePrinter( NEWPAGE, NULL );

    DosClose( Printer );
    return( TRUE );
    }
Ejemplo n.º 6
0
void printer_job_data(printer_job *pj, void *data, int len)
{
    DWORD written;

    if (!pj)
	return;

    WritePrinter(pj->hprinter, data, len, &written);
}
Ejemplo n.º 7
0
DWORD write_spool( PHYSDEV dev, const void *data, DWORD num )
{
    PSDRV_PDEVICE *physDev = get_psdrv_dev( dev );
    DWORD written;

    if (!WritePrinter(physDev->job.hprinter, (LPBYTE) data, num, &written) || (written != num))
        return SP_OUTOFDISK;

    return num;
}
Ejemplo n.º 8
0
BOOL OpenPrinter( VOID )
    {
    CHAR String[65];

    StdFarStrCpy( String, PrinterInfo->PrinterPort );
    DosCreate( String, &Printer, FILE_NORMAL );
    // Debug!!!!! DosCreate( "PRINTER.$$$", &Printer, FILE_NORMAL );

    WritePrinter( INIT, NULL );
    return( TRUE );
    }
Ejemplo n.º 9
0
/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT printer_win_write_printjob(rdpPrintJob* printjob, BYTE* data, int size)
{
	rdpWinPrintJob* win_printjob = (rdpWinPrintJob*) printjob;

	LPVOID pBuf = data;
	DWORD cbBuf = size;
	DWORD pcWritten;

	if(!WritePrinter(((rdpWinPrinter*)printjob->printer)->hPrinter, pBuf, cbBuf, &pcWritten))
		return ERROR_INTERNAL_ERROR;
	return CHANNEL_RC_OK;
}
Ejemplo n.º 10
0
static void printer_win_write_printjob(rdpPrintJob* printjob, BYTE* data, int size)
{
    rdpWinPrintJob* win_printjob = (rdpWinPrintJob*)printjob;

    LPVOID pBuf = data;
    DWORD cbBuf = size;
    DWORD pcWritten;

    if( ! WritePrinter( ((rdpWinPrinter*)printjob->printer)->hPrinter, pBuf, cbBuf, &pcWritten ) )
        DEBUG_WINPR("WritePrinter failed");
    ;

}
Ejemplo n.º 11
0
/*****************************************************************************
 * Write a string to the current document
*****************************************************************************/
void WriteString(char* sz, int len)
{
   int tabn = (int)CURRENT_FILE->tabsout_num;
   int i=0;
   char *p=NULL;
   char ch=0;
   DWORD dwNumWritten=0;

   if ( pd.hDC == NULL )
      return;
   if ( !documentON )
      StartDocument( );
   for (i = 0,p = sz; i < len; p++, i++)
   {
      ch = *p;
      switch ( ch )
      {
         case '\n':                             // Line-feed
            NextLine();
            break;

         case '\f' :                             // Form-feed
            NextPage();
            break;

         case '\r' :                             // Carriage-return
            column = 0;
            break;

         case '\t' :                             // Tab
            column += tabn - (column % tabn);
            if ( bLineWrapping
            && column >= LOWORD(dwCharExtent) )
               NextLine();
            break;
         default :
            if ( isprint(ch) )
            {
               if (defaultprinter)
                  TextOut(pd.hDC, column++, row, &ch, 1);
               else
                  WritePrinter( hPrinter, p, 1, &dwNumWritten );
               // Wrap line
               if ( bLineWrapping
               && column >= LOWORD(dwCharExtent) )
                  NextLine();
            }
            break;
      } // End switch
   }
}
Ejemplo n.º 12
0
//---------------------------------------------------------------------------
bool __fastcall TRawPrint::ImprimirLinha(AnsiString Linha)
{
 DWORD WrittenChars;
 bool Retorno = true;
 try
  {
   if (DispAberto)
    if (!WritePrinter(hPrinter, Linha.c_str(), Linha.Length(), &WrittenChars))
     Retorno = false;
  }
 catch(Exception & E)
  {
   Erro("Erro ao Imprimir Linha.\r\n\r\n" + E.Message + "\r\n");
  }
  return(Retorno);
};
Ejemplo n.º 13
0
DWORD
_RpcWritePrinter(WINSPOOL_PRINTER_HANDLE hPrinter, BYTE* pBuf, DWORD cbBuf, DWORD* pcWritten)
{
    DWORD dwErrorCode;

    dwErrorCode = RpcImpersonateClient(NULL);
    if (dwErrorCode != ERROR_SUCCESS)
    {
        ERR("RpcImpersonateClient failed with error %lu!\n", dwErrorCode);
        return dwErrorCode;
    }

    if (!WritePrinter(hPrinter, pBuf, cbBuf, pcWritten))
        dwErrorCode = GetLastError();

    RpcRevertToSelf();
    return dwErrorCode;
}
Ejemplo n.º 14
0
int fb_PrinterWriteWstr( DEV_LPT_INFO *devInfo, const FB_WCHAR *data, size_t length )
{
		W32_PRINTER_INFO *pInfo = (W32_PRINTER_INFO*) devInfo->driver_opaque;
    DWORD dwWritten;

    if( !pInfo->hPrinter ) {
        pInfo->Emu.pfnPrint( pInfo, data, length, TRUE);

    } else if( !WritePrinter( pInfo->hPrinter,
                       (LPVOID) data,
                       length * sizeof( FB_WCHAR ),
                       &dwWritten ) )
    {
        return fb_ErrorSetNum( FB_RTERROR_FILEIO );

    } else if ( dwWritten != length * sizeof( FB_WCHAR )) {
        return fb_ErrorSetNum( FB_RTERROR_FILEIO );
    }

    return fb_ErrorSetNum( FB_RTERROR_OK );
}
Ejemplo n.º 15
0
int RawPrinter::print(QString text)
{
    if (!opened) return 1;

    unsigned long len;
    QByteArray bytes = text.toLatin1();
    const char *buf = bytes.data();

    DOC_INFO_1 info;

    info.pDocName = L"Document";
    info.pOutputFile = NULL;
    info.pDatatype = L"RAW";

    StartDocPrinter(hPrinter, 1, (LPBYTE)&info);
    StartPagePrinter(hPrinter);
    int ret = WritePrinter(hPrinter, (LPVOID*)buf, strlen(buf), &len);
    EndPagePrinter(hPrinter);
    EndDocPrinter(hPrinter);
    if(ret) QTextStream(stdout) << "Error: " << GetLastError() << "\n";
    return ret;
}
Ejemplo n.º 16
0
void PrintFiles(FileList* SrcPanel)
{
	_ALGO(CleverSysLog clv(L"Alt-F5 (PrintFiles)"));
	string strPrinterName;
	DWORD Needed = 0, Returned;
	DWORD FileAttr;
	string strSelName;
	size_t DirsCount=0;
	size_t SelCount=SrcPanel->GetSelCount();

	if (!SelCount)
	{
		_ALGO(SysLog(L"Error: !SelCount"));
		return;
	}

	// проверка каталогов
	_ALGO(SysLog(L"Check for FILE_ATTRIBUTE_DIRECTORY"));
	SrcPanel->GetSelName(nullptr,FileAttr);

	while (SrcPanel->GetSelName(&strSelName,FileAttr))
	{
		if (TestParentFolderName(strSelName) || (FileAttr & FILE_ATTRIBUTE_DIRECTORY))
			DirsCount++;
	}

	if (DirsCount==SelCount)
		return;

	EnumPrinters(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, nullptr, PRINTER_INFO_LEVEL, nullptr, 0, &Needed, &Returned);

	if (!Needed)
		return;

	block_ptr<PRINTER_INFO> pi(Needed);

	if (!EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS,nullptr,PRINTER_INFO_LEVEL,(LPBYTE)pi.get(),Needed,&Needed,&Returned))
	{
		Global->CatchError();
		Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MPrintTitle),MSG(MCannotEnumeratePrinters),MSG(MOk));
		return;
	}

	{
		_ALGO(CleverSysLog clv2(L"Show Menu"));
		LangString strTitle;
		string strName;

		if (SelCount==1)
		{
			SrcPanel->GetSelName(nullptr,FileAttr);
			SrcPanel->GetSelName(&strName,FileAttr);
			strSelName = TruncStr(strName,50);
			strTitle = MPrintTo;
			strTitle << InsertQuote(strSelName);
		}
		else
		{
			_ALGO(SysLog(L"Correct: SelCount-=DirsCount"));
			SelCount-=DirsCount;
			strTitle = MPrintFilesTo;
			strTitle << SelCount;
		}

		VMenu2 PrinterList(strTitle,nullptr,0,ScrY-4);
		PrinterList.SetFlags(VMENU_WRAPMODE|VMENU_SHOWAMPERSAND);
		PrinterList.SetPosition(-1,-1,0,0);
		AddToPrintersMenu(&PrinterList,pi.get(),Returned);

		if (PrinterList.Run()<0)
		{
			_ALGO(SysLog(L"ESC"));
			return;
		}

		strPrinterName = NullToEmpty(static_cast<const wchar_t*>(PrinterList.GetUserData(nullptr, 0)));
	}

	HANDLE hPrinter;

	if (!OpenPrinter(UNSAFE_CSTR(strPrinterName), &hPrinter,nullptr))
	{
		Global->CatchError();
		Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MPrintTitle),MSG(MCannotOpenPrinter),
		        strPrinterName.data(),MSG(MOk));
		_ALGO(SysLog(L"Error: Cannot Open Printer"));
		return;
	}

	{
		_ALGO(CleverSysLog clv3(L"Print selected Files"));
		SCOPED_ACTION(SaveScreen);

		auto PR_PrintMsg = [](){ Message(0, 0, MSG(MPrintTitle), MSG(MPreparingForPrinting)); };

		SCOPED_ACTION(TPreRedrawFuncGuard)(std::make_unique<PreRedrawItem>(PR_PrintMsg));
		SetCursorType(false, 0);
		PR_PrintMsg();
		auto hPlugin=SrcPanel->GetPluginHandle();
		int PluginMode=SrcPanel->GetMode()==PLUGIN_PANEL &&
		               !Global->CtrlObject->Plugins->UseFarCommand(hPlugin,PLUGIN_FARGETFILE);
		SrcPanel->GetSelName(nullptr,FileAttr);

		while (SrcPanel->GetSelName(&strSelName,FileAttr))
		{
			if (TestParentFolderName(strSelName) || (FileAttr & FILE_ATTRIBUTE_DIRECTORY))
				continue;

			int Success=FALSE;
			string FileName;
			string strTempDir, strTempName;

			if (PluginMode)
			{
				if (FarMkTempEx(strTempDir))
				{
					api::CreateDirectory(strTempDir,nullptr);
					auto ListItem = SrcPanel->GetLastSelectedItem();
					if (ListItem)
					{
						PluginPanelItem PanelItem;
						FileList::FileListToPluginItem(*ListItem, &PanelItem);

						if (Global->CtrlObject->Plugins->GetFile(hPlugin,&PanelItem,strTempDir,strTempName,OPM_SILENT))
							FileName = strTempName;
						else
							api::RemoveDirectory(strTempDir);

						FreePluginPanelItem(PanelItem);
					}
				}
			}
			else
				FileName = strSelName;

			api::File SrcFile;
			if(SrcFile.Open(FileName, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, nullptr, OPEN_EXISTING))
			{
				DOC_INFO_1 di1 = {UNSAFE_CSTR(FileName)};

				if (StartDocPrinter(hPrinter,1,(LPBYTE)&di1))
				{
					char Buffer[8192];
					DWORD Read,Written;
					Success=TRUE;

					while (SrcFile.Read(Buffer, sizeof(Buffer), Read) && Read > 0)
						if (!WritePrinter(hPrinter,Buffer,Read,&Written))
						{
							Global->CatchError();
							Success=FALSE;
							break;
						}

					EndDocPrinter(hPrinter);
				}
				SrcFile.Close();
			}

			if (!strTempName.empty())
			{
				DeleteFileWithFolder(strTempName);
			}

			if (Success)
				SrcPanel->ClearLastGetSelection();
			else
			{
				if (Message(MSG_WARNING|MSG_ERRORTYPE,2,MSG(MPrintTitle),MSG(MCannotPrint),
				            strSelName.data(),MSG(MSkip),MSG(MCancel)))
					break;
			}
		}

		ClosePrinter(hPrinter);
	}

	SrcPanel->Redraw();
}
Ejemplo n.º 17
0
BOOL
PrintRawJob(
         IN PPRINTPROCESSORDATA pData,
    _In_ IN LPWSTR pPrinterName)
{
    DOC_INFO_1  DocInfo;
    DWORD       Copies;
    DWORD       NoRead, NoWritten;
    BOOL        rc;
    HANDLE      hPrinter;
    BYTE        *ReadBuffer = NULL;
    BOOL        bRet        = FALSE;
    BOOL        bStartDoc   = FALSE;

    DocInfo.pDocName    = pData->pDocument;     /* Document name */
    DocInfo.pOutputFile = pData->pOutputFile;   /* Output file */
    DocInfo.pDatatype   = pData->pDatatype;     /* Document data type */

    /** Let the printer know we are starting a new document **/

    if (!StartDocPrinter(pData->hPrinter, 1, (LPBYTE)&DocInfo)) {
        goto Done;
    }

    bStartDoc = TRUE;


    /** Allocate the read buffer, dynamically allocated to conserve stack space **/

    ReadBuffer = (BYTE *)AllocSplMem(READ_BUFFER_SIZE);

    if (!ReadBuffer) {
        goto Done;
    }

    /** Print the data pData->Copies times **/

    Copies = pData->Copies;

    while (Copies--) {

        /**
            Open the printer.  If it fails, return.  This also sets up the
            pointer for the ReadPrinter calls.
        **/

        if (!OpenPrinter(pPrinterName, &hPrinter, NULL)) {   
            goto Done;
        }

        /**
            Loop, getting data and sending it to the printer.  This also
            takes care of pausing and cancelling print jobs by checking
            the processor's status flags while printing.
        **/

        while (
            ((rc = ReadPrinter(hPrinter, ReadBuffer, READ_BUFFER_SIZE, &NoRead)) != 0) &&
            NoRead
            ) {


            /** If the print processor is paused, wait for it to be resumed **/

            if (pData->fsStatus & PRINTPROCESSOR_PAUSED) {
                WaitForSingleObject(pData->semPaused, INFINITE);
            }

            /** If the job has been aborted, don't write anymore **/

            if (pData->fsStatus & PRINTPROCESSOR_ABORTED) {
                break;
            }

            /** Write the data to the printer **/

            WritePrinter(pData->hPrinter, ReadBuffer, NoRead, &NoWritten);
        }


        /**
            Close the printer - we open/close the printer for each
            copy so the data pointer will rewind.
        **/

        ClosePrinter(hPrinter);

    } /* While copies to print */

    bRet = TRUE;

Done:    
    
    /** Close the buffer we allocated **/

    if (ReadBuffer) {
        FreeSplMem(ReadBuffer);
    }
    
    /** Let the printer know that we are done printing **/

    if (bStartDoc) {
        EndDocPrinter(pData->hPrinter);
    }
    
    return bRet;
}
Ejemplo n.º 18
0
//---------------------------------------------------------------------------//
bool CAddInRawPrinter::CallAsProc(const long lMethodNum,
                    tVariant* paParams, const long lSizeArray)
{ 
    switch(lMethodNum)
    { 
    case eMeth_Open:
		{
			if (hPrinter) {
				ClosePrinter(hPrinter);
				hPrinter = NULL;
			}

			WCHAR_T *m_PrinterName = paParams[0].pwstrVal;
			uint32_t len = paParams[0].wstrLen;
			uint32_t sz = sizeof(WCHAR_T)*(len + 1);
		
			if (PrinterName) {
				m_iMemory->FreeMemory(reinterpret_cast<void**>(&PrinterName));
				PrinterName = NULL;
				//delete PrinterName;
			}

			{
				m_iMemory->AllocMemory(reinterpret_cast<void**>(&PrinterName), sz);
				//PrinterName = new WCHAR_T[len + 1];
			}
			memcpy(reinterpret_cast<void*>(PrinterName), reinterpret_cast<void*>(m_PrinterName), sz);
			PrinterName[len] = 0;
			
			
			wchar_t *wp_Name = NULL;
			::convFromShortWchar(&wp_Name, PrinterName, len + 1);
			
			if (!OpenPrinterW(wp_Name, &hPrinter, NULL)) {
				wchar_t buf[512];
				wsprintf(buf, L"OpenPrinterW(%s) failed with code: %u", wp_Name, GetLastError());
				addError(1, L"Printer error", buf, 1);
			}
			
			delete [] wp_Name;
			
		}
        break;

    case eMeth_Close:
		
		if (PrinterName) {
			m_iMemory->FreeMemory(reinterpret_cast<void**>(&PrinterName));
			//delete PrinterName;
		}
		ClosePrinter(hPrinter);

		break;

    case eMeth_SendRaw:

		{
			WCHAR_T *wc = paParams[0].pwstrVal;
			char *utf8 = ConvToUtf8(wc);

			DWORD len = strlen(utf8), sent;
			if (!WritePrinter(hPrinter, utf8, len, &sent))
				addError(2, L"Failed to send data to printer!", L"Failed!", 2);

			delete [] utf8;
		}
        break;

	case eMeth_StartDocument:

		{
			
			wchar_t *doc_name = NULL;
			wchar_t *data_type = NULL;
			::convFromShortWchar(&doc_name, paParams[0].pwstrVal);
			::convFromShortWchar(&data_type, paParams[1].pwstrVal);

			DOC_INFO_1 doc;
			doc.pDocName = doc_name;
			doc.pOutputFile = NULL;
			doc.pDatatype = data_type;

			DWORD print_job = StartDocPrinter(hPrinter, 1, (LPBYTE)&doc);

			delete [] doc_name;
			delete [] data_type;
		}

		break;

	case eMeth_EndDocument:

		EndDocPrinter(hPrinter);
		break;

    default:
        return false;
    }

    return true;
}
Ejemplo n.º 19
0
BOOL WritePrinter( BYTE Command, VOID FAR *Data )
    {
    switch( Command )
	{
	case INIT:
	    DosWrite( Printer, PrinterInfo->ControlCodes[0], (WORD)StdFarStrLen( PrinterInfo->ControlCodes[0] ), NULL );
	    DosWrite( Printer, PrinterInfo->ControlCodes[1], (WORD)StdFarStrLen( PrinterInfo->ControlCodes[1] ), NULL );
	    DataInPrinterBuffer = TRUE;
	    HPos = 0;
	    VPos = 0;
	    Page = 1;
	    break;

	case TITLEFONT:
	    DosWrite( Printer, PrinterInfo->ControlCodes[2], (WORD)StdFarStrLen( PrinterInfo->ControlCodes[2] ), NULL );
	    break;

	case NORMALFONT:
	    DosWrite( Printer, PrinterInfo->ControlCodes[3], (WORD)StdFarStrLen( PrinterInfo->ControlCodes[3] ), NULL );
	    break;

	case COMPTITLEFONT:
	    DosWrite( Printer, PrinterInfo->ControlCodes[4], (WORD)StdFarStrLen( PrinterInfo->ControlCodes[4] ), NULL );
	    break;

	case COMPNORMALFONT:
	    DosWrite( Printer, PrinterInfo->ControlCodes[5], (WORD)StdFarStrLen( PrinterInfo->ControlCodes[5] ), NULL );
	    break;

	case STARTUNDERLINE:
	    DosWrite( Printer, PrinterInfo->ControlCodes[6], (WORD)StdFarStrLen( PrinterInfo->ControlCodes[6] ), NULL );
	    break;

	case ENDUNDERLINE:
	    DosWrite( Printer, PrinterInfo->ControlCodes[7], (WORD)StdFarStrLen( PrinterInfo->ControlCodes[7] ), NULL );
	    break;

	case STARTBOLD:
	    DosWrite( Printer, PrinterInfo->ControlCodes[8], (WORD)StdFarStrLen( PrinterInfo->ControlCodes[8] ), NULL );
	    break;

	case ENDBOLD:
	    DosWrite( Printer, PrinterInfo->ControlCodes[9], (WORD)StdFarStrLen( PrinterInfo->ControlCodes[9] ), NULL );
	    break;

	case DATA:
	    DosWrite( Printer, Data, (WORD)StdFarStrLen( Data ), NULL );
	    HPos += (BYTE)StdFarStrLen( Data );
	    DataInPrinterBuffer = TRUE;
	    break;

	case SETHPOS:
	    {
	    BYTE Counter;

	    for( Counter = HPos; Counter < (BYTE)Data; Counter++ )
		{
		DosWrite( Printer, (CHAR FAR *)" ", 1, NULL );
		HPos++;
		}

	    DataInPrinterBuffer = TRUE;
	    break;
	    }

	case NEWLINE:
	    if( VPos == PrinterInfo->LinesPerPage - 3 )
		{
		CHAR String[4];

		DosWrite( Printer, "\r\n\n", 3, NULL );
		HPos = 0;
		WritePrinter( SETHPOS, (CHAR FAR *)78 );

		StdStrCpy( String, "   " );
		StdBinToAscii( Page, 3, String, RIGHT, 1 );
		WritePrinter( DATA, String );
		DosWrite( Printer, "\r\f", 2, NULL );
		HPos = 0;
		VPos = 0;
		Page++;
		DataInPrinterBuffer = FALSE;
		return( FALSE );
		}
	    else
		{
		DosWrite( Printer, "\r\n", 2, NULL );
		VPos++;
		HPos = 0;
		return( TRUE );
		}
	    break;

	case NEWPAGE:
	    while( WritePrinter( NEWLINE, (CHAR FAR *)NULL ) );
	    break;
	}
    return( TRUE );
    }
Ejemplo n.º 20
0
void
DumpPrinter(HWND hwnd, LPTSTR szAppName, LPTSTR szFileName)
{
    PRINTDLGEX pd;
    DEVNAMES * pDevNames;
    LPCTSTR szDevice;
    GP_PRINT pr;
    HANDLE printer;
    DOC_INFO_1 di;
    DWORD jobid;
    HRESULT hr;
    LPSTR buf;
    int count;
    FILE *f;
    long lsize;
    long ldone;
    TCHAR pcdone[10];

    if ((f = _tfopen(szFileName, TEXT("rb"))) == NULL)
	return;
    fseek(f, 0L, SEEK_END);
    lsize = ftell(f);
    if (lsize <= 0)
	lsize = 1;
    fseek(f, 0L, SEEK_SET);
    ldone = 0;

    /* Print Property Sheet  */
    /* See http://support.microsoft.com/kb/240082 */
    memset(&pd, 0, sizeof(pd));
    pd.lStructSize = sizeof(pd);
    pd.hwndOwner = hwnd;
    pd.Flags = PD_NOPAGENUMS | PD_NOSELECTION | PD_NOCURRENTPAGE | PD_USEDEVMODECOPIESANDCOLLATE;
    pd.hDevNames = hDevNames;
    pd.hDevMode = hDevMode;
    pd.hDevNames = NULL;
    pd.hDevMode = NULL;
    pd.nCopies = 1;
    pd.nStartPage = START_PAGE_GENERAL;

    /* Replace the additional options in the lower part of the dialog with
     * a hint to change print options via terminal options.
     */
    pd.lpPrintTemplateName = TEXT("PrintDlgExSelect");
    pd.hInstance = graphwin->hInstance;
    pd.Flags |= PD_ENABLEPRINTTEMPLATE;

    if ((hr = PrintDlgEx(&pd)) != S_OK) {
	DWORD error = CommDlgExtendedError();
	fprintf(stderr, "\nError:  Opening the print dialog failed with error code %04x (%04x).\n", hr, error);
    }

    if (pd.dwResultAction == PD_RESULT_PRINT) {
	pDevNames = (DEVNAMES *) GlobalLock(pd.hDevNames);
	szDevice = (LPCTSTR)pDevNames + pDevNames->wDeviceOffset;
	if (!OpenPrinter((LPTSTR)szDevice, &printer, NULL))
		printer = NULL;
	GlobalUnlock(pd.hDevNames);
	/* We no longer free these structures, but preserve them for the next time
	GlobalFree(pd.hDevMode);
	GlobalFree(pd.hDevNames);
	*/
	hDevNames = pd.hDevNames;
	hDevMode = pd.hDevMode;

	if (printer == NULL)
	    return;	/* abort */

	pr.hdcPrn = printer;
	PrintRegister(&pr);
	if ((buf = (LPSTR) malloc(4096)) != NULL) {
	    EnableWindow(hwnd, FALSE);
	    pr.bUserAbort = FALSE;
	    pr.szTitle = szAppName;
	    pr.hDlgPrint = CreateDialogParam(hdllInstance, TEXT("CancelDlgBox"),
						hwnd, PrintDlgProc, (LPARAM) &pr);
	    SendMessage(GetDlgItem(pr.hDlgPrint, CANCEL_PROGRESS), PBM_SETRANGE32, 0, lsize);

	    di.pDocName = szAppName;
	    di.pOutputFile = NULL;
	    di.pDatatype = TEXT("RAW");
	    if ((jobid = StartDocPrinter(printer, 1, (LPBYTE) &di)) > 0) {
		while (pr.hDlgPrint && !pr.bUserAbort &&
		       (count = fread(buf, 1, 4096, f)) != 0 ) {
		    int ret;
		    DWORD dwBytesWritten;

		    ret = WritePrinter(printer, buf, count, &dwBytesWritten);
		    ldone += count;
		    if (dwBytesWritten > 0) {
			wsprintf(pcdone, TEXT("%d%% done"), (int)(ldone * 100 / lsize));
			SetWindowText(GetDlgItem(pr.hDlgPrint, CANCEL_PCDONE), pcdone);
			SendMessage(GetDlgItem(pr.hDlgPrint, CANCEL_PROGRESS), PBM_SETPOS, ldone, 0);
		    } else if (ret == 0) {
			SetWindowText(GetDlgItem(pr.hDlgPrint, CANCEL_PCDONE), TEXT("Error writing to printer!"));
			pr.bUserAbort  = TRUE;
		    }

		    /* handle window messages */
		    PrintAbortProc(printer, 0);
		}
		if (pr.bUserAbort) {
		    if (SetJob(printer, jobid, 0, NULL, JOB_CONTROL_DELETE) == 0) {
			SetWindowText(GetDlgItem(pr.hDlgPrint, CANCEL_PCDONE), TEXT("Error: Failed to cancel print job!"));
			fprintf(stderr, "Error: Failed to cancel print job!\n");
		    }
		}
		EndDocPrinter(printer);
		if (!pr.bUserAbort) {
		    EnableWindow(hwnd, TRUE);
		    DestroyWindow(pr.hDlgPrint);
		}
		free(buf);
	    }
	}
	ClosePrinter(printer);
	PrintUnregister(&pr);
    }
    fclose(f);
}
Ejemplo n.º 21
0
int main (int argc, char* argv[])
{
	
	HANDLE				printer;
	int					fd;
	BYTE				buffer[256];
	DWORD				bytes, wrote;
	DOC_INFO_1			buffer1;
	PRINTER_DEFAULTS	print_defaults;

	if (argc < 3)
	{
		fprintf (stderr, "useage: %s <printername> <filename>\n", argv[0]);
		exit (-1);
	}

	printf ("This test program exercises the following win32 functions:\n");
	printf ("\tResetPrinter()\n");
	printf ("\tStartDocPrinter()\n");
	printf ("\tEndDocPrinter()\n");
	printf ("\tStartPagePrinter()\n");
	printf ("\tEndPagePrinter()\n");
	printf ("\tWritePrinter()\n");
	printf ("\n\n");

	printf ("This test program exercises both the StartPagePrinter()\n");
	printf ("and EndPagePrinter() Win32 functions.\n\n");

	if (!OpenPrinter (argv[1], &printer, NULL))
	{
		fprintf (stderr, "Unable to open %s!\n", argv[1]);
		exit (-1);
	}
	else
	{
		printf ("Printer [%s] opened successfully.\n\n", argv[1]);
	}

	/* set the printer defaults */
	print_defaults.pDatatype		= strdup ("RAW");
	print_defaults.DesiredAccess	= NULL;
	print_defaults.pDevMode			= NULL;
	if (ResetPrinter(printer, &print_defaults))
		printf ("ResetPrinter call succeeded\n");
	else
		PrintLastError();
	printf ("\n");

	/* StartDocPrinter */
	buffer1.pDocName	= strdup("Testing Printer");
	buffer1.pDatatype	= strdup("RAW");
	buffer1.pOutputFile	= NULL;

	printf ("Attempting to call StartDocPrinter() using DOC_INFO_1 :\n");
	print_doc_info_1 (&buffer1);
	printf ("\n");

	if (StartDocPrinter (printer, 1, (LPBYTE)&buffer1))
		printf ("StartDocPrinter called successfully\n");
	else
		PrintLastError();
	printf ("\n");


	if (StartPagePrinter(printer))
	{
		printf ("StartPagePrinter returned success.\n");

		if ((fd=_open(argv[2], _O_RDONLY)) == -1)
		{
			fprintf (stderr, "ERROR: Unable to open [%s] for read access!\n", argv[2]);
			ClosePrinter (printer);
			exit (-1);
		}

		while ((bytes=_read(fd, buffer, 256)) != 0)
		{
			if (!WritePrinter(printer, (LPVOID)buffer, bytes, &wrote))
			{
				fprintf (stderr, "ERROR: WritePrinter failed for [%d] bytes!\n", bytes);
				PrintLastError();
			}
			else
				printf ("Successfully wrote [%d] bytes to the printer\n", bytes);
		}
		_close (fd);

		if (EndPagePrinter (printer))
			printf ("EndPagePrinter returned success.\n");
		else
			PrintLastError();
	}
	else
		PrintLastError();
	printf ("\n");
			
	printf ("Attempting to call EndDocPrinter\n");
	if (EndDocPrinter (printer))
		printf ("EndDocPrinter called successfully\n");
	else
		PrintLastError();
	printf ("\n");



	if (!ClosePrinter(printer))
	{
		fprintf (stderr, "Error closing printer!\n");
		exit (-1);
	}
	else
	{
		printf ("Printer [%s] closed successfully.\n", argv[1]);
	}

	return 0;

}
Ejemplo n.º 22
0
// **********************************************************************
// RawDataToPrinter - sends binary data directly to a printer
// 
// Params:
//   szPrinterName - NULL terminated string specifying printer name
//   lpData        - Pointer to raw data bytes
//   dwCount       - Length of lpData in bytes
// 
// Returns: TRUE for success, FALSE for failure.
// 
BOOL RawDataToPrinter( LPTSTR szPrinterName, LPBYTE lpData, DWORD dwCount )
{
    HANDLE     hPrinter;
    DOC_INFO_1 DocInfo;
    DWORD      dwJob;
    DWORD      dwBytesWritten;

    // Need a handle to the printer.
    if( ! OpenPrinter( szPrinterName, &hPrinter, NULL ) )
    {
        PrintError( GetLastError(), TEXT("OpenPrinter") );
        return FALSE;
    }

    // Fill in the structure with info about this "document."
    DocInfo.pDocName = TEXT("My Document");
    DocInfo.pOutputFile = NULL;
    DocInfo.pDatatype = TEXT("RAW");
    // Inform the spooler the document is beginning.
    if( (dwJob = StartDocPrinter( hPrinter, 1, (LPBYTE)&DocInfo )) == 0 )
    {
        PrintError( GetLastError(), TEXT("StartDocPrinter") );
        ClosePrinter( hPrinter );
        return FALSE;
    }
    // Start a page.
    if( ! StartPagePrinter( hPrinter ) )
    {
        PrintError( GetLastError(), TEXT("StartPagePrinter") );
        EndDocPrinter( hPrinter );
        ClosePrinter( hPrinter );
        return FALSE;
    }
    // Send the data to the printer.
    if( ! WritePrinter( hPrinter, lpData, dwCount, &dwBytesWritten ) )
    {
        PrintError( GetLastError(), TEXT("WritePrinter") );
        EndPagePrinter( hPrinter );
        EndDocPrinter( hPrinter );
        ClosePrinter( hPrinter );
        return FALSE;
    }

    /*********************************/
    // CODE USED TO READ THE PRINTER
    LPBYTE retData = NULL;
    LPDWORD bbr = NULL;

    if(ReadPrinter(hPrinter, retData, 1, bbr))
    {
        printf("OUT : %i", retData);
    }
    else
    {
        printf("Failed to read printer");
    }
    /*********************************/

    // End the page.
    if( ! EndPagePrinter( hPrinter ) )
    {
        PrintError( GetLastError(), TEXT("EndPagePrinter") );
        EndDocPrinter( hPrinter );
        ClosePrinter( hPrinter );
        return FALSE;
    }
    // Inform the spooler that the document is ending.
    if( ! EndDocPrinter( hPrinter ) )
    {
        PrintError( GetLastError(), TEXT("EndDocPrinter") );
        ClosePrinter( hPrinter );
        return FALSE;
    }
    // Tidy up the printer handle.
    ClosePrinter( hPrinter );
    // Check to see if correct number of bytes were written.
    if( dwBytesWritten != dwCount )
    {
        //printf( TEXT("Wrote %d bytes instead of requested %d bytes.\n"), dwBytesWritten, dwCount );
        return FALSE;
    }
    return TRUE;
}
Ejemplo n.º 23
0
/* True Win32 method, using OpenPrinter, WritePrinter etc. */
static int
gp_printfile_win32(const char *filename, char *port)
{
    DWORD count;
    char *buffer;
    char portname[MAXSTR];
    FILE *f;
    HANDLE printer;
    DOC_INFO_1 di;
    DWORD written;

    if (!get_queuename(portname, port))
	return FALSE;
    port = portname + 8;	/* skip over \\spool\ */

    if ((buffer = malloc(PRINT_BUF_SIZE)) == (char *)NULL)
	return FALSE;

    if ((f = fopen(filename, "rb")) == (FILE *) NULL) {
	free(buffer);
	return FALSE;
    }
    /* open a printer */
    if (!OpenPrinter(port, &printer, NULL)) {
	char buf[256];

	sprintf(buf, "OpenPrinter() failed for \042%s\042, error code = %d", port, GetLastError());
	MessageBox((HWND) NULL, buf, szAppName, MB_OK | MB_ICONSTOP);
	free(buffer);
	return FALSE;
    }
    /* from here until ClosePrinter, should AbortPrinter on error */

    di.pDocName = szAppName;
    di.pOutputFile = NULL;
    di.pDatatype = "RAW";	/* for available types see EnumPrintProcessorDatatypes */
    if (!StartDocPrinter(printer, 1, (LPBYTE) & di)) {
	char buf[256];

	sprintf(buf, "StartDocPrinter() failed, error code = %d", GetLastError());
	MessageBox((HWND) NULL, buf, szAppName, MB_OK | MB_ICONSTOP);
	AbortPrinter(printer);
	free(buffer);
	return FALSE;
    }
    /* copy file to printer */
    while ((count = fread(buffer, 1, PRINT_BUF_SIZE, f)) != 0) {
	if (!WritePrinter(printer, (LPVOID) buffer, count, &written)) {
	    free(buffer);
	    fclose(f);
	    AbortPrinter(printer);
	    return FALSE;
	}
    }
    fclose(f);
    free(buffer);

    if (!EndDocPrinter(printer)) {
	char buf[256];

	sprintf(buf, "EndDocPrinter() failed, error code = %d", GetLastError());
	MessageBox((HWND) NULL, buf, szAppName, MB_OK | MB_ICONSTOP);
	AbortPrinter(printer);
	return FALSE;
    }
    if (!ClosePrinter(printer)) {
	char buf[256];

	sprintf(buf, "ClosePrinter() failed, error code = %d", GetLastError());
	MessageBox((HWND) NULL, buf, szAppName, MB_OK | MB_ICONSTOP);
	return FALSE;
    }
    return TRUE;
}
Ejemplo n.º 24
0
void PrintFiles(Panel *SrcPanel)
{
	_ALGO(CleverSysLog clv(L"Alt-F5 (PrintFiles)"));
	string strPrinterName;
	DWORD Needed,Returned;
	int PrinterNumber;
	DWORD FileAttr;
	string strSelName;
	long DirsCount=0;
	int SelCount=SrcPanel->GetSelCount();

	if (!SelCount)
	{
		_ALGO(SysLog(L"Error: !SelCount"));
		return;
	}

	// проверка каталогов
	_ALGO(SysLog(L"Check for FILE_ATTRIBUTE_DIRECTORY"));
	SrcPanel->GetSelName(nullptr,FileAttr);

	while (SrcPanel->GetSelName(&strSelName,FileAttr))
	{
		if (TestParentFolderName(strSelName) || (FileAttr & FILE_ATTRIBUTE_DIRECTORY))
			DirsCount++;
	}

	if (DirsCount==SelCount)
		return;

	PRINTER_INFO *pi = nullptr;

	if (EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS,nullptr,PRINTER_INFO_LEVEL,nullptr,0,&Needed,&Returned) || Needed<=0)
		return;

	pi = (PRINTER_INFO *)xf_malloc(Needed);

	if (!EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS,nullptr,PRINTER_INFO_LEVEL,(LPBYTE)pi,Needed,&Needed,&Returned))
	{
		Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MPrintTitle),MSG(MCannotEnumeratePrinters),MSG(MOk));
		xf_free(pi);
		return;
	}

	{
		_ALGO(CleverSysLog clv2(L"Show Menu"));
		string strTitle;
		string strName;

		if (SelCount==1)
		{
			SrcPanel->GetSelName(nullptr,FileAttr);
			SrcPanel->GetSelName(&strName,FileAttr);
			TruncStr(strName,50);
			strSelName=strName;
			InsertQuote(strSelName);
			strTitle.Format(MSG(MPrintTo), strSelName.CPtr());
		}
		else
		{
			_ALGO(SysLog(L"Correct: SelCount-=DirsCount"));
			SelCount-=DirsCount;
			strTitle.Format(MSG(MPrintFilesTo),SelCount);
		}

		VMenu PrinterList(strTitle,nullptr,0,ScrY-4);
		PrinterList.SetFlags(VMENU_WRAPMODE|VMENU_SHOWAMPERSAND);
		PrinterList.SetPosition(-1,-1,0,0);
		AddToPrintersMenu(&PrinterList,pi,Returned);
		PrinterList.Process();
		PrinterNumber=PrinterList.Modal::GetExitCode();

		if (PrinterNumber<0)
		{
			xf_free(pi);
			_ALGO(SysLog(L"ESC"));
			return;
		}

		int nSize = PrinterList.GetUserDataSize();
		wchar_t *PrinterName = strPrinterName.GetBuffer(nSize);
		PrinterList.GetUserData(PrinterName, nSize);
		strPrinterName.ReleaseBuffer();
	}

	HANDLE hPrinter;

	if (!OpenPrinter((wchar_t*)strPrinterName.CPtr(),&hPrinter,nullptr))
	{
		Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MPrintTitle),MSG(MCannotOpenPrinter),
		        strPrinterName,MSG(MOk));
		xf_free(pi);
		_ALGO(SysLog(L"Error: Cannot Open Printer"));
		return;
	}

	{
		_ALGO(CleverSysLog clv3(L"Print selected Files"));
		//SaveScreen SaveScr;
		TPreRedrawFuncGuard preRedrawFuncGuard(PR_PrintMsg);
		SetCursorType(FALSE,0);
		PR_PrintMsg();
		HANDLE hPlugin=SrcPanel->GetPluginHandle();
		int PluginMode=SrcPanel->GetMode()==PLUGIN_PANEL &&
		               !CtrlObject->Plugins.UseFarCommand(hPlugin,PLUGIN_FARGETFILE);
		SrcPanel->GetSelName(nullptr,FileAttr);

		while (SrcPanel->GetSelName(&strSelName,FileAttr))
		{
			if (TestParentFolderName(strSelName) || (FileAttr & FILE_ATTRIBUTE_DIRECTORY))
				continue;

			int Success=FALSE;
			LPCWSTR FileName = nullptr;
			string strTempDir, strTempName;

			if (PluginMode)
			{
				if (FarMkTempEx(strTempDir))
				{
					apiCreateDirectory(strTempDir,nullptr);
					FileListItem ListItem;

					if (SrcPanel->GetLastSelectedItem(&ListItem))
					{
						PluginPanelItem PanelItem;
						FileList::FileListToPluginItem(&ListItem,&PanelItem);

						if (CtrlObject->Plugins.GetFile(hPlugin,&PanelItem,strTempDir,strTempName,OPM_SILENT))
							FileName = strTempName;
						else
							apiRemoveDirectory(strTempDir);

						FileList::FreePluginPanelItem(&PanelItem);
					}
				}
			}
			else
				FileName = strSelName;

			File SrcFile;
			if(SrcFile.Open(FileName, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, nullptr, OPEN_EXISTING))
			{
				DOC_INFO_1 di1 = {const_cast<LPWSTR>(FileName)};

				if (StartDocPrinter(hPrinter,1,(LPBYTE)&di1))
				{
					char Buffer[8192];
					DWORD Read,Written;
					Success=TRUE;

					while (SrcFile.Read(Buffer, sizeof(Buffer), Read) && Read > 0)
						if (!WritePrinter(hPrinter,Buffer,Read,&Written))
						{
							Success=FALSE;
							break;
						}

					EndDocPrinter(hPrinter);
				}
				SrcFile.Close();
			}

			if (!strTempName.IsEmpty())
			{
				DeleteFileWithFolder(strTempName);
			}

			if (Success)
				SrcPanel->ClearLastGetSelection();
			else
			{
				if (Message(MSG_WARNING|MSG_ERRORTYPE,2,MSG(MPrintTitle),MSG(MCannotPrint),
				            strSelName,MSG(MSkip),MSG(MCancel)))
					break;
			}
		}

		ClosePrinter(hPrinter);
	}

	SrcPanel->Redraw();
	xf_free(pi);
}