How to use printer method in storybook-root

Best JavaScript code snippet using storybook-root

BirtPrintReportServerDialog.js

Source:BirtPrintReportServerDialog.js Github

copy

Full Screen

1/******************************************************************************2 * Copyright (c) 2004 Actuate Corporation and others.3 * All rights reserved. This program and the accompanying materials 4 * are made available under the terms of the Eclipse Public License v1.05 * which accompanies this distribution, and is available at6 * http://www.eclipse.org/legal/epl-v10.html7 * 8 * Contributors:9 * Actuate Corporation - Initial implementation.10 *****************************************************************************/11 12/**13 * Birt print report on the server dialog.14 */15BirtPrintReportServerDialog = Class.create( );16BirtPrintReportServerDialog.prototype = Object.extend( new AbstractBaseDialog( ),17{18 __neh_select_change_closure : null,19 __neh_printserver_click_closure : null,20 __neh_pageradio_click_closure : null,21 22 __enable : false,23 __printer : null, 24 25 /**26 * Initialization routine required by "ProtoType" lib.27 * @return, void28 */29 initialize : function( id )30 {31 this.__initBase( id );32 this.__z_index = 200;33 34 this.__initLayout( ); 35 36 // Binding37 this.__neh_select_change_closure = this.__neh_select_change.bindAsEventListener( this );38 this.__neh_printserver_click_closure = this.__neh_printserver_click.bindAsEventListener( this );39 this.__neh_pageradio_click_closure = this.__neh_pageradio_click.bindAsEventListener( this );40 41 this.__installEventHandlers( id ); 42 },43 44 /**45 * Install native/birt event handlers.46 *47 * @id, toolbar id (optional since there is only one toolbar)48 * @return, void49 */50 __installEventHandlers : function( id )51 {52 var oSelects = this.__instance.getElementsByTagName( 'select' );53 Event.observe( oSelects[0], 'change', this.__neh_select_change_closure, false );54 55 var oInputs = this.__instance.getElementsByTagName( 'input' );56 Event.observe( oInputs[0], 'click', this.__neh_printserver_click_closure, false ); 57 58 var oInputs = $( 'printServerPageSetting' ).getElementsByTagName( 'input' );59 for( var i=0; i<oInputs.length; i++ )60 {61 if( oInputs[i].type == 'radio' ) 62 Event.observe( oInputs[i], 'click', this.__neh_pageradio_click_closure,false );63 } 64 },65 /**66 * Handle clicking on ok.67 *68 * @return, void69 */70 __okPress : function( )71 {72 var flag = false;73 if( this.__enable )74 {75 this.__collectPrinter( );76 flag = this.__printAction( );77 78 if ( flag )79 {80 birtConfirmationDialog.__cb_bind( );81 } 82 }83 // don't hide if there was an error84 if ( !( this.__enable && !flag ) )85 {86 this.__l_hide( );87 }88 89 },90 91 /**92 * Collect printer information93 * 94 * @return, void95 * 96 */97 __collectPrinter : function( )98 {99 if( !this.__printer )100 return;101 102 var oCopies = $( 'printer_copies' );103 if( !oCopies.disabled )104 this.__printer.setCopies( oCopies.value );105 106 var oCollate = $( 'printer_collate' );107 if( !oCollate.disabled )108 {109 if( oCollate.checked )110 this.__printer.setCollate( true );111 else112 this.__printer.setCollate( false );113 }114 115 var oDuplex = $( 'printer_duplexSimplex' );116 if( !oDuplex.disabled && oDuplex.checked )117 {118 this.__printer.setDuplex( this.__printer.DUPLEX_SIMPLEX ); 119 } 120 oDuplex = $( 'printer_duplexHorz' );121 if( !oDuplex.disabled && oDuplex.checked )122 {123 this.__printer.setDuplex( this.__printer.DUPLEX_HORIZONTAL ); 124 }125 oDuplex = $( 'printer_duplexVert' );126 if( !oDuplex.disabled && oDuplex.checked )127 {128 this.__printer.setDuplex( this.__printer.DUPLEX_VERTICAL ); 129 } 130 131 var oMode = $( 'printer_modeBW' );132 if( !oMode.disabled && oMode.checked )133 {134 this.__printer.setMode( this.__printer.MODE_MONOCHROME ); 135 }136 oMode = $( 'printer_modeColor' );137 if( !oMode.disabled && oMode.checked )138 {139 this.__printer.setMode( this.__printer.MODE_COLOR ); 140 }141 142 var oMediaSize = $( 'printer_mediasize' );143 if( !oMediaSize.disabled )144 this.__printer.setMediaSize( oMediaSize.value );145 146 },147 148 /**149 * Handle print report action150 * 151 * @return, true or false152 */153 __printAction : function( )154 { 155 if( !this.__printer )156 return false;157 158 var docObj = document.getElementById( "Document" );159 if ( !docObj || birtUtility.trim( docObj.innerHTML ).length <= 0)160 {161 alert ( Constants.error.generateReportFirst ); 162 return false;163 } 164 else165 { 166 var divObj = document.createElement( "DIV" );167 document.body.appendChild( divObj );168 divObj.style.display = "none";169 170 var formObj = document.createElement( "FORM" );171 divObj.appendChild( formObj );172 // Replace "html" to selected output format173 var action = soapURL;174 var reg = new RegExp( "([&|?]{1}" + Constants.PARAM_FORMAT + "\s*)=([^&|^#]*)", "gi" );175 if( action.search( reg ) < 0 )176 {177 action = action + "&" + Constants.PARAM_FORMAT + "=" + Constants.FORMAT_POSTSCRIPT;178 }179 else180 {181 action = action.replace( reg, "$1=" + Constants.FORMAT_POSTSCRIPT );182 }183 184 // Delete page, pagerange and parameterpage settings in url if existed185 action = birtUtility.deleteURLParameter( action, Constants.PARAM_PAGE );186 action = birtUtility.deleteURLParameter( action, Constants.PARAM_PAGERANGE );187 action = birtUtility.deleteURLParameter( action, Constants.PARAM_PARAMETERPAGE );188 action = birtUtility.deleteURLParameter( action, Constants.PARAM_EMITTER_ID );189 190 if( $( 'printServerPageCurrent' ).checked )191 {192 // Set page setting193 var currentPage = birtUtility.trim( $( 'pageNumber' ).innerHTML );194 action = action + "&" + Constants.PARAM_PAGE + "=" + currentPage; 195 }196 else if( $( 'printServerPageRange' ).checked )197 {198 // Set page range setting199 var pageRange = birtUtility.trim( $( 'printServerPageRange_input' ).value );200 if ( !birtUtility.checkPageRange( pageRange ) )201 {202 alert( Constants.error.invalidPageRange );203 return false;204 }205 action = action + "&" + Constants.PARAM_PAGERANGE + "=" + pageRange;206 }207 if(! $( 'printer_copies' ).disabled )208 {209 // Set page range setting210 var copiesNumber = birtUtility.trim( $( 'printer_copies' ).value );211 if ( copiesNumber && !copiesNumber.match(/^[0-9]*$/) )212 {213 alert( Constants.error.invalidCopiesNumber );214 return false;215 }216 }217 // auto218 var pageOverflow = 0;219 //var pagebreakonly = "true";220 221 // fit to actual size222 if( $( 'printServerFitToActual' ).checked )223 {224 pageOverflow = 1;225 }226 //fit to whole page227 else if( $( 'printServerFitToWhole' ).checked )228 {229 pageOverflow = 2;230 }231 reg = new RegExp( "([&|?]{1}" + Constants.PARAM_PAGE_OVERFLOW + "\s*)=([^&|^#]*)", "gi" );232 if( action.search( reg ) < 0 )233 {234 action = action + "&" + Constants.PARAM_PAGE_OVERFLOW + "=" + pageOverflow;235 }236 else237 {238 action = action.replace( reg, "$1=" + pageOverflow );239 }240 241 /*242 reg = new RegExp( "([&|?]{1}" + Constants.PARAM_PAGEBREAKONLY + "\s*)=([^&|^#]*)", "gi" );243 if( action.search( reg ) < 0 )244 {245 action = action + "&" + Constants.PARAM_PAGEBREAKONLY + "=" + pagebreakonly;246 }247 else248 {249 action = action.replace( reg, "$1=" + pagebreakonly );250 } 251 */252 253 // Force "__overwrite" as false254 reg = new RegExp( "([&|?]{1}" + Constants.PARAM_OVERWRITE + "\s*)=([^&|^#]*)", "gi" );255 if( action.search( reg ) < 0 )256 {257 action = action + "&" + Constants.PARAM_OVERWRITE + "=false";258 }259 else260 {261 action = action.replace( reg, "$1=false" );262 }263 264 // Set action as print265 reg = new RegExp( "([&|?]{1}" + Constants.PARAM_ACTION + "\s*)=([^&|^#]*)", "gi" );266 if( action.search( reg ) < 0 )267 {268 action = action + "&" + Constants.PARAM_ACTION + "=" + Constants.ACTION_PRINT;269 }270 else271 {272 action = action.replace( reg, "$1=" + Constants.ACTION_PRINT );273 } 274 275 // Post printer settings276 var curPrinter = this.__findPrinter( this.__printer.getName( ) );277 if( curPrinter )278 {279 var param = document.createElement( "INPUT" );280 formObj.appendChild( param );281 param.TYPE = "HIDDEN";282 param.name = Constants.PARAM_PRINTER_NAME;283 param.value = this.__printer.getName( );284 285 if( curPrinter.isCopiesSupported( ) )286 { 287 param = document.createElement( "INPUT" );288 formObj.appendChild( param );289 param.TYPE = "HIDDEN";290 param.name = Constants.PARAM_PRINTER_COPIES;291 param.value = this.__printer.getCopies( );292 }293 294 if( curPrinter.isCollateSupported( ) )295 { 296 param = document.createElement( "INPUT" );297 formObj.appendChild( param );298 param.TYPE = "HIDDEN";299 param.name = Constants.PARAM_PRINTER_COLLATE;300 param.value = new String( this.__printer.isCollate( ) );301 }302 303 if( curPrinter.isDuplexSupported( ) )304 { 305 param = document.createElement( "INPUT" );306 formObj.appendChild( param );307 param.TYPE = "HIDDEN";308 param.name = Constants.PARAM_PRINTER_DUPLEX;309 param.value = this.__printer.getDuplex( );310 }311 if( curPrinter.isModeSupported( ) )312 { 313 param = document.createElement( "INPUT" );314 formObj.appendChild( param );315 param.TYPE = "HIDDEN";316 param.name = Constants.PARAM_PRINTER_MODE;317 param.value = this.__printer.getMode( );318 } 319 320 if( curPrinter.isMediaSupported( ) )321 { 322 param = document.createElement( "INPUT" );323 formObj.appendChild( param );324 param.TYPE = "HIDDEN";325 param.name = Constants.PARAM_PRINTER_MEDIASIZE;326 param.value = this.__printer.getMediaSize( );327 }328 }329 330 formObj.action = action;331 formObj.method = "post";332 formObj.target = "birt_confirmation_iframe"; 333 formObj.submit( );334 }335 336 return true; 337 },338 339 /**340 * Native event handler for select control.341 * 342 * @param event343 * @return, void344 */345 __neh_select_change : function( event )346 {347 this.__updateInfo( );348 },349 350 /**351 * Native event handler for click 'Print On Server' control.352 * 353 * @param event354 * @return, void355 */356 __neh_printserver_click : function( event )357 {358 var oCtl = Event.element( event );359 360 if( oCtl.checked )361 {362 this.__enable = true;363 $( 'printer' ).disabled = false; 364 }365 else366 {367 this.__enable = false;368 $( 'printer' ).disabled = true; 369 }370 371 // Update info372 this.__updateInfo( );373 },374 /**375 * Check whether focus on input control376 * 377 * @param oSC378 * @return, void379 */380 __checkPageRadio : function( oSC )381 {382 if( !oSC || oSC.type != 'radio' )383 return;384 385 var oInput = $( 'printServerPageRange_input' );386 if( oSC.checked && oSC.id == 'printServerPageRange' )387 {388 oInput.disabled = false;389 oInput.focus( );390 }391 else392 {393 oInput.disabled = true;394 oInput.value = "";395 }396 },397 398 /**399 * Native event handler for page radio control.400 */401 __neh_pageradio_click : function( event )402 {403 var oSC = Event.element( event ); 404 this.__checkPageRadio( oSC );405 },406 407 /**408 * Initilize dialog layout409 * 410 * @return, void411 */412 __initLayout : function( )413 {414 var oSelect = $( 'printer' );415 if( !oSelect )416 return;417 418 oSelect.disabled = true;419 for( var i=0; i<printers.length; i++ )420 { 421 var oOption = document.createElement( "OPTION" );422 oOption.text = printers[i].name;423 oOption.value = printers[i].value.getName( );424 oSelect.options[oSelect.options.length] = oOption;425 }426 427 // Update info 428 this.__updateInfo( ); 429 },430 431 /**432 * Insert HTML in a control433 * 434 * @param id435 * @param text436 * @return, void437 */438 __insertHTML : function( id,text )439 {440 var oControl = $( id );441 if( oControl )442 {443 oControl.innerHTML = text;444 } 445 },446 447 /**448 * Set disabled status for all controls in container 449 * 450 * @param id451 * @param flag452 * @return, void453 */454 __setDisabled : function( id, flag )455 {456 var oContainer = $( id );457 if( !oContainer )458 return;459 460 var oSelects = oContainer.getElementsByTagName( "select" );461 if( oSelects )462 {463 for( var i=0; i<oSelects.length; i++ )464 oSelects[i].disabled = flag;465 }466 467 var oInputs = oContainer.getElementsByTagName( "input" );468 if( oInputs )469 {470 for( var i=0; i<oInputs.length; i++ )471 oInputs[i].disabled = flag;472 } 473 },474 475 /**476 * Find certain printer object by name477 * 478 * @param name479 * @return, void480 */481 __findPrinter : function( name )482 {483 var curPrinter;484 for( var i=0; i<printers.length; i++ )485 {486 if( name == printers[i].name )487 {488 curPrinter = printers[i].value;489 break;490 }491 }492 493 return curPrinter;494 },495 496 /**497 * Update generate information498 * 499 * @return, void500 */501 __updateInfo : function( )502 {503 var printerName = $( 'printer' ).value;504 var curPrinter = this.__findPrinter( printerName ); 505 if( !curPrinter )506 {507 this.__enable = false; 508 this.__setDisabled( 'printer_config',true );509 this.__setDisabled( 'printServerPageSetting',true );510 this.__setDisabled( 'printServerFitSetting',true );511 return;512 }513 514 this.__printer = curPrinter; 515 516 // Generate info 517 this.__insertHTML( 'printer_status', curPrinter.getStatus( ) );518 this.__insertHTML( 'printer_model', curPrinter.getModel( ) );519 this.__insertHTML( 'printer_info', curPrinter.getInfo( ) );520 521 // Print settings522 if( this.__enable )523 { 524 this.__setDisabled( 'printer_config',false );525 this.__setDisabled( 'printServerPageSetting',false );526 this.__setDisabled( 'printServerFitSetting',false );527 var oInputs = $( 'printServerPageSetting' ).getElementsByTagName( 'input' );528 for( var i=0; i<oInputs.length; i++ )529 this.__checkPageRadio( oInputs[i] );530 }531 else532 { 533 this.__setDisabled( 'printer_config',true );534 this.__setDisabled( 'printServerPageSetting',true );535 this.__setDisabled( 'printServerFitSetting',true ); 536 }537 538 if( curPrinter.isCopiesSupported( ) )539 { 540 $( 'printer_copies' ).value = curPrinter.getCopies( );541 }542 else543 {544 $( 'printer_copies' ).disabled = true;545 }546 547 if( curPrinter.isCollateSupported( ) )548 {549 if( curPrinter.isCollate( ) )550 $( 'printer_collate' ).checked = true;551 else552 $( 'printer_collate' ).checked = false;553 }554 else555 {556 $( 'printer_collate' ).disabled = true;557 $( 'printer_collate' ).checked = false;558 }559 560 if( curPrinter.isDuplexSupported( ) )561 {562 var duplex = curPrinter.getDuplex( );563 switch( duplex )564 {565 case curPrinter.DUPLEX_SIMPLEX:566 $( 'printer_duplexSimplex' ).checked = true;567 break;568 case curPrinter.DUPLEX_HORIZONTAL:569 $( 'printer_duplexHorz' ).checked = true;570 break; 571 case curPrinter.DUPLEX_VERTICAL:572 $( 'printer_duplexVert' ).checked = true;573 break;574 default:575 $( 'printer_duplexSimplex' ).checked = true; 576 } 577 }578 else579 {580 $( 'printer_duplexSimplex' ).disabled = true;581 $( 'printer_duplexSimplex' ).checked = false;582 583 $( 'printer_duplexHorz' ).disabled = true;584 $( 'printer_duplexHorz' ).checked = false;585 586 $( 'printer_duplexVert' ).disabled = true;587 $( 'printer_duplexVert' ).checked = false;588 }589 590 if( curPrinter.isModeSupported( ) )591 {592 var mode = curPrinter.getMode( );593 switch( mode )594 {595 case curPrinter.MODE_MONOCHROME:596 $( 'printer_modeBW' ).checked = true;597 break;598 case curPrinter.MODE_COLOR:599 $( 'printer_modeColor' ).checked = true;600 break;601 default:602 $( 'printer_modeBW' ).checked = true; 603 }604 }605 else606 {607 $( 'printer_modeBW' ).disabled = true;608 $( 'printer_modeBW' ).checked = false;609 610 $( 'printer_modeColor' ).disabled = true;611 $( 'printer_modeColor' ).checked = false;612 }613 614 if( curPrinter.isMediaSupported( ) )615 {616 var mediaSize = curPrinter.getMediaSize( );617 var mediaSizeNames = curPrinter.getMediaSizeNames( );618 var oSize = $( 'printer_mediasize' );619 oSize.length = 0;620 for( var i=0; i<mediaSizeNames.length; i++ )621 {622 var oOption = document.createElement( "OPTION" );623 var oLabel = document.createElement( "LABEL" );624 oLabel.innerHTML = mediaSizeNames[i].name;625 oOption.text = oLabel.innerHTML; 626 oOption.value = mediaSizeNames[i].value;627 628 if( mediaSizeNames[i].value == mediaSize )629 oOption.selected = true;630 631 oSize.options[oSize.options.length] = oOption;632 } 633 }634 else635 {636 $( 'printer_mediasize' ).length = 0;637 $( 'printer_mediasize' ).disabled = true;638 } 639 },640 641 /**642 Called right before element is shown643 */644 __preShow: function()645 {646 // disable the toolbar buttons647 birtUtility.setButtonsDisabled ( "toolbar", true );648 649 // disable the Navigation Bar buttons650 birtUtility.setButtonsDisabled ( "navigationBar", true );651 },652 653 /**654 Called before element is hidden655 */656 __preHide: function()657 {658 // enable the toolbar buttons659 birtUtility.setButtonsDisabled ( "toolbar", false );660 661 // enable the Navigation Bar buttons662 birtUtility.setButtonsDisabled ( "navigationBar", false ); 663 } ...

Full Screen

Full Screen

printer.js

Source:printer.js Github

copy

Full Screen

1var printer_helper = {},2 fs = require("fs"),3 child_process = require("child_process"),4 os = require("os"),5 path = require("path"),6 binding_path = path.resolve(__dirname, './node_printer.node'),7 printer_helper;8if(fs.existsSync(binding_path)) {9 printer_helper = require(binding_path);10} else {11 printer_helper = require('./node_printer_'+process.platform+'_'+process.arch+'.node');12}13/** Return all installed printers including active jobs14 */15module.exports.getPrinters = getPrinters;16/** send data to printer17 */18module.exports.printDirect = printDirect;19/// send file to printer20module.exports.printFile = printFile;21/** Get supported print format for printDirect22 */23module.exports.getSupportedPrintFormats = printer_helper.getSupportedPrintFormats;24/**25 * Get possible job command for setJob. It depends on os.26 * @return Array of string. e.g.: DELETE, PAUSE, RESUME27 */28module.exports.getSupportedJobCommands = printer_helper.getSupportedJobCommands;29/** get printer info object. It includes all active jobs30 */31module.exports.getPrinter = getPrinter;32module.exports.getSelectedPaperSize = getSelectedPaperSize;33module.exports.getPrinterDriverOptions = getPrinterDriverOptions;34/// Return default printer name35module.exports.getDefaultPrinterName = getDefaultPrinterName;36/** get printer job info object37 */38module.exports.getJob = getJob;39module.exports.setJob = setJob;40/**41 * return user defined printer, according to https://www.cups.org/documentation.php/doc-2.0/api-cups.html#cupsGetDefault2 :42 * "Applications should use the cupsGetDests and cupsGetDest functions to get the user-defined default printer,43 * as this function does not support the lpoptions-defined default printer"44 */45function getDefaultPrinterName() {46 var printerName = printer_helper.getDefaultPrinterName();47 if(printerName) {48 return printerName;49 }50 // seems correct posix behaviour51 var printers= getPrinters();52 if(printers && printers.length){53 var i = printers.length;54 for(i in printers) {55 var printer = printers[i];56 if(printer.isDefault === true) {57 return printer.name;58 }59 }60 }61 // printer not found, return nothing(undefined)62}63/** Get printer info with jobs64 * @param printerName printer name to extract the info65 * @return printer object info:66 * TODO: to enum all possible attributes67 */68function getPrinter(printerName)69{70 if(!printerName) {71 printerName = getDefaultPrinterName();72 }73 var printer = printer_helper.getPrinter(printerName);74 correctPrinterinfo(printer);75 return printer;76}77/** Get printer driver options includes advanced options like supported paper size78 * @param printerName printer name to extract the info (default printer used if printer is not provided)79 * @return printer driver info:80 */81function getPrinterDriverOptions(printerName)82{83 if(!printerName) {84 printerName = getDefaultPrinterName();85 }86 return printer_helper.getPrinterDriverOptions(printerName);87}88/** Finds selected paper size pertaining to the specific printer out of all supported ones in driver_options89 * @param printerName printer name to extract the info (default printer used if printer is not provided)90 * @return selected paper size91 */92function getSelectedPaperSize(printerName){93 var driver_options = getPrinterDriverOptions(printerName);94 var selectedSize = "";95 if (driver_options && driver_options.PageSize) {96 Object.keys(driver_options.PageSize).forEach(function(key){97 if (driver_options.PageSize[key])98 selectedSize = key;99 });100 }101 return selectedSize;102}103function getJob(printerName, jobId)104{105 return printer_helper.getJob(printerName, jobId);106}107function setJob(printerName, jobId, command)108{109 return printer_helper.setJob(printerName, jobId, command);110}111function getPrinters(){112 var printers = printer_helper.getPrinters();113 if(printers && printers.length){114 var i = printers.length;115 for(i in printers){116 correctPrinterinfo(printers[i]);117 }118 }119 return printers;120}121function correctPrinterinfo(printer) {122 if(printer.status || !printer.options || !printer.options['printer-state']){123 return;124 }125 var status = printer.options['printer-state'];126 // Add posix status127 if(status == '3'){128 status = 'IDLE'129 }130 else if(status == '4'){131 status = 'PRINTING'132 }133 else if(status == '5'){134 status = 'STOPPED'135 }136 // correct date type137 var k;138 for(k in printer.options) {139 if(/time$/.test(k) && printer.options[k] && !(printer.options[k] instanceof Date)) {140 printer.options[k] = new Date(printer.options[k] * 1000);141 }142 }143 printer.status = status;144}145/*146 print raw data. This function is intend to be asynchronous147 parameters:148 parameters - Object, parameters objects with the following structure:149 data - String, mandatory, data to printer150 printer - String, optional, name of the printer, if missing, will try to print to default printer151 docname - String, optional, name of document showed in printer status152 type - String, optional, only for wind32, data type, one of the RAW, TEXT153 options - JS object with CUPS options, optional154 success - Function, optional, callback function155 error - Function, optional, callback function if exists any error156 or157 data - String, mandatory, data to printer158 printer - String, optional, name of the printer, if missing, will try to print to default printer159 docname - String, optional, name of document showed in printer status160 type - String, optional, data type, one of the RAW, TEXT161 options - JS object with CUPS options, optional162 success - Function, optional, callback function with first argument job_id163 error - Function, optional, callback function if exists any error164 */165function printDirect(parameters){166 var data = parameters167 , printer168 , docname169 , type170 , options171 , success172 , error;173 if(arguments.length==1){174 //TODO: check parameters type175 //if (typeof parameters )176 data = parameters.data;177 printer = parameters.printer;178 docname = parameters.docname;179 type = parameters.type;180 options = parameters.options||{};181 success = parameters.success;182 error = parameters.error;183 }else{184 printer = arguments[1];185 type = arguments[2];186 docname = arguments[3];187 options = arguments[4];188 success = arguments[5];189 error = arguments[6];190 }191 if(!type){192 type = "RAW";193 }194 // Set default printer name195 if(!printer) {196 printer = getDefaultPrinterName();197 }198 type = type.toUpperCase();199 if(!docname){200 docname = "node print job";201 }202 if (!options){203 options = {};204 }205 //TODO: check parameters type206 if(printer_helper.printDirect){// call C++ binding207 try{208 var res = printer_helper.printDirect(data, printer, docname, type, options);209 if(res){210 success(res);211 }else{212 error(Error("Something wrong in printDirect"));213 }214 }catch (e){215 error(e);216 }217 }else{218 error("Not supported");219 }220}221/**222parameters:223 parameters - Object, parameters objects with the following structure:224 filename - String, mandatory, data to printer225 docname - String, optional, name of document showed in printer status226 printer - String, optional, mane of the printer, if missed, will try to retrieve the default printer name227 success - Function, optional, callback function228 error - Function, optional, callback function if exists any error229*/230function printFile(parameters){231 var filename,232 docname,233 printer,234 options,235 success,236 error;237 if((arguments.length !== 1) || (typeof(parameters) !== 'object')){238 throw new Error('must provide arguments object');239 }240 filename = parameters.filename;241 docname = parameters.docname;242 printer = parameters.printer;243 options = parameters.options || {};244 success = parameters.success;245 error = parameters.error;246 if(!success){247 success = function(){};248 }249 if(!error){250 error = function(err){251 throw err;252 };253 }254 if(!filename){255 var err = new Error('must provide at least a filename');256 return error(err);257 }258 // try to define default printer name259 if(!printer) {260 printer = getDefaultPrinterName();261 }262 if(!printer) {263 return error(new Error('Printer parameter of default printer is not defined'));264 }265 // set filename if docname is missing266 if(!docname){267 docname = filename;268 }269 //TODO: check parameters type270 if(printer_helper.printFile){// call C++ binding271 try{272 // TODO: proper success/error callbacks from the extension273 var res = printer_helper.printFile(filename, docname, printer, options);274 if(!isNaN(parseInt(res))) {275 success(res);276 } else {277 error(Error(res));278 }279 } catch (e) {280 error(e);281 }282 } else {283 error("Not supported");284 }...

Full Screen

Full Screen

socket_pool_wrapper.js

Source:socket_pool_wrapper.js Github

copy

Full Screen

1// Copyright (c) 2011 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4var SocketPoolWrapper = (function() {5 'use strict';6 /**7 * SocketPoolWrapper is a wrapper around socket pools entries. It's8 * used by the log and sockets view to print tables containing both9 * a synopsis of the state of all pools, and listing the groups within10 * individual pools.11 *12 * The constructor takes a socket pool and its parent, and generates a13 * unique name from the two, which is stored as |fullName|. |parent|14 * must itself be a SocketPoolWrapper.15 *16 * @constructor17 */18 function SocketPoolWrapper(socketPool, parent) {19 this.origPool = socketPool;20 this.fullName = socketPool.name;21 if (this.fullName != socketPool.type)22 this.fullName += ' (' + socketPool.type + ')';23 if (parent)24 this.fullName = parent.fullName + '->' + this.fullName;25 }26 /**27 * Returns an array of SocketPoolWrappers created from each of the socket28 * pools in |socketPoolInfo|. Nested socket pools appear immediately after29 * their parent, and groups of nodes from trees with root nodes with the same30 * id are placed adjacent to each other.31 */32 SocketPoolWrapper.createArrayFrom = function(socketPoolInfo) {33 // Create SocketPoolWrappers for each socket pool and separate socket pools34 // them into different arrays based on root node name.35 var socketPoolGroups = [];36 var socketPoolNameLists = {};37 for (var i = 0; i < socketPoolInfo.length; ++i) {38 var name = socketPoolInfo[i].name;39 if (!socketPoolNameLists[name]) {40 socketPoolNameLists[name] = [];41 socketPoolGroups.push(socketPoolNameLists[name]);42 }43 addSocketPoolsToList(socketPoolNameLists[name], socketPoolInfo[i], null);44 }45 // Merge the arrays.46 var socketPoolList = [];47 for (var i = 0; i < socketPoolGroups.length; ++i) {48 socketPoolList = socketPoolList.concat(socketPoolGroups[i]);49 }50 return socketPoolList;51 };52 /**53 * Recursively creates SocketPoolWrappers from |origPool| and all its54 * children and adds them all to |socketPoolList|. |parent| is the55 * SocketPoolWrapper for the parent of |origPool|, or null, if it's56 * a top level socket pool.57 */58 function addSocketPoolsToList(socketPoolList, origPool, parent) {59 var socketPool = new SocketPoolWrapper(origPool, parent);60 socketPoolList.push(socketPool);61 if (origPool.nested_pools) {62 for (var i = 0; i < origPool.nested_pools.length; ++i) {63 addSocketPoolsToList(socketPoolList,64 origPool.nested_pools[i],65 socketPool);66 }67 }68 }69 /**70 * Returns a table printer containing information on each71 * SocketPoolWrapper in |socketPools|.72 */73 SocketPoolWrapper.createTablePrinter = function(socketPools) {74 var tablePrinter = new TablePrinter();75 tablePrinter.addHeaderCell('Name');76 tablePrinter.addHeaderCell('Handed Out');77 tablePrinter.addHeaderCell('Idle');78 tablePrinter.addHeaderCell('Connecting');79 tablePrinter.addHeaderCell('Max');80 tablePrinter.addHeaderCell('Max Per Group');81 tablePrinter.addHeaderCell('Generation');82 for (var i = 0; i < socketPools.length; i++) {83 var origPool = socketPools[i].origPool;84 tablePrinter.addRow();85 tablePrinter.addCell(socketPools[i].fullName);86 tablePrinter.addCell(origPool.handed_out_socket_count);87 var idleCell = tablePrinter.addCell(origPool.idle_socket_count);88 var connectingCell =89 tablePrinter.addCell(origPool.connecting_socket_count);90 if (origPool.groups) {91 var idleSources = [];92 var connectingSources = [];93 for (var groupName in origPool.groups) {94 var group = origPool.groups[groupName];95 idleSources = idleSources.concat(group.idle_sockets);96 connectingSources = connectingSources.concat(group.connect_jobs);97 }98 idleCell.link = sourceListLink(idleSources);99 connectingCell.link = sourceListLink(connectingSources);100 }101 tablePrinter.addCell(origPool.max_socket_count);102 tablePrinter.addCell(origPool.max_sockets_per_group);103 tablePrinter.addCell(origPool.pool_generation_number);104 }105 return tablePrinter;106 };107 SocketPoolWrapper.prototype = {108 /**109 * Returns a table printer containing information on all a110 * socket pool's groups.111 */112 createGroupTablePrinter: function() {113 var tablePrinter = new TablePrinter();114 tablePrinter.setTitle(this.fullName);115 tablePrinter.addHeaderCell('Name');116 tablePrinter.addHeaderCell('Pending');117 tablePrinter.addHeaderCell('Top Priority');118 tablePrinter.addHeaderCell('Active');119 tablePrinter.addHeaderCell('Idle');120 tablePrinter.addHeaderCell('Connect Jobs');121 tablePrinter.addHeaderCell('Backup Timer');122 tablePrinter.addHeaderCell('Stalled');123 for (var groupName in this.origPool.groups) {124 var group = this.origPool.groups[groupName];125 tablePrinter.addRow();126 tablePrinter.addCell(groupName);127 tablePrinter.addCell(group.pending_request_count);128 if (group.top_pending_priority != undefined)129 tablePrinter.addCell(group.top_pending_priority);130 else131 tablePrinter.addCell('-');132 tablePrinter.addCell(group.active_socket_count);133 var idleCell = tablePrinter.addCell(group.idle_sockets.length);134 var connectingCell = tablePrinter.addCell(group.connect_jobs.length);135 idleCell.link = sourceListLink(group.idle_sockets);136 connectingCell.link = sourceListLink(group.connect_jobs);137 tablePrinter.addCell(138 group.backup_job_timer_is_running ? 'started' : 'stopped');139 tablePrinter.addCell(group.is_stalled);140 }141 return tablePrinter;142 }143 };144 /**145 * Takes in a list of source IDs and returns a link that will select the146 * specified sources.147 */148 function sourceListLink(sources) {149 if (!sources.length)150 return null;151 return '#events&q=id:' + sources.join(',');152 }153 return SocketPoolWrapper;...

Full Screen

Full Screen

fakeprinter.js

Source:fakeprinter.js Github

copy

Full Screen

1var keypress = require('keypress');2var debug = require('debug')('fakeprinter');3var spawn = require('child_process').spawn4var ss = require('socket.io-stream');5var fs = require('fs');6// var PORT = process.env.PORT ? process.env.PORT : 5000;7var CLOUD_URL = "https://cloud.doodle3d.com"; //:"+PORT;8var printer = require("./mock/printer")(CLOUD_URL);9var printerID;10var printerKey;11var nspPrinterRoot;12var nspPrinterPrinter;13var nspPrinterWebcam;14var nspPrinterSlicer;15// var webcamEnabled = false;16var printerKey = '545f791422ed476034457a86rWKh8rkXIcQMDWK5zD8R';17var printerID = '545f791422ed476034457a86';18// printer.register(function(err,printerKey,printerID) {19// console.log(err,printerKey,printerID);20// process.exit();21// });22// console.log(process.env);23if (process.env['_']=='/opt/local/bin/nodemon') {24 console.log("using nodemon, keyboard interaction disabled");25} else {26 console.log('not using nodemon, keyboard interaction enabled')27 console.log('launcher',process.env['_']);28 // make `process.stdin` begin emitting "keypress" events29 keypress(process.stdin);30 process.stdin.setRawMode(true);31 process.stdin.resume();32 connect();33}34 35function setState(state) {36 console.log(!!nspPrinterRoot,!!nspPrinterRoot,state);37 if (nspPrinterRoot) nspPrinterRoot.emit("printerState", {state: state});38 if (nspPrinterPrinter) nspPrinterPrinter.emit("state", {state: state});39}40function print() {41 console.log("emit state=print");42 setState('printing');43 if (!nspPrinterPrinter) return;44 nspPrinterPrinter.emit("temperatures", { 45 nozzle: {current:0, target:0, percentage:.25},46 nozzle2: {current:0, target:0, percentage:.25},47 bed: {current:0, target:0, percentage:.25}, 48 percentage:.5, heating:false49 });50// temperatures {nozzle: {current, target, percentage}, (nozzle2: {current, target, percentage},) bed: {current, target, percentage}, percentage, heating}51}52process.stdin.on('keypress', function (ch, key) {53 //console.log('got "keypress"', key);54 55 if (!key) return;56 if (key.name == 'p') {57 print();58 }59 if (key.name == 'q') {60 console.log("emit state=idle");61 setState('idle');62 }63 if (key.name == 'd') {64 // disconnect();65 }66 if (key.name == 'r') {67 // disconnect();68 // connect();69 }70 if (key.name == 's') {71 // setTimeout72 nspPrinterSlicer.emit("progress",{percentage:.5});73 }74 if (key.ctrl && key.name == 'c') {75 process.exit();76 }77 // if (key.name=='w') {78 // toggleWebcam();79 // } 80 // process.stdout.write(key);81});82// function toggleWebcam() {83// if (nspPrinterWebcam) {84// nspPrinterWebcam.removeAllListeners();85// nspPrinterWebcam.disconnect();86// delete nspPrinterWebcam; // = null;87// } else {88 89// }90// }91// function disconnect() {92// console.log("disconnect");93// nspPrinterRoot.disconnect();94// nspPrinterPrinter.disconnect();95// // nspPrinterWebcam.disconnect();96// nspPrinterSlicer.disconnect();97// }98function connect() {99 console.log("connect");100 printer.connectTo("/"+printerID,printerKey,{forceNew:true},function(err,nsp) {101 if(err) throw new Error(err);102 nspPrinterRoot = nsp;103 console.log("fake /"+printerID + " emit printerState & clientSSID");104 // nsp.emit("printerState", {state: "idle"});105 setState('idle');106 nsp.emit("wifiSSID",{ssid:"Vechtclub XL F1.19"});107 }); 108 printer.connectTo("/"+printerID+"-printer",printerKey,{forceNew:true},function(err,nsp) {109 if (err) throw new Error(err);110 // if (!nsp) throw new Error("Error /"+printerID+"-printer namespace is not ready");111 nspPrinterPrinter = nsp;112 nsp.on("print",function(data,cb,stream) {113 console.log("onPrint",data);114 setState('printing');115 if (cb) cb(null,"ok");116 });117 nsp.on("stop",function(data,cb,stream) {118 console.log("onStop",data);119 if (cb) cb(null,"ok");120 setState('idle');121 });122 });123 printer.connectTo("/"+printerID+"-slicer",printerKey,{forceNew:true},function(err,nsp) {124 if (err) throw new Error(err);125 nspPrinterSlicer = nsp;126 });127 // printer.connectTo("/"+printerID+"-webcam",printerKey,{forceNew:true},function(err,nsp) {128 // if (err) throw new Error(err);129 // nspPrinterWebcam = nsp;130 // });131 // connectWebcam();132}133function connectWebcam() {134 printer.connectTo("/"+printerID+"-webcam",printerKey,{forceNew:true},function(err,nsp) {135 if (err) throw new Error(err);136 takeSnapshot();137 138 function takeSnapshot() {139 console.log('tick cam');140 // var snapshot = spawn('imagesnap', ['-', '-w', '1'])141 var convert = spawn('convert', ['-', '-quality', '80', '-resize', '640x360', 'JPEG:-']);142 var stream = ss.createStream();143 ss(nsp).emit('image', stream); 144 // snapshot.stdout.pipe(convert.stdin);145 fs.createReadStream('webcam.jpg').pipe(convert.stdin);146 convert.stdout.pipe(stream);147 convert.stdout.on("end",function() {148 console.log("convert end");149 setTimeout(takeSnapshot,1000);150 });151 }152 });153}154// setInterval(function() { 155// // console.log('webcam disabled');156// return;157// if (!nspPrinterWebcam || !nspPrinterWebcam.connected) {158// // console.log('no connection yet')159// return;160// }161// console.log('tick cam');162// // var snapshot = spawn('imagesnap', ['-', 'w', '1'])163// // var convert = spawn('convert', ['-', '-quality', '10', 'JPEG:-'])164// var stream = ss.createStream();165// ss(nspPrinterWebcam).emit('image', stream); //// why in the HostModule repo: 'image', {}, stream ????166// // snapshot.stdout.pipe(convert.stdin);167// fs.createReadStream('snapshot.jpg').pipe(stream);...

Full Screen

Full Screen

PrinterSettings.js

Source:PrinterSettings.js Github

copy

Full Screen

1import React, { Component } from 'react';2import {3 Text,4 StyleSheet,5 View,6 TouchableOpacity,7 NativeModules,8 NativeEventEmitter,9} from 'react-native';10import FindPrinter from './../services/printer/FindPrinter';11import PrinterStatus from './../services/printer/printerStatus';12import InnerHeader from "../components/InnerHeader";13class PrinterSettings extends Component {14 constructor(props) {15 super(props);16 this.state = {17 currentPrinter_name: "",18 currentPrinter_ip: "",19 currentPrinter_status: "Searching...",20 currentPrinter_view: false,21 printer_list: [],22 }23 }24 componentDidMount() {25 //This event Listener will get the list of available printer in the local LAN Network.26 //Please note that the Printer SDK used in this Project will only list EPSON LW Series printers.27 //And for this project, the Search is filtered for EPSON LW1000P Model. 28 //You can add more on ModuleFindPrinter.java file.29 const PrinterListEventListener = new NativeEventEmitter(NativeModules.FindPrinter);30 PrinterListEventListener.addListener('PrinterList', (event) => {31 console.log(event.List)32 this.setState({ printer_list: (JSON.parse(event.List)) })33 })34 this.discoverPrinter();35 this.printerStatus();36 }37 componentWillUnmount() {38 this.cancelSearch();39 }40 //Initialize printer search process41 discoverPrinter = async () => {42 FindPrinter.discover(43 (msg) => {44 console.log(msg);45 },46 );47 }48 //Send the index of the selected printer and the printer details are stored in the java side49 //Also terminates the search process.50 //This details will be available even after restarting the app.51 selectPrinter = async (index) => {52 FindPrinter.selectPrinter(index,53 (msg) => {54 console.log(msg);55 this.printerStatus();56 },57 )58 }59 //Terminates the printer Search process.60 cancelSearch = async () => {61 FindPrinter.cancelSearch(62 (msg) => {63 console.log(msg);64 },65 );66 }67 //Get the recently connected printer information68 printerStatus = async () => {69 PrinterStatus.getPrinterDetails(70 (name, host) => {71 console.log(name, host);72 if (name != "notAvailable") {73 this.setState({74 currentPrinter_name: name,75 currentPrinter_ip: host,76 currentPrinter_view: true,77 })78 PrinterStatus.getStatus(79 (status) => {80 this.setState({81 currentPrinter_status: status,82 })83 },84 )85 }86 },87 )88 }89 render() {90 return (91 <View style={{ backgroundColor: "#008abe", flex: 1 }}>92 <InnerHeader navigation={this.props.navigation}93 station=""94 user_role="" />95 <Text style={styles.Heading}>Printer Settings</Text>96 <Text style={styles.SubHeading}>Curent Printer</Text>97 {98 this.state.currentPrinter_view ?99 <>100 <Text style={styles.content}>Printer Name : {this.state.currentPrinter_name}</Text>101 <Text style={styles.content}>Printer Address : {this.state.currentPrinter_ip}</Text>102 <Text style={styles.content}>Printer Status : {this.state.currentPrinter_status}</Text>103 </>104 :105 <Text style={styles.content}>Not Connected to any Printer Yet</Text>106 }107 <View style={{ height: 30 }}></View>108 <Text style={styles.SubHeading}>Available Printers</Text>109 <View>110 {this.state.printer_list.length === 0 ?111 <Text style={styles.content}>No Printer Found</Text>112 :113 this.state.printer_list.map((item, index) => {114 console.log(item.data.name)115 return (116 <TouchableOpacity onPress={() => this.selectPrinter(item.index)}>117 <View style={styles.printerView}>118 <Text style={styles.content}>{item.data.name}</Text>119 <Text style={styles.content}>{item.data.host}</Text>120 </View>121 </TouchableOpacity>122 )123 })124 }125 </View>126 </View>127 );128 }129};130const styles = StyleSheet.create({131 Heading: {132 fontWeight: 'bold',133 fontSize: 30,134 textAlign: "center"135 },136 SubHeading: {137 fontWeight: 'bold',138 fontSize: 25,139 },140 content: {141 fontSize: 20,142 },143 printerView: {144 width: "100%",145 backgroundColor: "#e8e8e8",146 marginBottom: 5, padding: 15147 },148 btnView: {149 width: "40%",150 textAlign: "center"151 },152 button: {153 fontSize: 20,154 }155});...

Full Screen

Full Screen

thermal.js

Source:thermal.js Github

copy

Full Screen

1const ThermalPrinter = require("../node-thermal-printer").printer;2const PrinterTypes = require("../node-thermal-printer").types;3let printer = new ThermalPrinter({4 type: PrinterTypes.STAR, // Printer type: 'star' or 'epson'5 interface: 'tcp://xxx.xxx.xxx.xxx', // Printer interface6 characterSet: 'SLOVENIA', // Printer character set - default: SLOVENIA7 removeSpecialCharacters: false, // Removes special characters - default: false8 lineCharacter: "=", // Set character for lines - default: "-"9 options:{ // Additional options10 timeout: 5000 // Connection timeout (ms) [applicable only for network printers] - default: 300011 }12 });13 14 let isConnected = await printer.isPrinterConnected(); // Check if printer is connected, return bool of status15 let execute = await printer.execute(); // Executes all the commands. Returns success or throws error16 let raw = await printer.raw(Buffer.from("Hello world")); // Print instantly. Returns success or throws error17 printer.print("Hello World"); // Append text18 printer.println("Hello World"); // Append text with new line19 printer.openCashDrawer(); // Kick the cash drawer20 printer.cut(); // Cuts the paper (if printer only supports one mode use this)21 printer.partialCut(); // Cuts the paper leaving a small bridge in middle (if printer supports multiple cut modes)22 printer.beep(); // Sound internal beeper/buzzer (if available)23 printer.upsideDown(true); // Content is printed upside down (rotated 180 degrees)24 printer.setCharacterSet("SLOVENIA"); // Set character set - default set on init25 printer.setPrinterDriver(Object) // Set printer drive - default set on init26 27 printer.bold(true); // Set text bold28 printer.invert(true); // Background/text color inversion29 printer.underline(true); // Underline text (1 dot thickness)30 printer.underlineThick(true); // Underline text with thick line (2 dot thickness)31 printer.drawLine(); // Draws a line32 printer.newLine(); // Insers break line33 34 printer.alignCenter(); // Align text to center35 printer.alignLeft(); // Align text to left36 printer.alignRight(); // Align text to right37 38 printer.setTypeFontA(); // Set font type to A (default)39 printer.setTypeFontB(); // Set font type to B40 41 printer.setTextNormal(); // Set text to normal42 printer.setTextDoubleHeight(); // Set text to double height43 printer.setTextDoubleWidth(); // Set text to double width44 printer.setTextQuadArea(); // Set text to quad area45 printer.setTextSize(7,7); // Set text height (0-7) and width (0-7)46 47 printer.leftRight("Left", "Right"); // Prints text left and right48 printer.table(["One", "Two", "Three"]); // Prints table equaly49 printer.tableCustom([ // Prints table with custom settings (text, align, width, cols, bold)50 { text:"Left", align:"LEFT", width:0.5 },51 { text:"Center", align:"CENTER", width:0.25, bold:true },52 { text:"Right", align:"RIGHT", cols:8 }53 ]);54 55 printer.code128("Code128"); // Print code128 bar code56 printer.printQR("QR CODE"); // Print QR code57 await printer.printImage('./assets/olaii-logo-black.png'); // Print PNG image58 59 print.clear(); // Clears printText value60 print.getText(); // Returns printer buffer string value61 print.getBuffer(); // Returns printer buffer62 print.setBuffer(newBuffer); // Set the printer buffer to a copy of newBuffer...

Full Screen

Full Screen

printerAPI.js

Source:printerAPI.js Github

copy

Full Screen

1var path = require('path');2var fs = require("fs");3var printer = require("node-thermal-printer");4var bwipjs = require('bwip-js');5var dateFormat = require('dateformat');6/*7var barcode = require('barcode');8var code39 = barcode('ean13', {9 data: "123456789012",10 width: 400,11 height: 100,12});13*/14//var outfile = path.join('assets', 'imgs', 'mycode.png')15/*16var outfile = path.join('./assets', 'mycode.png');17code39.saveImage(outfile, function (err) {18 if (err) throw err;19 console.log('File has been written!');20});21*/22function PrinterEPSON() {23 printer.init({24 type: 'epson',25 characterSet: 'LATINA',26 removeSpecialCharacters: false,27 replaceSpecialCharacters: true,28 interface: '/dev/usb/lp0' //ESDPRT001 - /dev/usb/lp029 });30 printer.isPrinterConnected(function(exists){31 console.log("Printer connected? " + exists);32 if( exists ){33 printer.alignCenter();34 printer.println("Impressora pronta!");35 printer.partialCut();36 printer.execute(function(err){37 if (err) {38 console.error("Print failed", err);39 } else {40 console.log("Print done : isPrinterConnected");41 }42 });43 }44 });45}46PrinterEPSON.prototype.printCupom = function(rede, loja, id, qtdeGarrafa, barcode, bartype){47 var agora = new Date();48 printer.alignCenter();49 // printer.printImage('assets/ambev-black-400.png', function(done){50 // console.log("done: " + done);51 // printer.newLine();52 printer.bold(true);53 printer.setTextDoubleHeight();54 printer.setTextDoubleWidth();55 printer.println(rede);56 printer.println(loja);57 printer.bold(false);58 printer.setTextNormal();59 printer.newLine();60 printer.println("DEVOLUÇÃO DE VASILHAMES");61 printer.newLine();62 printer.alignLeft();63 printer.drawLine();64 // printer.newLine();65 printer.leftRight(dateFormat(agora, 'dd/mm/yyyy'), dateFormat(agora, 'HH:MM:ss'));66 // printer.newLine();67 printer.drawLine();68 printer.newLine();69 printer.alignCenter();70 printer.println(qtdeGarrafa + " x Cerveja GFA 300ML");71 printer.newLine();72 printer.alignCenter();73 printer.bold(true);74 printer.setTextDoubleHeight();75 printer.setTextDoubleWidth();76 printer.invert(true);77 printer.println(" " + qtdeGarrafa + " ");78 printer.invert(false);79 printer.bold(false);80 printer.setTextNormal();81 bwipjs.toBuffer({82 bcid: bartype, // Barcode type83 text: barcode, // Text to encode84 scale: 3, // 3x scaling factor85 height: 15, // Bar height, in millimeters86 includetext: true, // Show human-readable text87 textxalign: 'center', // Always good to set this88 // textfont: 'Inconsolata', // Use your custom font89 textsize: 10 // Font size, in points90 }, function (err, png) {91 if (err) {92 console.error("Write imagem barcode failed : ", err);93 } else {94 fs.writeFile("assets/mycode.png", png, function(err) {95 if(err) console.log(err);96 console.log("The file was saved!");97 printer.alignCenter();98 printer.printImage('assets/mycode.png', function(done){99 if(done) console.log(done);100 printer.newLine();101 printer.drawLine();102 // printer.newLine();103 printer.leftRight("Recibo", id);104 // printer.newLine();105 printer.drawLine();106 printer.bold(true);107 printer.setTextDoubleHeight();108 printer.setTextDoubleWidth();109 printer.print("VALIDO SOMENTE HOJE");110 printer.bold(false);111 printer.setTextNormal();112 printer.partialCut();113 printer.execute(function(err){114 if (err) {115 console.log("Print failed: ", err);116 } else {117 console.log("Print done : writeFile");118 }119 });120 });121 });122 }123 });124 // });125}126module.exports = PrinterEPSON;127/*128Teste unitario da API129var printerAPI = new PrinterEPSON();130printerAPI.printCupom("Garrafas Aprovadas!", '2343212234510');...

Full Screen

Full Screen

main.js

Source:main.js Github

copy

Full Screen

1printer = new Printer("Ultimaker-test01");2loadSettings(printer); //reads from localStorage using printer.name3if (!printer.id || !printer.key) {4 printer.register(function(data) {5 console.log('register cb',printer)6 saveSettings(printer);7 init();8 });9} else {10 init();11}12function init() {13 printer.connect("/"+printer.id,function(err,printerRootSocket) {14 console.log('connected',err,printerRootSocket)15 });16}17function loadSettings(printer) {18 var settings = JSON.parse(localStorage.getItem(printer.name)) || undefined;19 20 //decorate printer object with values from settings object21 for (var i in settings) {22 printer[i] = settings[i];23 }24}25function saveSettings(printer) {26 localStorage.setItem(printer.name,JSON.stringify(printer));27}28function removeSettings(printer) {29 localStorage.removeItem(printer.name);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { action } from '@storybook/addon-actions';4import { linkTo } from '@storybook/addon-links';5import { Button, Welcome } from '@storybook/react/demo';6import { print } from 'storybook-root';7storiesOf('Button', module)8 .add('with text', () => (9 <Button onClick={action('clicked')}>Hello Button</Button>10 .add('with some emoji', () => (11 <Button onClick={action('clicked')}>12 .add('with print', () => {13 print('print me');14 return (15 <Button onClick={action('clicked')}>Hello Button</Button>16 });17storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />);18import { configure } from '@storybook/react';19import './storybook-root';20const req = require.context('../src', true, /.stories.js$/);21function loadStories() {22 req.keys().forEach(filename => req(filename));23}24configure(loadStories, module);25import { addParameters } from '@storybook/react';26import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';27addParameters({28 viewport: {29 },30});31import { print } from 'storybook-root';32export default function() {33 print('Hello World');34}35const path = require('path');36module.exports = ({ config }) => {37 config.module.rules.push({38 loaders: [require.resolve('@storybook/source-loader')],39 });40 config.resolve.alias = {41 'storybook-root': path.resolve(__dirname, '../src/storybook-root.js'),42 };43 return config;44};45import { print } from 'storybook-root';46export default function() {47 print('Hello World');48}49{

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { action } from '@storybook/addon-actions';4import { Button } from '@storybook/react/demo';5storiesOf('Button', module)6 .add('with text', () => (7 <Button onClick={action('clicked')}>Hello Button</Button>8 .add('with some emoji', () => (9 <Button onClick={action('clicked')}>😀 😎 👍 💯</Button>10 ));11import React from 'react';12import { storiesOf } from '@storybook/react';13import { action } from '@storybook/addon-actions';14import { Button } from '@storybook/react/demo';15storiesOf('Button', module)16 .add('with text', () => (17 <Button onClick={action('clicked')}>Hello Button</Button>18 .add('with some emoji', () => (19 <Button onClick={action('clicked')}>😀 😎 👍 💯</Button>20 ));21import React from 'react';22import { storiesOf } from '@storybook/react';23import { action } from '@storybook/addon-actions';24import { Button } from '@storybook/react/demo';25storiesOf('Button1', module)26 .add('with text', () => (27 <Button onClick={action('clicked')}>Hello Button</Button>28 .add('with some emoji', () => (29 <Button onClick={action('clicked')}>😀 😎 👍 💯</Button>30 ));31import React from 'react';32import { storiesOf } from '@storybook/react';33import { action } from '@storybook/addon-actions';34import { Button } from '@storybook/react/demo';35storiesOf('Button2', module

Full Screen

Using AI Code Generation

copy

Full Screen

1import { printer } from 'storybook-root'2printer('Hello World')3import { printer } from 'storybook-root'4printer('Hello World')5import { printer } from 'storybook-root'6printer('Hello World')7import { printer } from 'storybook-root'8printer('Hello World')9import { printer } from 'storybook-root'10printer('Hello World')11import { printer } from 'storybook-root'12printer('Hello World')13import { printer } from 'storybook-root'14printer('Hello World')15import { printer } from 'storybook-root'16printer('Hello World')17import { printer } from 'storybook-root'18printer('Hello World')19import { printer } from 'storybook-root'20printer('Hello World')21import { printer } from 'storybook-root'22printer('Hello World')23import { printer } from 'storybook-root'24printer('Hello World')25import { printer } from 'storybook-root'26printer('Hello World')27import { printer } from 'storybook-root'28printer('Hello World')29import { printer } from 'storybook-root'30printer('Hello World')31import { printer } from 'storybook-root'32printer('Hello World')

Full Screen

Using AI Code Generation

copy

Full Screen

1import storybook from 'storybook-root';2storybook.printer('Hello World');3import storybook from 'storybook-root';4storybook.printer('Hello World');5import storybook from 'storybook-root';6storybook.printer('Hello World');7import storybook from 'storybook-root';8storybook.printer('Hello World');9import storybook from 'storybook-root';10storybook.printer('Hello World');11import storybook from 'storybook-root';12storybook.printer('Hello World');13import storybook from 'storybook-root';14storybook.printer('Hello World');15import storybook from 'storybook-root';16storybook.printer('Hello World');17import storybook from 'storybook-root';18storybook.printer('Hello World');19import storybook from 'storybook-root';20storybook.printer('Hello World');21import storybook from 'storybook-root';22storybook.printer('Hello World');23import storybook from 'storybook-root';24storybook.printer('Hello World');25import storybook from 'storybook-root';26storybook.printer('Hello World');27import storybook from 'storybook-root';28storybook.printer('Hello World');29import storybook from 'storybook-root

Full Screen

Using AI Code Generation

copy

Full Screen

1import { printer } from 'storybook-root';2console.log(printer());3module.exports = {4};5import { addDecorator } from '@storybook/react';6import { withRoot } from 'storybook-root';7addDecorator(withRoot);8const { resolve } = require('path');9const { withRoot } = require('storybook-root');10module.exports = async ({ config, mode }) => {11 const withRootConfig = withRoot({12 root: resolve(__dirname, '../'),13 });14 return withRootConfig;15};16.storybook-root {17 padding: 1rem;18}19module.exports = {20 webpackFinal: async (config) => {21 config.module.rules.push({22 include: path.resolve(__dirname, '../'),23 });24 return config;25 },26};

Full Screen

Using AI Code Generation

copy

Full Screen

1import { printer } from 'storybook-root'2printer('hello world')3import { printer } from 'storybook-root'4printer('hello world')5import { printer } from 'storybook-root'6printer('hello world')7import { printer } from 'storybook-root'8printer('hello world')9import { printer } from 'storybook-root'10printer('hello world')11import { printer } from 'storybook-root'12printer('hello world')13import { printer } from 'storybook-root'14printer('hello world')15import { printer } from 'storybook-root'16printer('hello world')17import { printer } from 'storybook-root'18printer('hello world')19import { printer } from 'storybook-root'20printer('hello world')21import { printer } from 'storybook-root'22printer('hello world')23import { printer } from 'storybook-root'24printer('hello world')25import { printer } from 'storybook-root'26printer('hello world')27import { printer } from 'storybook-root'28printer('hello world')29import { printer } from 'storybook-root'30printer('hello world')31import { printer } from 'storybook-root'32printer('hello world')33import { printer } from 'storybook-root'34printer('hello world')

Full Screen

Using AI Code Generation

copy

Full Screen

1import { printer } from 'storybook-root';2printer('Hello');3export function printer(msg) {4 console.log(msg);5}6const path = require('path');7const webpack = require('webpack');8module.exports = {9 output: {10 path: path.join(__dirname, 'dist'),11 },12 resolve: {13 alias: {14 'storybook-root': path.resolve(__dirname, '..', 'storybook-root')15 }16 },17 module: {18 {19 },20 {21 },22 {23 test: /\.(png|svg|jpg|gif)$/,24 },25 },26 new webpack.DefinePlugin({27 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),28 }),29};30{31 "scripts": {32 },33 "devDependencies": {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful