1.5.11 • Published 9 months ago

@happy-gastro/react-native-printer-module v1.5.11

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

React Native Printer BL and IP printer module

react-native-notification-badge GitHub követők

Native bridge for thermal printer, forked from react-native-thermal-printer with additional features.

Description

This module provides a bridge for printing on thermal printers using React Native. It supports both network and Bluetooth printing. We must added some editing into Java files to work well with Bluetooth and Hungarian characters and we will add some other features soon.

Android Only (Working on iOS)

This module bridges the following library: https://github.com/DantSu/ESCPOS-ThermalPrinter-Android/tree/3.0.1

Installation

npm @happy-gastro/install react-native-printer-module

or

yarn add @happy-gastro/react-native-printer-module

Android Manifest Configuration

Ensure the following permissions are added to android/app/src/main/AndroidManifest.xml:

For network printing:

<uses-permission android:name="android.permission.INTERNET"/>

For Bluetooth printing:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

Usage

Import the Module

import PrinterModule from 'react-native-printer-module';

Set Default Configuration

PrinterModule.defaultConfig.ip = '192.168.100.246';
PrinterModule.defaultConfig.port = 9100;
PrinterModule.defaultConfig.autoCut = false;
PrinterModule.defaultConfig.timeout = 30000; // in milliseconds

or

PrinterModule.defaultConfig = {
  ...PrinterModule.defaultConfig,
  ip: '192.168.100.246',
  port: 9100,
  autoCut: false,
  timeout: 30000, // in milliseconds
};

Sending a Print Job

// Inside an async function
try {
  await PrinterModule.printTcp({ payload: 'Hello, world!' });
} catch (err) {
  console.log(err.message);
}

You can also specify the configuration for each call:

// Inside an async function
try {
  await PrinterModule.printTcp({
    ip: '192.168.100.246',
    port: 9100,
    payload: 'Hello, world!',
    printerWidthMM: 50,
    timeout: 30000,
  });

  await PrinterModule.printTcp({
    ip: '192.168.100.247',
    port: 9100,
    payload: 'Hello, world!',
    autoCut: false,
    timeout: 30000,
  });
} catch (err) {
  console.log(err.message);
}

Bluetooth Printing

Pair your Bluetooth device and use the printBluetooth method. The configurations remain the same.

// Inside an async function
try {
  await PrinterModule.printBluetooth({
    payload: 'Hello, world!',
    printerNbrCharactersPerLine: 38,
  });
} catch (err) {
  console.log(err.message);
}

Methods

Supports both network and Bluetooth printing.

MethodParameterParameter TypeDefault
printTcpconfigPartial<PrintTcpInterface> & Pick<PrinterInterface, 'payload'>defaultConfig
printBluetoothconfigPartial<PrintBluetoothInterface> & Pick<PrinterInterface, 'payload'>defaultConfig

Interfaces and Configurations

// Default parameters
function PrinterInterface(payload, autoCut, openCashbox, mmFeedPaper, printerDpi, printerWidthMM, printerNbrCharactersPerLine) {
  this.payload = payload;
  this.autoCut = autoCut;
  this.openCashbox = openCashbox;
  this.mmFeedPaper = mmFeedPaper;
  this.printerDpi = printerDpi;
  this.printerWidthMM = printerWidthMM;
  this.printerNbrCharactersPerLine = printerNbrCharactersPerLine;
}

// Printing on TCP / IP printers
function PrintTcpInterface(ip, port, timeout, payload, autoCut, openCashbox, mmFeedPaper, printerDpi, printerWidthMM, printerNbrCharactersPerLine) {
  PrinterInterface.call(this, payload, autoCut, openCashbox, mmFeedPaper, printerDpi, printerWidthMM, printerNbrCharactersPerLine);
  this.ip = ip;
  this.port = port;
  this.timeout = timeout;
}

// Printing to Bluetooth printers
function PrintBluetoothInterface(macAddress, payload, autoCut, openCashbox, mmFeedPaper, printerDpi, printerWidthMM, printerNbrCharactersPerLine) {
  PrinterInterface.call(this, payload, autoCut, openCashbox, mmFeedPaper, printerDpi, printerWidthMM, printerNbrCharactersPerLine);
  this.macAddress = macAddress;
}

Default Configuration

const defaultConfig = {
  ip: '192.168.1.121',
  port: 9100,
  payload: '',
  autoCut: true,
  openCashbox: false,
  mmFeedPaper: 20,
  printerDpi: 203,
  printerWidthMM: 80,
  printerNbrCharactersPerLine: 42,
  timeout: 30000,
};

Available Config Options

NameTypeDefaultDescription
ipstring192.168.1.121Printer IP address
portnumber9100Printer port
payloadstring``Text sent to the printer
autoCutbooleantrueAutomatically cut the paper
openCashboxbooleanfalseOpen cashbox after printing
mmFeedPapernumber20Paper feed in millimeters
printerDpinumber203Printer DPI
printerWidthMMnumber80Printing width in millimeters
printerNbrCharactersPerLinenumber42Maximum characters per line
timeoutnumber30000Timeout duration in milliseconds

Example

const text =
  '[C]<img>https://via.placeholder.com/300.jpg</img>\n' +
  '[L]\n' +
  "[C]<u><font size='big'>ORDER #316-235</font></u>\n" +
  '[L]\n' +
  '[C]================================\n' +
  '[L]\n' +
  '[L]<b>PRODUCT NAME</b>[R]9.99€\n' +
  '[C]--------------------------------\n' +
  '[R]TOTAL PRICE :[R]34.98€\n' +
  '[R]TAX :[R]4.23€\n' +
  '[C]================================\n' +
  '[C]Thank You for beeing Our customer:\n' +
  '[C]Happy Solutions\n' +
  '[C]www.happysolutions.hu\n\n' +
  '[C]<barcode type="ean13" height="10">831254784551</barcode>\n' +
  '[C]<qrcode size="20">http://example.com/</qrcode>\n';

Tested Devices

  • Epson Printers
  • Bixolon Printers
  • SunMe Devices inner printers
  • iMin Devices inner printers
  • No-name Bluetooth printers
  • Zywell
  • VSC
  • EPPOS

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Author

This project is maintained by Farkas Ferenc.

Company

Happy Gastro Ltd.

License

MIT

JSONStreamabababort-controllerabsolute-pathacceptsacornacorn-globalsacorn-jsxacorn-walkadd-streamaggregate-errorajvanseransi-alignansi-colorsansi-cyanansi-escapesansi-fragmentsansi-grayansi-redansi-regexansi-stylesansi-wrapanymatchargparsearr-diffarr-flattenarr-unionarray-filterarray-find-indexarray-ifyarray-includesarray-maparray-reducearray-slicearray-unionarray-uniquearray.prototype.flatmaparrifyasapasn1assert-plusassign-symbolsastral-regexasyncasync-retryasynckitat-least-nodeatobaws-sign2aws4babel-eslintbabel-jestbabel-plugin-dynamic-import-nodebabel-plugin-istanbulbabel-plugin-jest-hoistbabel-plugin-polyfill-corejs2babel-plugin-polyfill-corejs3babel-plugin-polyfill-regeneratorbabel-plugin-syntax-trailing-function-commasbabel-preset-current-node-syntaxbabel-preset-fbjsbabel-preset-jestbalanced-matchbasebase64-jsbcrypt-pbkdfbefore-after-hookbig-integerbindingsblboxenbplist-creatorbplist-parserbrace-expansionbracesbrowser-process-hrtimebrowserslistbserbufferbuffer-crc32buffer-frombytescache-basecacheable-lookupcacheable-requestcall-bindcaller-callsitecaller-pathcallsitescamelcasecamelcase-keyscaniuse-litecapture-exitcaselesschalkchar-regexchardetci-infocjs-module-lexerclass-utilsclean-stackcli-boxescli-cursorcli-spinnerscli-widthcliuicloneclone-deepclone-responsecocollect-v8-coveragecollection-visitcolor-convertcolor-namecolor-supportcolorettecombined-streamcommand-existscommandercommondircompare-funccompare-versionscomponent-emittercompressiblecompressionconcat-mapconcat-streamconfigstoreconnectconventional-changelogconventional-changelog-angularconventional-changelog-atomconventional-changelog-codemirrorconventional-changelog-conventionalcommitsconventional-changelog-coreconventional-changelog-emberconventional-changelog-eslintconventional-changelog-expressconventional-changelog-jqueryconventional-changelog-jshintconventional-changelog-preset-loaderconventional-changelog-writerconventional-commits-filterconventional-commits-parserconventional-recommended-bumpconvert-source-mapcopy-descriptorcore-jscore-js-compatcore-util-iscosmiconfigcross-spawncrypto-random-stringcssomcssstylecsstypecurrently-unhandleddargsdashdashdata-urlsdateformatdayjsdebugdecamelizedecamelize-keysdecimal.jsdecode-uri-componentdecompress-responsededentdeep-extenddeep-isdeepmergedefaultsdefer-to-connectdefine-propertiesdefine-propertydeldelayed-streamdenodeifydepddeprecated-objdeprecationdestroydetect-newlinediff-sequencesdir-globdoctrinedomexceptiondot-propduplexer3ecc-jsbnee-firstelectron-to-chromiumemitteryemoji-regexencodeurlencodingend-of-streamenquirerenvinfoerror-exerror-stack-parsererrorhandleres-abstractes-to-primitiveescaladeescape-goatescape-htmlescape-string-regexpescodegeneslint-plugin-eslint-commentseslint-plugin-flowtypeeslint-plugin-jesteslint-plugin-reacteslint-plugin-react-hookseslint-plugin-react-nativeeslint-plugin-react-native-globalseslint-scopeeslint-utilseslint-visitor-keysespreeesprimaesqueryesrecurseestraverseesutilsetagevent-target-shimeventemitter3exec-shexecaexitexpand-bracketsexpectextendextend-shallowexternal-editorextglobextsprintffancy-logfast-deep-equalfast-difffast-globfast-json-stable-stringifyfast-levenshteinfastqfb-watchmanfbjsfbjs-css-varsfbjs-scriptsfiguresfile-entry-cachefile-uri-to-pathfill-rangefilter-objfinalhandlerfind-cache-dirfind-upfind-versionsflatflat-cacheflattedfor-inforever-agentform-datafragment-cachefreshfs-extrafs.realpathfseventsfunction-bindfunctional-red-black-treegensyncget-caller-fileget-intrinsicget-package-typeget-pkg-repoget-stdinget-streamget-valuegetpassgit-raw-commitsgit-remote-origin-urlgit-semver-tagsgit-upgit-url-parsegitconfiglocalglobglob-parentglobal-dirsglobalsglobbygotgraceful-fsgrowlyhandlebarshar-schemahar-validatorhard-rejectionhashas-bigintshas-flaghas-symbolshas-valuehas-valueshas-yarnhermes-enginehermes-profile-transformerhosted-git-infohtml-encoding-snifferhtml-escaperhttp-cache-semanticshttp-errorshttp-signaturehttp2-wrapperhuman-signalsiconv-liteieee754ignoreimage-sizeimport-cwdimport-freshimport-fromimport-lazyimport-localimurmurhashindent-stringinflightinheritsiniinquirerinternal-slotinterpretinvariantipis-absoluteis-accessor-descriptoris-arrayishis-bigintis-boolean-objectis-bufferis-callableis-ciis-core-moduleis-data-descriptoris-date-objectis-descriptoris-directoryis-dockeris-extendableis-extglobis-finiteis-fullwidth-code-pointis-generator-fnis-git-dirtyis-git-repositoryis-globis-installed-globallyis-interactiveis-negative-zerois-npmis-numberis-number-objectis-objis-path-cwdis-path-insideis-plain-objis-plain-objectis-potential-custom-element-nameis-regexis-relativeis-sshis-streamis-stringis-symbolis-text-pathis-typedarrayis-unc-pathis-unicode-supportedis-utf8is-windowsis-wslis-yarn-globalisarrayisexeisobjectisomorphic-fetchisstreamistanbul-lib-coverageistanbul-lib-instrumentistanbul-lib-reportistanbul-lib-source-mapsistanbul-reportsjest-changed-filesjest-clijest-configjest-diffjest-docblockjest-eachjest-environment-jsdomjest-environment-nodejest-get-typejest-haste-mapjest-jasmine2jest-leak-detectorjest-matcher-utilsjest-message-utiljest-mockjest-pnp-resolverjest-regex-utiljest-resolvejest-resolve-dependenciesjest-runnerjest-runtimejest-serializerjest-snapshotjest-utiljest-validatejest-watcherjest-workerjetifierjs-tokensjs-yamljsbnjsc-androidjsdomjsescjson-bufferjson-parse-better-errorsjson-parse-even-better-errorsjson-schemajson-schema-traversejson-stable-stringifyjson-stable-stringify-without-jsonifyjson-stringify-safejson5jsonfilejsonifyjsonparsejsprimjsx-ast-utilskeyvkind-ofklawkleurlatest-versionlevenlevnlines-and-columnsload-json-filelocate-pathlodashlodash.clonedeeplodash.debouncelodash.ismatchlodash.throttlelodash.truncatelog-symbolslogkittyloose-envifyloud-rejectionlowercase-keyslru-cachemacos-releasemake-dirmakeerrormap-cachemap-objmap-visitmeowmerge-streammerge2metrometro-babel-registermetro-babel-transformermetro-cachemetro-configmetro-coremetro-inspector-proxymetro-minify-uglifymetro-react-native-babel-presetmetro-react-native-babel-transformermetro-resolvermetro-source-mapmetro-symbolicatemicromatchmimemime-dbmime-typesmimic-fnmimic-responsemin-indentminimatchminimistminimist-optionsmixin-deepmkdirpmodify-valuesmsmute-streamnannanomatchnatural-comparenegotiatorneo-asyncnice-trynocachenode-fetchnode-int64node-modules-regexpnode-notifiernode-releasesnode-stream-zipnormalize-package-datanormalize-pathnormalize-urlnpm-run-pathnullthrowsnwsapioauth-signob1object-assignobject-copyobject-inspectobject-keysobject-visitobject.assignobject.entriesobject.fromentriesobject.pickobject.valueson-finishedon-headersonceonetimeopenopencollective-postinstalloptionatoroptionsoraos-nameos-tmpdirp-cancelablep-each-seriesp-finallyp-limitp-locatep-mapp-trypackage-jsonparent-moduleparse-github-repo-urlparse-jsonparse-node-versionparse-pathparse-urlparse5parseurlpascalcasepath-existspath-is-absolutepath-keypath-parsepath-typeperformance-nowpicomatchpifypinkiepinkie-promisepiratespkg-dirplease-upgrade-nodeplistplugin-errorposix-character-classesprelude-lsprepend-fileprepend-httpprettier-linter-helperspretty-formatprocess-nextick-argsprogresspromisepromptsprop-typesprotocolspseudomappslpumppunycodepupaqqsquery-stringqueue-microtaskquick-lrurange-parserrcreact-devtools-corereact-isreact-refreshread-pkgread-pkg-upreadable-streamrechoirredentregenerateregenerate-unicode-propertiesregenerator-runtimeregenerator-transformregex-notregexp.prototype.flagsregexppregexpu-coreregistry-auth-tokenregistry-urlregjsgenregjsparserremove-trailing-separatorrepeat-elementrepeat-stringrepeatingrequestrequest-promise-corerequest-promise-nativerequire-directoryrequire-from-stringrequire-main-filenameresolveresolve-alpnresolve-cwdresolve-fromresolve-globalresolve-urlresponselikerestore-cursorretretryreusifyrimrafrsvprun-asyncrun-parallelrx-literx-lite-aggregatesrxjssafe-buffersafe-regexsafer-buffersanesaxsaxesschedulersemversemver-comparesemver-diffsemver-regexsendserialize-errorserve-staticset-blockingset-valuesetimmediatesetprototypeofshallow-cloneshebang-commandshebang-regexshell-quoteshelljsshellwordsside-channelsignal-exitsimple-plistsisteransislashslice-ansisnapdragonsnapdragon-nodesnapdragon-utilsource-mapsource-map-resolvesource-map-supportsource-map-urlspdx-correctspdx-exceptionsspdx-expression-parsespdx-license-idssplitsplit-on-firstsplit-stringsplit2sprintf-jssshpkstack-utilsstackframestacktrace-parserstatic-extendstatusesstealthy-requirestream-buffersstrict-uri-encodestring-lengthstring-widthstring.prototype.matchallstring.prototype.trimendstring.prototype.trimstartstring_decoderstrip-ansistrip-bomstrip-eofstrip-final-newlinestrip-indentstrip-json-commentssudo-promptsupports-colorsupports-hyperlinkssymbol-treetabletemptemp-dirtemp-writeterminal-linktest-excludetext-extensionstext-tablethroatthroughthrough2time-stamptmptmplto-fast-propertiesto-object-pathto-readable-streamto-regexto-regex-rangetoidentifiertough-cookietr46trim-newlinestrim-off-newlinestslibtsutilstunnel-agenttweetnacltype-checktype-detecttype-festtypedarraytypedarray-to-bufferua-parser-jsuglify-esuglify-jsultronunbox-primitiveunc-path-regexunicode-canonical-property-names-ecmascriptunicode-match-property-ecmascriptunicode-match-property-value-ecmascriptunicode-property-aliases-ecmascriptunion-valueunique-stringuniversal-user-agentuniversalifyunpipeunset-valueupdate-notifieruri-jsurixurl-joinurl-parse-laxuseuse-subscriptionutil-deprecateutils-mergeuuidv8-compile-cachev8-to-istanbulvalidate-npm-package-licensevaryverrorvlqw3c-hr-timew3c-xmlserializerwalkerwcwidthwebidl-conversionswhatwg-encodingwhatwg-fetchwhatwg-mimetypewhatwg-urlwhichwhich-boxed-primitivewhich-modulewhich-pm-runswidest-linewindows-releaseword-wrapwordwrapwrap-ansiwrappywrite-file-atomicwsxcodexdg-basedirxml-name-validatorxmlbuilderxmlcharsxmldocxmldomxpipextendy18nyallistyamlyargsyargs-parseryocto-queue
1.5.11

9 months ago

1.5.10

9 months ago

1.5.9

9 months ago