printer_job *printer_start_job(char *printer) { printer_job *ret = smalloc(sizeof(printer_job)); DOC_INFO_1 docinfo; int jobstarted = 0, pagestarted = 0; ret->hprinter = NULL; if (!OpenPrinter(printer, &ret->hprinter, NULL)) goto error; docinfo.pDocName = "PuTTY remote printer output"; docinfo.pOutputFile = NULL; docinfo.pDatatype = "RAW"; if (!StartDocPrinter(ret->hprinter, 1, (LPSTR)&docinfo)) goto error; jobstarted = 1; if (!StartPagePrinter(ret->hprinter)) goto error; pagestarted = 1; return ret; error: if (pagestarted) EndPagePrinter(ret->hprinter); if (jobstarted) EndDocPrinter(ret->hprinter); if (ret->hprinter) ClosePrinter(ret->hprinter); sfree(ret); return NULL; }
/************************************************************************ * PSDRV_EndDoc */ INT PSDRV_EndDoc( PHYSDEV dev ) { PSDRV_PDEVICE *physDev = get_psdrv_dev( dev ); INT ret = 1; if(!physDev->job.id) { FIXME("hJob == 0. Now what?\n"); return 0; } if(!physDev->job.OutOfPage) { WARN("Somebody forgot an EndPage\n"); PSDRV_EndPage( dev ); } if (physDev->job.PageNo) PSDRV_WriteFooter( dev ); ret = EndDocPrinter(physDev->job.hprinter); ClosePrinter(physDev->job.hprinter); physDev->job.hprinter = NULL; physDev->job.id = 0; HeapFree( GetProcessHeap(), 0, physDev->job.doc_name ); physDev->job.doc_name = NULL; return ret; }
//--------------------------------------------------------------------------- bool __fastcall TRawPrint::FechaDispositivo(void) { bool Retorno = true; try { if (DispAberto) { if (PaginaAberta) { if(!EndPagePrinter(hPrinter)) Erro("Erro ao Finalizar Página"); if(!EndDocPrinter(hPrinter)) Erro("Erro ao Finalizar Documento"); else { if(!ClosePrinter(hPrinter)) { Erro("Erro ao Fechar a Impressora"); Retorno = false; } DispAberto = false; } } } } catch(Exception & E) { Erro("Erro ao Fechar a Impressora.\r\n\r\n" + E.Message + "\r\n"); } return Retorno; };
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); }
void printer_finish_job(printer_job *pj) { if (!pj) return; EndPagePrinter(pj->hprinter); EndDocPrinter(pj->hprinter); ClosePrinter(pj->hprinter); sfree(pj); }
void printer_finish_job(void) { if (printer) { EndPagePrinter(printer); EndDocPrinter(printer); ClosePrinter(printer); printer = 0; } }
void printer_start_job(char *printer_name) { if (OpenPrinter(printer_name, &printer, 0)) { if (StartDocPrinter(printer, 1, (LPBYTE)&doc_info)) { if (StartPagePrinter(printer)) return; EndDocPrinter(printer); } ClosePrinter(printer); printer = 0; } }
/***************************************************************************** End document Done on PRINT CLOSE *****************************************************************************/ static void EndDocument(void) { DeleteObject( SelectObject( pd.hDC, hOldFont ) ); if (defaultprinter) { EndPage( pd.hDC ); EndDoc( pd.hDC ); } else { EndPagePrinter( hPrinter ); EndDocPrinter( hPrinter ); } documentON = FALSE; }
void Demo_WritePrinter(void) { PRINTDLG pd; memset(&pd, 0, sizeof(PRINTDLG)); pd.lStructSize = sizeof(PRINTDLG); if ( PrintDlg(&pd)==IDOK ) { HANDLE hPrinter; DEVMODE * pDevMode = (DEVMODE *) GlobalLock(pd.hDevMode); PRINTER_DEFAULTS prn; prn.pDatatype = "NT EMF 1.008"; prn.pDevMode = pDevMode; prn.DesiredAccess = PRINTER_ACCESS_USE; if ( OpenPrinter((char *) pDevMode->dmDeviceName, & hPrinter, & prn) ) { KFileDialog fd; if ( fd.GetOpenFileName(NULL, "spl", "Windows 2000 EMF Spool file") ) { DOC_INFO_1 docinfo; docinfo.pDocName = "Testing WritePrinter"; docinfo.pOutputFile = NULL; docinfo.pDatatype = "NT EMF 1.008"; StartDocPrinter(hPrinter, 1, (BYTE *) & docinfo); StartPagePrinter(hPrinter); SendFile(hPrinter, fd.m_TitleName, true); EndPagePrinter(hPrinter); EndDocPrinter(hPrinter); } ClosePrinter(hPrinter); } if ( pd.hDevMode ) GlobalFree(pd.hDevMode); if ( pd.hDevNames ) GlobalFree(pd.hDevNames); } }
DWORD _RpcEndDocPrinter(WINSPOOL_PRINTER_HANDLE hPrinter) { DWORD dwErrorCode; dwErrorCode = RpcImpersonateClient(NULL); if (dwErrorCode != ERROR_SUCCESS) { ERR("RpcImpersonateClient failed with error %lu!\n", dwErrorCode); return dwErrorCode; } if (!EndDocPrinter(hPrinter)) dwErrorCode = GetLastError(); RpcRevertToSelf(); return dwErrorCode; }
int fb_PrinterClose( DEV_LPT_INFO *devInfo ) { W32_PRINTER_INFO *pInfo = (W32_PRINTER_INFO*) devInfo->driver_opaque; if( pInfo->hDc!=NULL ) { if( pInfo->Emu.iPageStarted ) EndPage( pInfo->hDc ); EndDoc( pInfo->hDc ); DeleteDC( pInfo->hDc ); } else { EndDocPrinter( pInfo->hPrinter ); ClosePrinter( pInfo->hPrinter ); } if( devInfo->driver_opaque ) free(devInfo->driver_opaque); devInfo->driver_opaque = NULL; return fb_ErrorSetNum( FB_RTERROR_OK ); }
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; }
JNIEXPORT jboolean JNICALL Java_org_apache_harmony_x_print_GDIClient_endDocPrinter (JNIEnv *env, jclass owner, jint printerID) { HANDLE hPrinter = *((HANDLE *)&printerID); #ifdef PRINTING_DEBUG if (file != NULL) { fclose(file); file = NULL; } #endif /* PRINTING_DEBUG */ if (hPrinter != NULL) { if (EndDocPrinter(hPrinter) != 0) { ClosePrinter(hPrinter); hPrinter = NULL; return JNI_TRUE; } } #ifdef PRINTING_DEBUG if (res == JNI_FALSE) { DWORD error = GetLastError(); printf("Error occurred while ending: %d.\n", error); } #endif /* PRINTING_DEBUG */ return JNI_FALSE; }
int fb_PrinterOpen( DEV_LPT_INFO *devInfo, int iPort, const char *pszDevice ) { int result = fb_ErrorSetNum( FB_RTERROR_OK ); const DEV_PRINTER_EMU_MODE *pFoundEmu = NULL; DWORD dwJob = 0; BOOL fResult; HANDLE hPrinter = NULL; HDC hDc = NULL; char *printer_name = NULL; char *doc_title = NULL; DEV_LPT_PROTOCOL *lpt_proto; if ( !fb_DevLptParseProtocol( &lpt_proto, pszDevice, strlen(pszDevice), TRUE ) ) { if( lpt_proto!=NULL ) free(lpt_proto); return fb_ErrorSetNum( FB_RTERROR_ILLEGALFUNCTIONCALL ); } /* Allow only valid emulation modes */ if( *lpt_proto->emu!=0 ) { int i; for( i=0; i!=sizeof(aEmulationModes)/sizeof(aEmulationModes[0]); ++i ) { const DEV_PRINTER_EMU_MODE *pEmu = aEmulationModes + i; if( strcasecmp( lpt_proto->emu, pEmu->pszId )==0 ) { pFoundEmu = pEmu; break; } } if( !pFoundEmu ) { if( lpt_proto!=NULL ) free(lpt_proto); return fb_ErrorSetNum( FB_RTERROR_ILLEGALFUNCTIONCALL ); } } if( iPort==0 ) { /* LPT:[PrinterName] */ if( *lpt_proto->name ) { printer_name = strdup( lpt_proto->name ); } else { printer_name = GetDefaultPrinterName(); } } else { /* LPTx: */ FB_LIST dev_printer_devs; DEV_PRINTER_DEVICE* node; fb_hListDevInit( &dev_printer_devs ); fb_hPrinterBuildList( &dev_printer_devs ); /* Find printer attached to specified device */ node = fb_hListDevFindDevice( &dev_printer_devs, lpt_proto->proto ); if( node!=NULL ) { printer_name = strdup( node->printer_name ); } fb_hListDevClear( &dev_printer_devs ); } if( printer_name == NULL ) { result = fb_ErrorSetNum( FB_RTERROR_FILENOTFOUND ); } else { if( *lpt_proto->emu!= '\0' ) { /* When EMULATION is used, we have to use the DC instead of * the PRINTER directly */ hDc = CreateDCA( "WINSPOOL", printer_name, NULL, NULL ); fResult = hDc!=NULL; } else { /* User PRINTER directly */ fResult = OpenPrinter(printer_name, &hPrinter, NULL); } if( !fResult ) { result = fb_ErrorSetNum( FB_RTERROR_FILENOTFOUND ); } } if( lpt_proto->title && *lpt_proto->title ) { doc_title = strdup( lpt_proto->title ); } else { doc_title = strdup( "FreeBASIC document" ); } if( result==FB_RTERROR_OK ) { if( *lpt_proto->emu!= '\0' ) { int iJob; DOCINFO docInfo; memset( &docInfo, 0, sizeof(DOCINFO) ); docInfo.cbSize = sizeof(DOCINFO); docInfo.lpszDocName = doc_title; iJob = StartDoc( hDc, &docInfo ); if( iJob <= 0 ) { result = fb_ErrorSetNum( FB_RTERROR_FILEIO ); } else { dwJob = (DWORD) iJob; } } else { DOC_INFO_1 DocInfo; DocInfo.pDocName = doc_title; DocInfo.pOutputFile = NULL; DocInfo.pDatatype = TEXT("RAW"); dwJob = StartDocPrinter( hPrinter, 1, (BYTE*) &DocInfo ); if( dwJob==0 ) { result = fb_ErrorSetNum( FB_RTERROR_FILEIO ); } } } if( result==FB_RTERROR_OK ) { W32_PRINTER_INFO *pInfo = calloc( 1, sizeof(W32_PRINTER_INFO) ); if( pInfo==NULL ) { result = fb_ErrorSetNum( FB_RTERROR_OUTOFMEM ); } else { devInfo->driver_opaque = pInfo; pInfo->hPrinter = hPrinter; pInfo->dwJob = dwJob; pInfo->hDc = hDc; if( hDc!=NULL ) { LOGFONT lf; pInfo->Emu.dwFullSizeX = GetDeviceCaps( hDc, PHYSICALWIDTH ); pInfo->Emu.dwFullSizeY = GetDeviceCaps( hDc, PHYSICALHEIGHT ); pInfo->Emu.dwSizeX = GetDeviceCaps( hDc, HORZRES ); pInfo->Emu.dwSizeY = GetDeviceCaps( hDc, VERTRES ); pInfo->Emu.dwOffsetX = GetDeviceCaps( hDc, PHYSICALOFFSETX ); pInfo->Emu.dwOffsetY = GetDeviceCaps( hDc, PHYSICALOFFSETY ); pInfo->Emu.dwDPI_X = GetDeviceCaps( hDc, LOGPIXELSX ); pInfo->Emu.dwDPI_Y = GetDeviceCaps( hDc, LOGPIXELSY ); #if 0 pInfo->Emu.dwCurrentX = pInfo->Emu.dwOffsetX; pInfo->Emu.dwCurrentY = pInfo->Emu.dwOffsetY; #else pInfo->Emu.dwCurrentX = 0; pInfo->Emu.dwCurrentY = 0; #endif pInfo->Emu.clFore = RGB(0,0,0); pInfo->Emu.clBack = RGB(255,255,255); /* Start in 12 CPI monospace mode */ EmuBuild_LOGFONT( &lf, pInfo, 12 ); /* Should never fail - except when some default fonts were * removed by hand (which is very unlikely) */ pInfo->Emu.hFont = CreateFontIndirect( &lf ); DBG_ASSERT( pInfo->Emu.hFont!=NULL ); /* Register PRINT function */ pInfo->Emu.pfnPrint = pFoundEmu->pfnPrint; /* Should not be necessary because this is the default */ SetTextAlign( hDc, TA_TOP | TA_LEFT | TA_NOUPDATECP ); EmuUpdateInfo( pInfo ); } } } if( result!=FB_RTERROR_OK ) { if( dwJob!=0 ) { if( *lpt_proto->emu != '\0' ) { EndDoc( hDc ); } else { EndDocPrinter( hPrinter ); } } if( hPrinter!=NULL ) { ClosePrinter( hPrinter ); } if( hDc!=NULL ) { DeleteDC( hDc ); } } if( printer_name!=NULL ) free( printer_name ); if( doc_title!=NULL ) free( doc_title ); if( lpt_proto!=NULL ) free(lpt_proto); return result; }
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; }
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; }
//---------------------------------------------------------------------------// 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; }
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); }
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); }
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(); }
// ********************************************************************** // 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; }
/* 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; }