recreate project
This commit is contained in:
+4
@@ -0,0 +1,4 @@
|
||||
service_name: travis-ci
|
||||
coverage_clover: build/logs/clover.xml
|
||||
json_path: build/logs/coveralls-upload.json
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Eclipse files
|
||||
.settings/*
|
||||
.project
|
||||
.buildpath
|
||||
|
||||
# doxygen files
|
||||
doc/html
|
||||
doc/latex
|
||||
doc/doxygen_sqlite3.db
|
||||
|
||||
# composer files
|
||||
vendor/
|
||||
|
||||
# other build files
|
||||
build/*
|
||||
*.phar
|
||||
Vendored
+40
@@ -0,0 +1,40 @@
|
||||
---
|
||||
dist: xenial
|
||||
sudo: required
|
||||
|
||||
language: php
|
||||
|
||||
php:
|
||||
- '7.3'
|
||||
- '7.4'
|
||||
- '8.0'
|
||||
- nightly
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- php: nightly
|
||||
|
||||
before_install:
|
||||
- sudo apt-get -qq update
|
||||
- sudo apt-get install -y imagemagick ghostscript unifont
|
||||
|
||||
install:
|
||||
- composer install
|
||||
|
||||
before_script:
|
||||
# Install 'imagick' plugin
|
||||
- bash -c 'if [[ $TRAVIS_PHP_VERSION != 8* ]] && [[ $TRAVIS_PHP_VERSION != "nightly" ]] ; then printf "\n" | pecl install imagick; fi'
|
||||
# Directory for coverage report
|
||||
- mkdir -p build/logs/
|
||||
|
||||
script:
|
||||
# Check code style
|
||||
- php vendor/bin/phpcs --standard=psr2 src/ -n
|
||||
# Run tests
|
||||
- php vendor/bin/phpunit --coverage-clover build/logs/clover.xml
|
||||
|
||||
after_success:
|
||||
# Upload coverage statistics to coveralls service after test
|
||||
- wget -c -nc https://github.com/satooshi/php-coveralls/releases/download/v1.0.1/coveralls.phar
|
||||
- php coveralls.phar -v
|
||||
...
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
# How to contribute
|
||||
|
||||
This project is open to many different types of contribution. You can help with improving the documentation and examples, sharing your insights on the issue tracker, adding fixes to the code, providing test cases, or just [writing about your hardware setup that you use](https://github.com/mike42/escpos-php/issues/new).
|
||||
|
||||
## Issue tracker
|
||||
|
||||
Open issues of all sorts are tracked on the [issue tracker](https://github.com/mike42/escpos-php/issues). Please check [the FAQ](https://github.com/mike42/escpos-php/blob/development/doc/FAQ.md) before you post, and practice good [bug tracker etiquette](https://bugzilla.mozilla.org/page.cgi?id=etiquette.html) to keep it running smoothly.
|
||||
|
||||
Issues are [loosely categorised](https://github.com/mike42/escpos-php/labels), and will stay open while there is still something that can be resolved.
|
||||
|
||||
Anybody may add to the discussion on the bug tracker. Just be sure to add new questions as separate issues, and to avoid commenting on closed issues.
|
||||
|
||||
## Submitting changes
|
||||
|
||||
Code changes may be submitted as a "[pull request](https://help.github.com/articles/about-pull-requests/)" at [mike42/escpos-php](https://github.com/mike42/escpos-php). The description should include some information about how the change improves the library.
|
||||
|
||||
The project is MIT-licensed (see [LICENSE.md](https://github.com/mike42/escpos-php/blob/development/LICENSE.md) for details). You are not required to assign copyright in order to submit changes, but you do need to agree for your code to be distributed under this license in order for it to be accepted.
|
||||
|
||||
### Documentation changes
|
||||
|
||||
The official documentaton is also located in the main repository, under the [doc/](https://github.com/mike42/escpos-php/tree/development/doc) folder.
|
||||
|
||||
You are welcome to post any suggested improvements as pull requests.
|
||||
|
||||
### Release process
|
||||
|
||||
Once a pull request is accepted, it usually appears in a release a few days later.
|
||||
|
||||
Branches:
|
||||
|
||||
- "development" is the most recent code, possibly containing unreleased fixes
|
||||
- "master" contains the most recently released code (old versions are not maintained).
|
||||
|
||||
The release process for your changes is:
|
||||
|
||||
- Changes are submitted via pull request to the shared "development" branch.
|
||||
- A new release is staged on the "master" branch via another pull request, and then tagged.
|
||||
|
||||
## Code style
|
||||
|
||||
This project uses the [PSR-2 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) for all PHP source code.
|
||||
|
||||
## Testing and CI
|
||||
|
||||
The tests are executed on [Travis CI](https://travis-ci.org/mike42/escpos-php) over PHP 5.4, 5.5, 5.6, 7.0, 7.1 and 7.2, plus the latest LTS version of HHVM, 3.21. Older versions of PHP are not supported in current releases.
|
||||
|
||||
For development, it's suggested that you load `imagick`, `gd` and `Xdebug` PHP exensions, and install `composer`.
|
||||
|
||||
Fetch a copy of this code and load dependencies with composer:
|
||||
|
||||
git clone https://github.com/mike42/escpos-php
|
||||
cd escpos-php/
|
||||
composer install
|
||||
|
||||
Execute unit tests via `phpunit`:
|
||||
|
||||
php vendor/bin/phpunit --coverage-text
|
||||
|
||||
Code style can be checked via [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer):
|
||||
|
||||
php vendor/bin/phpcs --standard=psr2 src/ -n
|
||||
|
||||
The developer docs are built with [doxygen](https://github.com/doxygen/doxygen). Re-build them to check for documentation warnings:
|
||||
|
||||
make -C doc clean && make -C doc
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
# escpos-php contributors
|
||||
|
||||
This file contains a list of people who have made contributions of
|
||||
code which appear in the public repository of escpos-php.
|
||||
|
||||
Main repository: [mike42/escpos-php](https://github.com/mike42/escpos-php) ([online contributor list](https://github.com/mike42/escpos-php/graphs/contributors))
|
||||
|
||||
- [Michael Billington](https://github.com/mike42)
|
||||
- [Alif Maulana El Fattah Nataly](https://github.com/alif25r)
|
||||
- [Mareks Sudniks](https://github.com/marech)
|
||||
- [matiasgaston](https://github.com/matiasgaston)
|
||||
- [Mike Stivala](https://github.com/brndwgn)
|
||||
- [Nicholas Long](https://github.com/longsview)
|
||||
- [Evandro Araújo](https://github.com/evsar3)
|
||||
|
||||
Via fork: [wdoyle/EpsonESCPOS-PHP](https://github.com/wdoyle/EpsonESCPOS-PHP):
|
||||
|
||||
- [Warren Doyle](https://github.com/wdoyle)
|
||||
|
||||
Via fork: [ronisaha/php-esc-pos](https://github.com/ronisaha/php-esc-pos):
|
||||
|
||||
- [Roni Saha](https://github.com/ronisaha)
|
||||
- [Gergely Radics](https://github.com/Gerifield)
|
||||
- [vharo](https://github.com/vharo)
|
||||
|
||||
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2014-2016 Michael Billington, incorporating modifications by others.
|
||||
See CONTRIBUTORS.md for a full list.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+575
@@ -0,0 +1,575 @@
|
||||
# ESC/POS Print Driver for PHP
|
||||
[](https://travis-ci.org/mike42/escpos-php) [](https://packagist.org/packages/mike42/escpos-php)
|
||||
[](https://packagist.org/packages/mike42/escpos-php)
|
||||
[](https://packagist.org/packages/mike42/escpos-php)
|
||||
[](https://coveralls.io/github/mike42/escpos-php?branch=development)
|
||||
|
||||
This project implements a subset of Epson's ESC/POS protocol for thermal receipt printers. It allows you to generate and print receipts with basic formatting, cutting, and barcodes on a compatible printer.
|
||||
|
||||
The library was developed to add drop-in support for receipt printing to any PHP app, including web-based point-of-sale (POS) applications.
|
||||
|
||||
## Compatibility
|
||||
|
||||
### Interfaces and operating systems
|
||||
This driver is known to work with the following OS/interface combinations:
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th> </th>
|
||||
<th>Linux</th>
|
||||
<th>Mac</th>
|
||||
<th>Windows</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Ethernet</th>
|
||||
<td><a href="https://github.com/mike42/escpos-php/tree/master/example/interface/ethernet.php">Yes</a></td>
|
||||
<td><a href="https://github.com/mike42/escpos-php/tree/master/example/interface/ethernet.php">Yes</a></td>
|
||||
<td><a href="https://github.com/mike42/escpos-php/tree/master/example/interface/ethernet.php">Yes</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>USB</th>
|
||||
<td><a href="https://github.com/mike42/escpos-php/tree/master/example/interface/linux-usb.php">Yes</a></td>
|
||||
<td>Not tested</td>
|
||||
<td><a href="https://github.com/mike42/escpos-php/tree/master/example/interface/windows-usb.php">Yes</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>USB-serial</th>
|
||||
<td>Yes</td>
|
||||
<td>Yes</td>
|
||||
<td>Yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Serial</th>
|
||||
<td>Yes</td>
|
||||
<td>Yes</td>
|
||||
<td>Yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Parallel</th>
|
||||
<td><a href="https://github.com/mike42/escpos-php/tree/master/example/interface/windows-lpt.php">Yes</a></td>
|
||||
<td>Not tested</td>
|
||||
<td>Yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>SMB shared</th>
|
||||
<td><a href="https://github.com/mike42/escpos-php/tree/master/example/interface/smb.php">Yes</a></td>
|
||||
<td>No</td>
|
||||
<td><a href="https://github.com/mike42/escpos-php/tree/master/example/interface/smb.php">Yes</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>CUPS hosted</th>
|
||||
<td><a href="https://github.com/mike42/escpos-php/tree/master/example/interface/cups.php">Yes</a></td>
|
||||
<td><a href="https://github.com/mike42/escpos-php/tree/master/example/interface/cups.php">Yes</a></td>
|
||||
<td>No</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
### Printers
|
||||
Many thermal receipt printers support ESC/POS to some degree. This driver has been known to work with:
|
||||
|
||||
- 3nStar RPT-008
|
||||
- Approx APPPOS80AM
|
||||
- AURES ODP-333
|
||||
- AURES ODP-500
|
||||
- Bematech-4200-TH
|
||||
- Bematech LR2000E
|
||||
- Birch PRP-085III
|
||||
- Bixolon SRP-350III
|
||||
- Bixolon SRP-350Plus
|
||||
- Black Copper BC-85AC
|
||||
- CHD TH-305N
|
||||
- Citizen CBM1000-II
|
||||
- Citizen CT-S310II
|
||||
- Dapper-Geyi Q583P
|
||||
- Daruma DR800
|
||||
- DR-MP200 (manufacturer unknown)
|
||||
- EPOS TEP 220M
|
||||
- Elgin i9
|
||||
- Epson EU-T332C
|
||||
- Epson FX-890 (requires `feedForm()` to release paper).
|
||||
- Epson TM-T20
|
||||
- Epson TM-T20II
|
||||
- Epson TM-T70
|
||||
- Epson TM-T70II
|
||||
- Epson TM-T81
|
||||
- Epson TM-T82II
|
||||
- Epson TM-T88II
|
||||
- Epson TM-T88III
|
||||
- Epson TM-T88IV
|
||||
- Epson TM-T88V
|
||||
- Epson TM-U220
|
||||
- Epson TM-U295 (requires `release()` to release slip).
|
||||
- Epson TM-U590 and TM-U590P
|
||||
- Equal (EQ-IT-001) POS-58
|
||||
- Everycom EC-58
|
||||
- Excelvan HOP-E200
|
||||
- Excelvan HOP-E58
|
||||
- Excelvan HOP-E801
|
||||
- Gainscha GP-2120TF
|
||||
- Gainscha GP-5890x (Also marketed as EC Line 5890x)
|
||||
- Gainscha GP-U80300I (Also marketed as gprinter GP-U80300I)
|
||||
- gprinter GP-U80160I
|
||||
- HOIN HOP-H58
|
||||
- Ithaca iTherm 28
|
||||
- Hasar HTP 250
|
||||
- Metapace T-1
|
||||
- Metapace T-25
|
||||
- Nexa PX700
|
||||
- Nyear NP100
|
||||
- OKI RT322
|
||||
- OKI 80 Plus III
|
||||
- Orient BTP-R580
|
||||
- P-822D
|
||||
- P85A-401 (make unknown)
|
||||
- Partner Tech RP320
|
||||
- POSLIGNE ODP200H-III-G
|
||||
- QPOS Q58M
|
||||
- Rongta RP326US
|
||||
- Rongta RP58-U
|
||||
- Rongta RP80USE
|
||||
- SAM4S GIANT-100DB
|
||||
- Senor TP-100
|
||||
- Sewoo SLK-TS400
|
||||
- SEYPOS PRP-96
|
||||
- SEYPOS PRP-300 (Also marketed as TYSSO PRP-300)
|
||||
- SNBC BTP-R880NPIII
|
||||
- Solux SX-TP-88300
|
||||
- Sicar POS-80
|
||||
- Silicon SP-201 / RP80USE
|
||||
- SPRT SP-POS88V
|
||||
- Star BSC10
|
||||
- Star TSP100 ECO
|
||||
- Star TSP100III FuturePRNT
|
||||
- Star TSP-650
|
||||
- Star TUP-592
|
||||
- TVS RP45 Shoppe
|
||||
- Venus V248T
|
||||
- Xeumior SM-8330
|
||||
- Xprinter F-900
|
||||
- Xprinter XP-365B
|
||||
- Xprinter XP-58 Series
|
||||
- Xprinter XP-80C
|
||||
- Xprinter XP-90
|
||||
- XPrinter XP-Q20011
|
||||
- Xprinter XP-Q800
|
||||
- Zjiang NT-58H
|
||||
- Zjiang ZJ-5870
|
||||
- Zjiang ZJ-5890 (Also sold as POS-5890 by many vendors; ZJ-5890K, ZJ-5890T also work).
|
||||
- Zjiang ZJ-8220 (Also marketed as Excelvan ZJ-8220)
|
||||
- Zjiang ZJ-8250
|
||||
|
||||
If you use any other printer with this code, please [let us know](https://github.com/mike42/escpos-php/issues/new) so that it can be added to the list.
|
||||
|
||||
## Basic usage
|
||||
|
||||
### Include the library
|
||||
|
||||
#### Composer
|
||||
|
||||
This library is designed for use with the `composer` PHP dependency manager. Simply add the `mike42/escpos-php` package to get started:
|
||||
|
||||
```bash
|
||||
composer require mike42/escpos-php
|
||||
```
|
||||
|
||||
If you haven't used `composer` before, you can read about it at [getcomposer.org](https://getcomposer.org/).
|
||||
|
||||
#### Requirements
|
||||
|
||||
This project has few hard dependencies:
|
||||
|
||||
- PHP 7.3 or newer.
|
||||
- `json` extension, used to load bundled printer definitions (see [documentation](https://www.php.net/manual/en/book.json.php))
|
||||
- `intl` extension, used for character encoding (see [documentation](https://www.php.net/manual/en/book.intl.php))
|
||||
- `zlib` extension, used for de-compressing bundled resources (see [documentation](https://www.php.net/manual/en/book.zlib.php)).
|
||||
|
||||
It is also suggested that you install either `imagick` or `gd`, as these can be used to speed up image processing.
|
||||
|
||||
A number of optional extensions can be added to enable more specific features. These
|
||||
are described in the "suggest" section of [composer.json](https://github.com/mike42/escpos-php/tree/master/composer.json).
|
||||
|
||||
### The 'Hello World' receipt
|
||||
|
||||
To make use of this driver, your server (where PHP is installed) must be able to communicate with your printer. Start by generating a simple receipt and sending it to your printer using the command-line.
|
||||
|
||||
```php
|
||||
<?php
|
||||
/* Call this file 'hello-world.php' */
|
||||
require __DIR__ . '/vendor/autoload.php';
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
use Mike42\Escpos\Printer;
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
$printer -> text("Hello World!\n");
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
```
|
||||
|
||||
Some examples are below for common interfaces.
|
||||
|
||||
Communicate with a printer with an Ethernet interface using `netcat`:
|
||||
|
||||
```bash
|
||||
php hello-world.php | nc 10.x.x.x. 9100
|
||||
```
|
||||
|
||||
A USB local printer connected with `usblp` on Linux has a device file (Includes USB-parallel interfaces):
|
||||
|
||||
```bash
|
||||
php hello-world.php > /dev/usb/lp0
|
||||
```
|
||||
|
||||
A computer installed into the local `cups` server is accessed through `lp` or `lpr`:
|
||||
|
||||
```bash
|
||||
php hello-world.php > foo.txt
|
||||
lpr -o raw -H localhost -P printer foo.txt
|
||||
```
|
||||
|
||||
A local or networked printer on a Windows computer is mapped in to a file, and generally requires you to share the printer first:
|
||||
|
||||
```
|
||||
php hello-world.php > foo.txt
|
||||
net use LPT1 \\server\printer
|
||||
copy foo.txt LPT1
|
||||
del foo.txt
|
||||
```
|
||||
|
||||
If you have troubles at this point, then you should consult your OS and printer system documentation to try to find a working print command.
|
||||
|
||||
### Using a PrintConnector
|
||||
|
||||
To print receipts from PHP, use the most applicable [PrintConnector](https://github.com/mike42/escpos-php/tree/master/src/Mike42/Escpos/PrintConnectors) for your setup. The connector simply provides the plumbing to get data to the printer.
|
||||
|
||||
For example, a `NetworkPrintConnector` accepts an IP address and port:
|
||||
|
||||
```php
|
||||
use Mike42\Escpos\PrintConnectors\NetworkPrintConnector;
|
||||
use Mike42\Escpos\Printer;
|
||||
$connector = new NetworkPrintConnector("10.x.x.x", 9100);
|
||||
$printer = new Printer($connector);
|
||||
try {
|
||||
// ... Print stuff
|
||||
} finally {
|
||||
$printer -> close();
|
||||
}
|
||||
```
|
||||
|
||||
While a serial printer might use:
|
||||
|
||||
```php
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
use Mike42\Escpos\Printer;
|
||||
$connector = new FilePrintConnector("/dev/ttyS0");
|
||||
$printer = new Printer($connector);
|
||||
```
|
||||
|
||||
For each OS/interface combination that's supported, there are examples in the compatibility section of how a `PrintConnector` would be constructed. If you can't get a `PrintConnector` to work, then be sure to include the working print command in your issue.
|
||||
|
||||
### Using a CapabilityProfile
|
||||
|
||||
Support for commands and code pages varies between printer vendors and models. By default, the driver will accept UTF-8, and output commands that are suitable for Epson TM-series printers.
|
||||
|
||||
When trying out a new brand of printer, it's a good idea to use the "simple" `CapabilityProfile`, which instructs the driver to avoid the use of advanced features (generally simpler image handling, ASCII-only text).
|
||||
|
||||
```php
|
||||
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
$profile = CapabilityProfile::load("simple");
|
||||
$connector = new WindowsPrintConnector("smb://computer/printer");
|
||||
$printer = new Printer($connector, $profile);
|
||||
```
|
||||
|
||||
As another example, Star-branded printers use different commands:
|
||||
|
||||
```php
|
||||
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
$profile = CapabilityProfile::load("SP2000")
|
||||
$connector = new WindowsPrintConnector("smb://computer/printer");
|
||||
$printer = new Printer($connector, $profile);
|
||||
```
|
||||
|
||||
For a list of available profiles, or to have support for your printer improved, please see the upstream [receipt-print-hq/escpos-printer-db](https://github.com/receipt-print-hq/escpos-printer-db) project.
|
||||
|
||||
### Tips & examples
|
||||
|
||||
On Linux, your printer device file will be somewhere like `/dev/lp0` (parallel), `/dev/usb/lp1` (USB), `/dev/ttyUSB0` (USB-Serial), `/dev/ttyS0` (serial).
|
||||
|
||||
On Windows, the device files will be along the lines of `LPT1` (parallel) or `COM1` (serial). Use the `WindowsPrintConnector` to tap into system printing on Windows (eg. [Windows USB](https://github.com/mike42/escpos-php/tree/master/example/interface/windows-usb.php), [SMB](https://github.com/mike42/escpos-php/tree/master/example/interface/smb.php) or [Windows LPT](https://github.com/mike42/escpos-php/tree/master/example/interface/windows-lpt.php)) - this submits print jobs via a queue rather than communicating directly with the printer.
|
||||
|
||||
A complete real-world receipt can be found in the code of [Auth](https://github.com/mike42/Auth) in [ReceiptPrinter.php](https://github.com/mike42/Auth/blob/master/lib/misc/ReceiptPrinter.php). It includes justification, boldness, and a barcode.
|
||||
|
||||
Other examples are located in the [example/](https://github.com/mike42/escpos-php/blob/master/example/) directory.
|
||||
|
||||
## Available methods
|
||||
|
||||
### __construct(PrintConnector $connector, CapabilityProfile $profile)
|
||||
Construct new print object.
|
||||
|
||||
Parameters:
|
||||
- `PrintConnector $connector`: The PrintConnector to send data to.
|
||||
- `CapabilityProfile $profile` Supported features of this printer. If not set, the "default" CapabilityProfile will be used, which is suitable for Epson printers.
|
||||
|
||||
See [example/interface/](https://github.com/mike42/escpos-php/tree/master/example/interface/) for ways to open connections for different platforms and interfaces.
|
||||
|
||||
### barcode($content, $type)
|
||||
Print a barcode.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `string $content`: The information to encode.
|
||||
- `int $type`: The barcode standard to output. If not specified, `Printer::BARCODE_CODE39` will be used.
|
||||
|
||||
Currently supported barcode standards are (depending on your printer):
|
||||
|
||||
- `BARCODE_UPCA`
|
||||
- `BARCODE_UPCE`
|
||||
- `BARCODE_JAN13`
|
||||
- `BARCODE_JAN8`
|
||||
- `BARCODE_CODE39`
|
||||
- `BARCODE_ITF`
|
||||
- `BARCODE_CODABAR`
|
||||
|
||||
Note that some barcode standards can only encode numbers, so attempting to print non-numeric codes with them may result in strange behaviour.
|
||||
|
||||
### bitImage(EscposImage $image, $size)
|
||||
See [graphics()](#graphicsescposimage-image-size) below.
|
||||
|
||||
### cut($mode, $lines)
|
||||
Cut the paper.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $mode`: Cut mode, either `Printer::CUT_FULL` or `Printer::CUT_PARTIAL`. If not specified, `Printer::CUT_FULL` will be used.
|
||||
- `int $lines`: Number of lines to feed before cutting. If not specified, 3 will be used.
|
||||
|
||||
### feed($lines)
|
||||
Print and feed line / Print and feed n lines.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $lines`: Number of lines to feed
|
||||
|
||||
### feedForm()
|
||||
Some printers require a form feed to release the paper. On most printers, this command is only useful in page mode, which is not implemented in this driver.
|
||||
|
||||
### feedReverse($lines)
|
||||
Print and reverse feed n lines.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $lines`: number of lines to feed. If not specified, 1 line will be fed.
|
||||
|
||||
### graphics(EscposImage $image, $size)
|
||||
Print an image to the printer.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `EscposImage $img`: The image to print.
|
||||
- `int $size`: Output size modifier for the image.
|
||||
|
||||
Size modifiers are:
|
||||
|
||||
- `IMG_DEFAULT` (leave image at original size)
|
||||
- `IMG_DOUBLE_WIDTH`
|
||||
- `IMG_DOUBLE_HEIGHT`
|
||||
|
||||
A minimal example:
|
||||
|
||||
```php
|
||||
<?php
|
||||
$img = EscposImage::load("logo.png");
|
||||
$printer -> graphics($img);
|
||||
```
|
||||
|
||||
See the [example/](https://github.com/mike42/escpos-php/blob/master/example/) folder for detailed examples.
|
||||
|
||||
The function [bitImage()](#bitimageescposimage-image-size) takes the same parameters, and can be used if your printer doesn't support the newer graphics commands. As an additional fallback, the `bitImageColumnFormat()` function is also provided.
|
||||
|
||||
### initialize()
|
||||
Initialize printer. This resets formatting back to the defaults.
|
||||
|
||||
### pdf417Code($content, $width, $heightMultiplier, $dataColumnCount, $ec, $options)
|
||||
Print a two-dimensional data code using the PDF417 standard.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `string $content`: Text or numbers to store in the code
|
||||
- `number $width`: Width of a module (pixel) in the printed code. Default is 3 dots.
|
||||
- `number $heightMultiplier`: Multiplier for height of a module. Default is 3 times the width.
|
||||
- `number $dataColumnCount`: Number of data columns to use. 0 (default) is to auto-calculate. Smaller numbers will result in a narrower code, making larger pixel sizes possible. Larger numbers require smaller pixel sizes.
|
||||
- `real $ec`: Error correction ratio, from 0.01 to 4.00. Default is 0.10 (10%).
|
||||
- `number $options`: Standard code `Printer::PDF417_STANDARD` with start/end bars, or truncated code `Printer::PDF417_TRUNCATED` with start bars only.
|
||||
|
||||
### pulse($pin, $on_ms, $off_ms)
|
||||
Generate a pulse, for opening a cash drawer if one is connected. The default settings (0, 120, 240) should open an Epson drawer.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $pin`: 0 or 1, for pin 2 or pin 5 kick-out connector respectively.
|
||||
- `int $on_ms`: pulse ON time, in milliseconds.
|
||||
- `int $off_ms`: pulse OFF time, in milliseconds.
|
||||
|
||||
### qrCode($content, $ec, $size, $model)
|
||||
Print the given data as a QR code on the printer.
|
||||
|
||||
- `string $content`: The content of the code. Numeric data will be more efficiently compacted.
|
||||
- `int $ec` Error-correction level to use. One of `Printer::QR_ECLEVEL_L` (default), `Printer::QR_ECLEVEL_M`, `Printer::QR_ECLEVEL_Q` or `Printer::QR_ECLEVEL_H`. Higher error correction results in a less compact code.
|
||||
- `int $size`: Pixel size to use. Must be 1-16 (default 3)
|
||||
- `int $model`: QR code model to use. Must be one of `Printer::QR_MODEL_1`, `Printer::QR_MODEL_2` (default) or `Printer::QR_MICRO` (not supported by all printers).
|
||||
|
||||
### selectPrintMode($mode)
|
||||
Select print mode(s).
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $mode`: The mode to use. Default is `Printer::MODE_FONT_A`, with no special formatting. This has a similar effect to running `initialize()`.
|
||||
|
||||
Several MODE_* constants can be OR'd together passed to this function's `$mode` argument. The valid modes are:
|
||||
|
||||
- `MODE_FONT_A`
|
||||
- `MODE_FONT_B`
|
||||
- `MODE_EMPHASIZED`
|
||||
- `MODE_DOUBLE_HEIGHT`
|
||||
- `MODE_DOUBLE_WIDTH`
|
||||
- `MODE_UNDERLINE`
|
||||
|
||||
### setBarcodeHeight($height)
|
||||
Set barcode height.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $height`: Height in dots. If not specified, 8 will be used.
|
||||
|
||||
### setBarcodeWidth($width)
|
||||
Set barcode bar width.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $width`: Bar width in dots. If not specified, 3 will be used. Values above 6 appear to have no effect.
|
||||
|
||||
### setColor($color)
|
||||
Select print color - on printers that support multiple colors.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $color`: Color to use. Must be either `Printer::COLOR_1` (default), or `Printer::COLOR_2`
|
||||
|
||||
### setDoubleStrike($on)
|
||||
Turn double-strike mode on/off.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `boolean $on`: true for double strike, false for no double strike.
|
||||
|
||||
### setEmphasis($on)
|
||||
Turn emphasized mode on/off.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `boolean $on`: true for emphasis, false for no emphasis.
|
||||
|
||||
### setFont($font)
|
||||
Select font. Most printers have two fonts (Fonts A and B), and some have a third (Font C).
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $font`: The font to use. Must be either `Printer::FONT_A`, `Printer::FONT_B`, or `Printer::FONT_C`.
|
||||
|
||||
### setJustification($justification)
|
||||
Select justification.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $justification`: One of `Printer::JUSTIFY_LEFT`, `Printer::JUSTIFY_CENTER`, or `Printer::JUSTIFY_RIGHT`.
|
||||
|
||||
### setLineSpacing($height)
|
||||
|
||||
Set the height of the line.
|
||||
|
||||
Some printers will allow you to overlap lines with a smaller line feed.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $height`: The height of each line, in dots. If not set, the printer will reset to its default line spacing.
|
||||
|
||||
### setPrintLeftMargin($margin)
|
||||
|
||||
Set print area left margin. Reset to default with `Printer::initialize()`.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $margin`: The left margin to set on to the print area, in dots.
|
||||
|
||||
### setPrintWidth($width)
|
||||
|
||||
Set print area width. This can be used to add a right margin to the print area. Reset to default with `Printer::initialize()`.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $width`: The width of the page print area, in dots.
|
||||
|
||||
### setReverseColors($on)
|
||||
Set black/white reverse mode on or off. In this mode, text is printed white on a black background.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `boolean $on`: True to enable, false to disable.
|
||||
|
||||
### setTextSize($widthMultiplier, $heightMultiplier)
|
||||
Set the size of text, as a multiple of the normal size.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $widthMultiplier`: Multiple of the regular height to use (range 1 - 8).
|
||||
- `int $heightMultiplier`: Multiple of the regular height to use (range 1 - 8).
|
||||
|
||||
### setUnderline($underline)
|
||||
Set underline for printed text.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `int $underline`: Either `true`/`false`, or one of `Printer::UNDERLINE_NONE`, `Printer::UNDERLINE_SINGLE` or `Printer::UNDERLINE_DOUBLE`. Defaults to `Printer::UNDERLINE_SINGLE`.
|
||||
|
||||
### text($str)
|
||||
Add text to the buffer. Text should either be followed by a line-break, or `feed()` should be called after this.
|
||||
|
||||
Parameters:
|
||||
|
||||
- `string $str`: The string to print.
|
||||
|
||||
# Further notes
|
||||
Posts I've written up for people who are learning how to use receipt printers:
|
||||
|
||||
* [What is ESC/POS, and how do I use it?](https://mike42.me/blog/what-is-escpos-and-how-do-i-use-it), which documents the output of `example/demo.php`.
|
||||
* [Setting up an Epson receipt printer](https://mike42.me/blog/2014-20-26-setting-up-an-epson-receipt-printer)
|
||||
* [Getting a USB receipt printer working on Linux](https://mike42.me/blog/2015-03-getting-a-usb-receipt-printer-working-on-linux)
|
||||
|
||||
# Development
|
||||
|
||||
This code is MIT licensed, and you are encouraged to contribute any modifications back to the project.
|
||||
|
||||
For development, it's suggested that you load `imagick`, `gd` and `Xdebug` PHP extensions.
|
||||
|
||||
The tests are executed on [Travis CI](https://travis-ci.org/mike42/escpos-php) over PHP 7.3, 7.4 and 8.0. Older versions of PHP are not supported in the current release, nor is HHVM.
|
||||
|
||||
Fetch a copy of this code and load dependencies with composer:
|
||||
|
||||
git clone https://github.com/mike42/escpos-php
|
||||
cd escpos-php/
|
||||
composer install
|
||||
|
||||
Execute unit tests via `phpunit`:
|
||||
|
||||
php vendor/bin/phpunit --coverage-text
|
||||
|
||||
This project uses the PSR-2 standard, which can be checked via [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer):
|
||||
|
||||
php vendor/bin/phpcs --standard=psr2 src/ -n
|
||||
|
||||
The developer docs are build with [doxygen](https://github.com/doxygen/doxygen). Re-build them to check for documentation warnings:
|
||||
|
||||
make -C doc clean && make -C doc
|
||||
|
||||
Pull requests and bug reports welcome.
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name" : "mike42/escpos-php",
|
||||
"type" : "library",
|
||||
"description" : "PHP receipt printer library for use with ESC/POS-compatible thermal and impact printers",
|
||||
"homepage" : "https://github.com/mike42/escpos-php",
|
||||
"keywords" : [
|
||||
"barcode",
|
||||
"epson",
|
||||
"receipt-printer",
|
||||
"printer",
|
||||
"escpos"
|
||||
],
|
||||
"license" : "MIT",
|
||||
"authors" : [{
|
||||
"name" : "Michael Billington",
|
||||
"email" : "michael.billington@gmail.com"
|
||||
}
|
||||
],
|
||||
"config": {
|
||||
"platform": {
|
||||
"php": "7.3.0"
|
||||
}
|
||||
},
|
||||
"require" : {
|
||||
"php" : ">=7.3.0",
|
||||
"ext-json": "*",
|
||||
"ext-intl": "*",
|
||||
"ext-zlib": "*",
|
||||
"mike42/gfx-php" : "^0.6"
|
||||
},
|
||||
"suggest" : {
|
||||
"ext-imagick" : "Will be used for image printing if present. Required for PDF printing or use of custom fonts.",
|
||||
"ext-gd" : "Used for image printing if present."
|
||||
},
|
||||
"require-dev" : {
|
||||
"phpunit/phpunit" : "^9",
|
||||
"squizlabs/php_codesniffer" : "^3.3"
|
||||
},
|
||||
"autoload" : {
|
||||
"psr-4" : {
|
||||
"Mike42\\" : "src/Mike42"
|
||||
}
|
||||
}
|
||||
}
|
||||
+2216
File diff suppressed because it is too large
Load Diff
Vendored
+142
@@ -0,0 +1,142 @@
|
||||
# Frequently Asked Questions (FAQ)
|
||||
|
||||
## Can I print to File Format X with this?
|
||||
|
||||
If you are trying to generate XPS, PDF or DOCX or HTML files from PHP, then you are most likely in the wrong place.
|
||||
|
||||
The purpose of this driver it to generate binary ESC/POS code, which is understood by many embedded thermal receipt and impact printers.
|
||||
|
||||
## I have Printer X. Can I use this driver?
|
||||
|
||||
If the printer understands ESC/POS, and you know how to get raw binary data to it, then yes. Otherwise, no.
|
||||
|
||||
The [list of printers that are known to work](https://github.com/mike42/escpos-php/blob/development/README.md#printers) is crowd-sourced. We appreciate it when developers try out the driver, then [file information on the bug tracker](https://github.com/mike42/escpos-php/issues/new) with some information about which features worked on their model of printer.
|
||||
|
||||
To see how well your printer works, first check that it supports ESC/POS, then begin by attempting to send the text "Hello World" to your printer on the command-line, from the computer that will run PHP.
|
||||
|
||||
Once you solve this, [try to do the same from PHP](https://github.com/mike42/escpos-php/blob/development/README.md#basic-usage) using the default profile. Further details are in the [README](https://github.com/mike42/escpos-php/blob/development/README.md) file.
|
||||
|
||||
## Can you add support for Printer X?
|
||||
|
||||
Features vary between printers, so we collaborate on an ESC/POS printer compatibility database to collect known differences: [receipt-print-hq/escpos-printer-db](https://github.com/receipt-print-hq/escpos-printer-db).
|
||||
|
||||
If you encounter garbage output when you try to print images or special characters, then please submit a test page and a link to vendor documentation to the `escpos-printer-db` project, so that support can be improved for future versions.
|
||||
|
||||
## I have a printer that does not understand ESC/POS. Can I use this driver?
|
||||
|
||||
No. The purpose of this driver it to generate binary ESC/POS code. If your printer doesn't understand that, then this code wont be much use to you.
|
||||
|
||||
Some printers do have an emulation mode for ESC/POS. The vendor docs will tell if this is the case, and how to enable it.
|
||||
|
||||
## Why do I get this error when I try to print?
|
||||
|
||||
Start by testing that you can send text to your printer outside of escpos-php. The examples linked to in the README are commented with some commands to get you started.
|
||||
|
||||
Generally, initial setup problems seem to have one of these causes:
|
||||
|
||||
1. You are writing to the wrong place. Writing to `LPT1` does not output to parallel port on Linux, and `/dev/ttyS0` is not a serial printer on Windows.
|
||||
2. The printer has not been set up to accept printing the way you expect. This means permissions on Linux, network printers being configured, and shared printers having user accounts and firewalls set up correctly on the print server.
|
||||
3. Your printer actually doesn't work (rare but possible).
|
||||
|
||||
To be clear, these are not escpos-php issues: No amount of PHP code can set up your printer for you. Instead, the driver relies on developers determining how their setup is going to work before using a connector to transport data to their printer.
|
||||
|
||||
Once you have a working command to send text to your printer (from the PHP server), you are ready to use escpos-php. You can try to use a PrintConnector now, based on your operating system and printer interface. A table is located in the README to help you select the right one.
|
||||
|
||||
The connectors are-
|
||||
|
||||
- `FilePrintConnector` and `NetworkPrintConnector` directly use files or network sockets.
|
||||
- `WindowsPrintConnector` and `CupsPrintConnector` tie in with Windows and Unix system printing.
|
||||
- `DummyPrintConnector` does not connect to a real printer, and can be used to save ESC/POS receipts to a database, for example.
|
||||
|
||||
At this point, you might find that the way you would like to print is not supported by escpos-php. You can post your printing command as a feature request on the issue tracker.
|
||||
|
||||
Lastly, you may run in to the final common trap:
|
||||
|
||||
4. Your PHP is not running with the same sort of permissions as your login account. Again, no amount of PHP code can fix this. For example, on LAMP, your `www-data` user needs to be in the `lp` group, while on WAMP, `Local Service` account may run in to problems. SELinux and firewalls are also worth a look.
|
||||
|
||||
When printing fails, you can expect a PHP Exception that explains what went wrong. They are all clues:
|
||||
|
||||
- `Warning: copy(\\pc\printer): failed to open stream: Permission denied`
|
||||
- `/dev/usb/lp0: Permission denied`
|
||||
- `User name or password is incorrect`
|
||||
|
||||
Ensure that while you are developing, you configure PHP to show error messages, so that you can see these problems.
|
||||
|
||||
Please file a bug if you think that there is a specific situation which escpos-php could provide better error messages for.
|
||||
|
||||
## Can I print over the network?
|
||||
|
||||
Certainly, as long as your printer is available over the network.
|
||||
|
||||
- `NetworkPrintConnector` will speak directly to an Ethernet-connected printer on port 9100.
|
||||
|
||||
For USB or Serial printers, you need to install the printer on a computer and then share it, so that it becomes network-accessible.
|
||||
|
||||
- `WindowsPrintConnector` will connect to Windows shared printers from Windows or Linux (Linux users will need Samba).
|
||||
- `CupsPrintConnector` will connect to CUPS-shared printers from Linux or Mac.
|
||||
|
||||
Always start by testing your shared printer setup outside of escpos-php. The examples linked to in the README are commented with some example commands to get you started. Typically, networks, firewalls and permissions need to be set up.
|
||||
|
||||
Once you have a working command to send text to your printer (from the PHP server), you are ready to use escpos-php.
|
||||
|
||||
If you have any issues at this stage, please ask on the issue tracker, and include the commands that you used to verify your setup.
|
||||
|
||||
## Can I print from my server on the Internet?
|
||||
|
||||
Since PHP is a server-side language, escpos-php is a server-side print library. The driver is able to transport data between a server and a printer in a few different ways, all of them server-side. For example, you may print to a USB printer *connected to the server running PHP*, or an Ethernet printer *on a network accessible to the server*.
|
||||
|
||||
Many developers dream of having an application that is hosted on the public Internet, with POS terminals accessing it, and printing via a web browser. Because the webserver cannot see the printer in this sort of setup, a server-side print driver is not much use.
|
||||
|
||||
Because of this, there are no cut-and-paste recipes available, but here are two top-level approaches you could take:
|
||||
|
||||
1. Architect your application so that the server can see your printer
|
||||
2. Use an application which runs client-side to deliver print data instead
|
||||
|
||||
### Option 1: Allow the server to print
|
||||
|
||||
Server-side printing is viable if the server can get to the printer. Here are some ways it could work:
|
||||
|
||||
- Run your server on the LAN instead, and read the section above about printing over the network
|
||||
- Set up a VPN so that your cloud-hosted server can also access the LAN
|
||||
- Expose the printer via some other secure tunnel to the server, via SSH or TLS
|
||||
|
||||
Please do your own research to determine how these may apply to your setup- the escpos-php issue tracker is not a place where you should be requesting network support.
|
||||
|
||||
### Option 2: Use client software to print
|
||||
|
||||
If you aren't able to set up some network infrastructure to implement the above, then you cannot use a server-side print driver.
|
||||
|
||||
Here are some browser-based printing tools which you may like to consider instead.
|
||||
|
||||
- Use system printing with a vendor driver, and some good `@media print` CSS
|
||||
- [Chrome Raw Print](https://github.com/receipt-print-hq/chrome-raw-print) app
|
||||
- [qz](https://qz.io/)
|
||||
- [ePOS-Device SDK for JavaScript](https://reference.epson-biz.com/modules/ref_epos_device_js_en/index.php?content_id=139). Requires network interface card that supports ePOS (UB-E04/R04)
|
||||
|
||||
Please direct queries about client-side printing products to the appropriate project.
|
||||
|
||||
## Why is image printing slow?
|
||||
|
||||
Three things tend to slow down the image processing:
|
||||
|
||||
1. Slow PHP code
|
||||
2. Data link
|
||||
3. The printer itself
|
||||
|
||||
First, ensure you have the Imagick plugin loaded. The driver will avoid a slower image processing implementation once you've got it.
|
||||
|
||||
Next, connect over a faster interface. Serial printers have a low bit-rate, and the printer spends a lot of time waiting for data. If you have USB or Ethernet, then use it (note: storing graphics to the printer memory is not currently implemented).
|
||||
|
||||
Lastly, the printer will go faster if you use less pixels. Since images are two-dimensional, scaling down by 50% removes 75% of the pixels. The driver can then print at a half the density, so that your lower resolution image appears the same size when printed.
|
||||
|
||||
## How can I get the status of the printer?
|
||||
|
||||
This feature is not implemented, but a solution for some Epson printers is planned.
|
||||
|
||||
Only `FilePrintConnector` or `NetworkPrintConnector` will support reading from the printer, ensure that you migrate to those if you would like these features.
|
||||
|
||||
## How do I produce this complex layout?
|
||||
|
||||
ESC/POS "page mode" is not currently supported, which would allow some printers to render some more complex layouts natively
|
||||
|
||||
Since the output is raster anyway, it is suggested that you render your output to an image and print that instead. The driver supports PDF printing via Imagick, and an example that uses `wkhtmltoimage` is available in the repository.
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
html: escpos.doxyfile
|
||||
# Compile
|
||||
doxygen escpos.doxyfile
|
||||
# Filter out warnings on README.md- doxygen cannot handle image links that
|
||||
# are used there: [](https://example.com/image)
|
||||
sed -i '/README.md\:/d' warnings.log
|
||||
# Show warnings log
|
||||
cat warnings.log
|
||||
# Return failure if there were any doc warnings
|
||||
[ ! -s warnings.log ]
|
||||
|
||||
latex: html
|
||||
# Do nothing
|
||||
|
||||
xml: html
|
||||
xsltproc xml/combine.xslt xml/index.xml > all.xml
|
||||
|
||||
clean:
|
||||
rm --preserve-root -Rf html latex xml doxygen_sqlite3.db all.xml warnings.log
|
||||
|
||||
+2352
File diff suppressed because it is too large
Load Diff
+26
@@ -0,0 +1,26 @@
|
||||
Examples
|
||||
--------
|
||||
|
||||
This folder contains a collectoion of feature examples.
|
||||
Generally, demo.php is the fastest way to find out which features your
|
||||
printer supports.
|
||||
|
||||
## Subfolders
|
||||
- `interface/` - contains examples for output interfaces: eg, parallel, serial, USB, network, file-based.
|
||||
- `specific/` - examples made in response to issues & questions. These cover specific languages, printers and interfaces, so hit narrower use cases.
|
||||
|
||||
## List of examples
|
||||
|
||||
Each example prints to standard output, so either edit the print connector, or redirect the output to your printer to see it in action. They are designed for developers: open them in a text editor before you run them!
|
||||
|
||||
- `bit-image.php` - Prints a images to the printer using the older "bit image" commands.
|
||||
- `demo.php` - Demonstrates output using a large subset of availale features.
|
||||
- `qr-code.php` - Prints QR codes, if your printer supports it.
|
||||
- `character-encodings.php` - Shows available character encodings. Change from the DefaultCapabilityProfile to get more useful output for your specific printer.
|
||||
- `graphics.php` - The same output as `bit-image.php`, printed with the newer graphics commands (not supported on many non-Epson printers)
|
||||
- `receipt-with-logo.php` - A simple receipt containing a logo and basic formating.
|
||||
- `character-encodings-with-images.php` - The same as `character-encodings.php`, but also prints each string using an `ImagePrintBuffer`, showing compatibility gaps.
|
||||
- `print-from-html.php` - Runs `wkhtmltoimage` to convert HTML to an image, and then prints the image. (This is very slow)
|
||||
- `character-tables.php` - Prints a compact character code table for each available character set. Used to debug incorrect output from `character-encodings.php`.
|
||||
- `print-from-pdf.php` - Loads a PDF and prints each page in a few different ways (very slow as well)
|
||||
- `rawbt-receipt` (.php & .html) - Demonstration of Back and Front for integration between the site and the Android application “RawBT - Printer Driver for Android”
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
|
||||
/* Height and width */
|
||||
$printer->selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
|
||||
$printer->text("Height and bar width\n");
|
||||
$printer->selectPrintMode();
|
||||
$heights = array(1, 2, 4, 8, 16, 32);
|
||||
$widths = array(1, 2, 3, 4, 5, 6, 7, 8);
|
||||
$printer -> text("Default look\n");
|
||||
$printer->barcode("ABC", Printer::BARCODE_CODE39);
|
||||
|
||||
foreach($heights as $height) {
|
||||
$printer -> text("\nHeight $height\n");
|
||||
$printer->setBarcodeHeight($height);
|
||||
$printer->barcode("ABC", Printer::BARCODE_CODE39);
|
||||
}
|
||||
foreach($widths as $width) {
|
||||
$printer -> text("\nWidth $width\n");
|
||||
$printer->setBarcodeWidth($width);
|
||||
$printer->barcode("ABC", Printer::BARCODE_CODE39);
|
||||
}
|
||||
$printer->feed();
|
||||
// Set to something sensible for the rest of the examples
|
||||
$printer->setBarcodeHeight(40);
|
||||
$printer->setBarcodeWidth(2);
|
||||
|
||||
/* Text position */
|
||||
$printer->selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
|
||||
$printer->text("Text position\n");
|
||||
$printer->selectPrintMode();
|
||||
$hri = array (
|
||||
Printer::BARCODE_TEXT_NONE => "No text",
|
||||
Printer::BARCODE_TEXT_ABOVE => "Above",
|
||||
Printer::BARCODE_TEXT_BELOW => "Below",
|
||||
Printer::BARCODE_TEXT_ABOVE | Printer::BARCODE_TEXT_BELOW => "Both"
|
||||
);
|
||||
foreach ($hri as $position => $caption) {
|
||||
$printer->text($caption . "\n");
|
||||
$printer->setBarcodeTextPosition($position);
|
||||
$printer->barcode("012345678901", Printer::BARCODE_JAN13);
|
||||
$printer->feed();
|
||||
}
|
||||
|
||||
/* Barcode types */
|
||||
$standards = array (
|
||||
Printer::BARCODE_UPCA => array (
|
||||
"title" => "UPC-A",
|
||||
"caption" => "Fixed-length numeric product barcodes.",
|
||||
"example" => array (
|
||||
array (
|
||||
"caption" => "12 char numeric including (wrong) check digit.",
|
||||
"content" => "012345678901"
|
||||
),
|
||||
array (
|
||||
"caption" => "Send 11 chars to add check digit automatically.",
|
||||
"content" => "01234567890"
|
||||
)
|
||||
)
|
||||
),
|
||||
Printer::BARCODE_UPCE => array (
|
||||
"title" => "UPC-E",
|
||||
"caption" => "Fixed-length numeric compact product barcodes.",
|
||||
"example" => array (
|
||||
array (
|
||||
"caption" => "6 char numeric - auto check digit & NSC",
|
||||
"content" => "123456"
|
||||
),
|
||||
array (
|
||||
"caption" => "7 char numeric - auto check digit",
|
||||
"content" => "0123456"
|
||||
),
|
||||
array (
|
||||
"caption" => "8 char numeric",
|
||||
"content" => "01234567"
|
||||
),
|
||||
array (
|
||||
"caption" => "11 char numeric - auto check digit",
|
||||
"content" => "01234567890"
|
||||
),
|
||||
array (
|
||||
"caption" => "12 char numeric including (wrong) check digit",
|
||||
"content" => "012345678901"
|
||||
)
|
||||
)
|
||||
),
|
||||
Printer::BARCODE_JAN13 => array (
|
||||
"title" => "JAN13/EAN13",
|
||||
"caption" => "Fixed-length numeric barcodes.",
|
||||
"example" => array (
|
||||
array (
|
||||
"caption" => "12 char numeric - auto check digit",
|
||||
"content" => "012345678901"
|
||||
),
|
||||
array (
|
||||
"caption" => "13 char numeric including (wrong) check digit",
|
||||
"content" => "0123456789012"
|
||||
)
|
||||
)
|
||||
),
|
||||
Printer::BARCODE_JAN8 => array (
|
||||
"title" => "JAN8/EAN8",
|
||||
"caption" => "Fixed-length numeric barcodes.",
|
||||
"example" => array (
|
||||
array (
|
||||
"caption" => "7 char numeric - auto check digit",
|
||||
"content" => "0123456"
|
||||
),
|
||||
array (
|
||||
"caption" => "8 char numeric including (wrong) check digit",
|
||||
"content" => "01234567"
|
||||
)
|
||||
)
|
||||
),
|
||||
Printer::BARCODE_CODE39 => array (
|
||||
"title" => "Code39",
|
||||
"caption" => "Variable length alphanumeric w/ some special chars.",
|
||||
"example" => array (
|
||||
array (
|
||||
"caption" => "Text, numbers, spaces",
|
||||
"content" => "ABC 012"
|
||||
),
|
||||
array (
|
||||
"caption" => "Special characters",
|
||||
"content" => "$%+-./"
|
||||
),
|
||||
array (
|
||||
"caption" => "Extra char (*) Used as start/stop",
|
||||
"content" => "*TEXT*"
|
||||
)
|
||||
)
|
||||
),
|
||||
Printer::BARCODE_ITF => array (
|
||||
"title" => "ITF",
|
||||
"caption" => "Variable length numeric w/even number of digits,\nas they are encoded in pairs.",
|
||||
"example" => array (
|
||||
array (
|
||||
"caption" => "Numeric- even number of digits",
|
||||
"content" => "0123456789"
|
||||
)
|
||||
)
|
||||
),
|
||||
Printer::BARCODE_CODABAR => array (
|
||||
"title" => "Codabar",
|
||||
"caption" => "Varaible length numeric with some allowable\nextra characters. ABCD/abcd must be used as\nstart/stop characters (one at the start, one\nat the end) to distinguish between barcode\napplications.",
|
||||
"example" => array (
|
||||
array (
|
||||
"caption" => "Numeric w/ A A start/stop. ",
|
||||
"content" => "A012345A"
|
||||
),
|
||||
array (
|
||||
"caption" => "Extra allowable characters",
|
||||
"content" => "A012$+-./:A"
|
||||
)
|
||||
)
|
||||
),
|
||||
Printer::BARCODE_CODE93 => array (
|
||||
"title" => "Code93",
|
||||
"caption" => "Variable length- any ASCII is available",
|
||||
"example" => array (
|
||||
array (
|
||||
"caption" => "Text",
|
||||
"content" => "012abcd"
|
||||
)
|
||||
)
|
||||
),
|
||||
Printer::BARCODE_CODE128 => array (
|
||||
"title" => "Code128",
|
||||
"caption" => "Variable length- any ASCII is available",
|
||||
"example" => array (
|
||||
array (
|
||||
"caption" => "Code set A uppercase & symbols",
|
||||
"content" => "{A" . "012ABCD"
|
||||
),
|
||||
array (
|
||||
"caption" => "Code set B general text",
|
||||
"content" => "{B" . "012ABCDabcd"
|
||||
),
|
||||
array (
|
||||
"caption" => "Code set C compact numbers\n Sending chr(21) chr(32) chr(43)",
|
||||
"content" => "{C" . chr(21) . chr(32) . chr(43)
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
$printer->setBarcodeTextPosition(Printer::BARCODE_TEXT_BELOW);
|
||||
foreach ($standards as $type => $standard) {
|
||||
$printer->selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
|
||||
$printer->text($standard ["title"] . "\n");
|
||||
$printer->selectPrintMode();
|
||||
$printer->text($standard ["caption"] . "\n\n");
|
||||
foreach ($standard ["example"] as $id => $barcode) {
|
||||
$printer->setEmphasis(true);
|
||||
$printer->text($barcode ["caption"] . "\n");
|
||||
$printer->setEmphasis(false);
|
||||
$printer->text("Content: " . $barcode ["content"] . "\n");
|
||||
$printer->barcode($barcode ["content"], $type);
|
||||
$printer->feed();
|
||||
}
|
||||
}
|
||||
$printer->cut();
|
||||
$printer->close();
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
/* Example print-outs using the older bit image print command */
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\EscposImage;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
|
||||
try {
|
||||
$tux = EscposImage::load("resources/tux.png", false);
|
||||
|
||||
$printer -> text("These example images are printed with the older\nbit image print command. You should only use\n\$p -> bitImage() if \$p -> graphics() does not\nwork on your printer.\n\n");
|
||||
|
||||
$printer -> bitImage($tux);
|
||||
$printer -> text("Regular Tux (bit image).\n");
|
||||
$printer -> feed();
|
||||
|
||||
$printer -> bitImage($tux, Printer::IMG_DOUBLE_WIDTH);
|
||||
$printer -> text("Wide Tux (bit image).\n");
|
||||
$printer -> feed();
|
||||
|
||||
$printer -> bitImage($tux, Printer::IMG_DOUBLE_HEIGHT);
|
||||
$printer -> text("Tall Tux (bit image).\n");
|
||||
$printer -> feed();
|
||||
|
||||
$printer -> bitImage($tux, Printer::IMG_DOUBLE_WIDTH | Printer::IMG_DOUBLE_HEIGHT);
|
||||
$printer -> text("Large Tux in correct proportion (bit image).\n");
|
||||
} catch (Exception $e) {
|
||||
/* Images not supported on your PHP, or image file not found */
|
||||
$printer -> text($e -> getMessage() . "\n");
|
||||
}
|
||||
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
/* Change to the correct path if you copy this example! */
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
use Mike42\Escpos\PrintBuffers\EscposPrintBuffer;
|
||||
use Mike42\Escpos\PrintBuffers\ImagePrintBuffer;
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
|
||||
/**
|
||||
* This example builds on character-encodings.php, also providing an image-based rendering.
|
||||
* This is quite slow, since a) the buffers are changed dozens of
|
||||
* times in the example, and b) It involves sending very wide images, which printers don't like!
|
||||
*
|
||||
* There are currently no test cases around the image printing, since it is an experimental feature.
|
||||
*
|
||||
* It does, however, illustrate the way that more encodings are available when image output is used.
|
||||
*/
|
||||
include(dirname(__FILE__) . '/resources/character-encoding-test-strings.inc');
|
||||
|
||||
try {
|
||||
// Enter connector and capability profile
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$profile = CapabilityProfile::load('default');
|
||||
$buffers = array(new EscposPrintBuffer(), new ImagePrintBuffer());
|
||||
|
||||
/* Print a series of receipts containing i18n example strings */
|
||||
$printer = new Printer($connector, $profile);
|
||||
$printer -> selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_EMPHASIZED | Printer::MODE_DOUBLE_WIDTH);
|
||||
$printer -> text("Implemented languages\n");
|
||||
$printer -> selectPrintMode();
|
||||
foreach ($inputsOk as $label => $str) {
|
||||
$printer -> setEmphasis(true);
|
||||
$printer -> text($label . ":\n");
|
||||
$printer -> setEmphasis(false);
|
||||
foreach ($buffers as $buffer) {
|
||||
$printer -> setPrintBuffer($buffer);
|
||||
$printer -> text($str);
|
||||
}
|
||||
$printer -> setPrintBuffer($buffers[0]);
|
||||
}
|
||||
$printer -> feed();
|
||||
|
||||
$printer -> selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_EMPHASIZED | Printer::MODE_DOUBLE_WIDTH);
|
||||
$printer -> text("Works in progress\n");
|
||||
$printer -> selectPrintMode();
|
||||
foreach ($inputsNotOk as $label => $str) {
|
||||
$printer -> setEmphasis(true);
|
||||
$printer -> text($label . ":\n");
|
||||
$printer -> setEmphasis(false);
|
||||
foreach ($buffers as $buffer) {
|
||||
$printer -> setPrintBuffer($buffer);
|
||||
$printer -> text($str);
|
||||
}
|
||||
$printer -> setPrintBuffer($buffers[0]);
|
||||
}
|
||||
$printer -> cut();
|
||||
|
||||
/* Close printer */
|
||||
$printer -> close();
|
||||
} catch (Exception $e) {
|
||||
echo "Couldn't print to this printer: " . $e -> getMessage() . "\n";
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
/* Change to the correct path if you copy this example! */
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
|
||||
/**
|
||||
* This demonstrates available character encodings. Escpos-php accepts UTF-8,
|
||||
* and converts this to lower-level data to the printer. This is a complex area, so be
|
||||
* prepared to code a model-specific hack ('CapabilityProfile') for your printer.
|
||||
*
|
||||
* If you run into trouble, please file an issue on GitHub, including at a minimum:
|
||||
* - A UTF-8 test string in the language you're working in, and
|
||||
* - A test print or link to a technical document which lists the available
|
||||
* code pages ('character code tables') for your printer.
|
||||
*
|
||||
* The DefaultCapabilityProfile works for Espson-branded printers. For other models, you
|
||||
* must use/create a PrinterCapabilityProfile for your printer containing a list of code
|
||||
* page numbers for your printer- otherwise you will get mojibake.
|
||||
*
|
||||
* If you do not intend to use non-English characters, then use SimpleCapabilityProfile,
|
||||
* which has only the default encoding, effectively disabling code page changes.
|
||||
*/
|
||||
|
||||
include(dirname(__FILE__) . '/resources/character-encoding-test-strings.inc');
|
||||
try {
|
||||
// Enter connector and capability profile (to match your printer)
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$profile = CapabilityProfile::load("default");
|
||||
|
||||
/* Print a series of receipts containing i18n example strings */
|
||||
$printer = new Printer($connector, $profile);
|
||||
$printer -> selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_EMPHASIZED | Printer::MODE_DOUBLE_WIDTH);
|
||||
$printer -> text("Implemented languages\n");
|
||||
$printer -> selectPrintMode();
|
||||
foreach ($inputsOk as $label => $str) {
|
||||
$printer -> setEmphasis(true);
|
||||
$printer -> text($label . ":\n");
|
||||
$printer -> setEmphasis(false);
|
||||
$printer -> text($str);
|
||||
}
|
||||
$printer -> feed();
|
||||
|
||||
$printer -> selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_EMPHASIZED | Printer::MODE_DOUBLE_WIDTH);
|
||||
$printer -> text("Works in progress\n");
|
||||
$printer -> selectPrintMode();
|
||||
foreach ($inputsNotOk as $label => $str) {
|
||||
$printer -> setEmphasis(true);
|
||||
$printer -> text($label . ":\n");
|
||||
$printer -> setEmphasis(false);
|
||||
$printer -> text($str);
|
||||
}
|
||||
$printer -> cut();
|
||||
|
||||
/* Close printer */
|
||||
$printer -> close();
|
||||
} catch (Exception $e) {
|
||||
echo "Couldn't print to this printer: " . $e -> getMessage() . "\n";
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
/**
|
||||
* This demo prints out supported code pages on your printer. This is intended
|
||||
* for debugging character-encoding issues: If your printer does not work with
|
||||
* a built-in capability profile, you need to check its documentation for
|
||||
* supported code pages.
|
||||
*
|
||||
* These are then loaded into a capability profile, which maps code page
|
||||
* numbers to iconv encoding names on your particular printer. This script
|
||||
* will print all configured code pages, so that you can check that the chosen
|
||||
* iconv encoding name matches the actual code page contents.
|
||||
*
|
||||
* If this is correctly set up for your printer, then the driver will try its
|
||||
* best to map UTF-8 text into these code pages for you, allowing you to accept
|
||||
* arbitrary input from a database, without worrying about encoding it for the printer.
|
||||
*/
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
|
||||
// Enter connector and capability profile (to match your printer)
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$profile = CapabilityProfile::load("default");
|
||||
$verbose = false; // Skip tables which iconv wont convert to (ie, only print characters available with UTF-8 input)
|
||||
|
||||
/* Print a series of receipts containing i18n example strings - Code below shouldn't need changing */
|
||||
$printer = new Mike42\Escpos\Printer($connector, $profile);
|
||||
$codePages = $profile -> getCodePages();
|
||||
$first = true; // Print larger table for first code-page.
|
||||
foreach ($codePages as $table => $page) {
|
||||
/* Change printer code page */
|
||||
$printer -> selectCharacterTable(255);
|
||||
$printer -> selectCharacterTable($table);
|
||||
/* Select & print a label for it */
|
||||
$label = $page -> getId();
|
||||
if (!$page -> isEncodable()) {
|
||||
$label= " (not supported)";
|
||||
}
|
||||
$printer -> setEmphasis(true);
|
||||
$printer -> textRaw("Table $table: $label\n");
|
||||
$printer -> setEmphasis(false);
|
||||
if (!$page -> isEncodable() && !$verbose) {
|
||||
continue; // Skip non-recognised
|
||||
}
|
||||
/* Print a table of available characters (first table is larger than subsequent ones */
|
||||
if ($first) {
|
||||
$first = false;
|
||||
compactCharTable($printer, 1, true);
|
||||
} else {
|
||||
compactCharTable($printer);
|
||||
}
|
||||
}
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
|
||||
function compactCharTable($printer, $start = 4, $header = false)
|
||||
{
|
||||
/* Output a compact character table for the current encoding */
|
||||
$chars = str_repeat(' ', 256);
|
||||
for ($i = 0; $i < 255; $i++) {
|
||||
$chars[$i] = ($i > 32 && $i != 127) ? chr($i) : ' ';
|
||||
}
|
||||
if ($header) {
|
||||
$printer -> setEmphasis(true);
|
||||
$printer -> textRaw(" 0123456789ABCDEF0123456789ABCDEF\n");
|
||||
$printer -> setEmphasis(false);
|
||||
}
|
||||
for ($y = $start; $y < 8; $y++) {
|
||||
$printer -> setEmphasis(true);
|
||||
$printer -> textRaw(strtoupper(dechex($y * 2)) . " ");
|
||||
$printer -> setEmphasis(false);
|
||||
$printer -> textRaw(substr($chars, $y * 32, 32) . "\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
/**
|
||||
* This demo interacts with an Aures OCD-300 customer display,
|
||||
* showing its support for ESC/POS text encodings.
|
||||
*/
|
||||
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\Devices\AuresCustomerDisplay;
|
||||
|
||||
/*
|
||||
* Device appears as a serial port.
|
||||
*
|
||||
* stat /dev/ttyACM0
|
||||
* sudo usermod -a -G dialout [username]
|
||||
*/
|
||||
$connector = new FilePrintConnector("/dev/ttyACM0");
|
||||
|
||||
// Profile and display
|
||||
$profile = CapabilityProfile::load("OCD-300");
|
||||
$display = new AuresCustomerDisplay($connector, $profile);
|
||||
|
||||
|
||||
// Make a really long test string
|
||||
include(__DIR__ . "/resources/character-encoding-test-strings.inc");
|
||||
$input = "";
|
||||
foreach ($inputsOk as $str) {
|
||||
$input .= $str;
|
||||
}
|
||||
|
||||
// Wrap at a fixed width (as ASCII...), and show the user
|
||||
// what's about to be sent to the printer
|
||||
$wrapped = wordwrap($input, 20);
|
||||
echo($wrapped);
|
||||
|
||||
// Roll out each line with 0.5s delay
|
||||
foreach (explode("\n", $wrapped) as $line) {
|
||||
$display -> feed();
|
||||
$display -> text($line);
|
||||
usleep(500000);
|
||||
}
|
||||
|
||||
// Finish by showing "Hello World"
|
||||
$display -> clear();
|
||||
$display -> text("Hello World\n");
|
||||
|
||||
// Dont forget to close the device
|
||||
$display -> close();
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
<?php
|
||||
/**
|
||||
* This is a demo script for the functions of the PHP ESC/POS print driver,
|
||||
* Escpos.php.
|
||||
*
|
||||
* Most printers implement only a subset of the functionality of the driver, so
|
||||
* will not render this output correctly in all cases.
|
||||
*
|
||||
* @author Michael Billington <michael.billington@gmail.com>
|
||||
*/
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
use Mike42\Escpos\EscposImage;
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
|
||||
/* Initialize */
|
||||
$printer -> initialize();
|
||||
|
||||
/* Text */
|
||||
$printer -> text("Hello world\n");
|
||||
$printer -> cut();
|
||||
|
||||
/* Line feeds */
|
||||
$printer -> text("ABC");
|
||||
$printer -> feed(7);
|
||||
$printer -> text("DEF");
|
||||
$printer -> feedReverse(3);
|
||||
$printer -> text("GHI");
|
||||
$printer -> feed();
|
||||
$printer -> cut();
|
||||
|
||||
/* Font modes */
|
||||
$modes = array(
|
||||
Printer::MODE_FONT_B,
|
||||
Printer::MODE_EMPHASIZED,
|
||||
Printer::MODE_DOUBLE_HEIGHT,
|
||||
Printer::MODE_DOUBLE_WIDTH,
|
||||
Printer::MODE_UNDERLINE);
|
||||
for ($i = 0; $i < pow(2, count($modes)); $i++) {
|
||||
$bits = str_pad(decbin($i), count($modes), "0", STR_PAD_LEFT);
|
||||
$mode = 0;
|
||||
for ($j = 0; $j < strlen($bits); $j++) {
|
||||
if (substr($bits, $j, 1) == "1") {
|
||||
$mode |= $modes[$j];
|
||||
}
|
||||
}
|
||||
$printer -> selectPrintMode($mode);
|
||||
$printer -> text("ABCDEFGHIJabcdefghijk\n");
|
||||
}
|
||||
$printer -> selectPrintMode(); // Reset
|
||||
$printer -> cut();
|
||||
|
||||
/* Underline */
|
||||
for ($i = 0; $i < 3; $i++) {
|
||||
$printer -> setUnderline($i);
|
||||
$printer -> text("The quick brown fox jumps over the lazy dog\n");
|
||||
}
|
||||
$printer -> setUnderline(0); // Reset
|
||||
$printer -> cut();
|
||||
|
||||
/* Cuts */
|
||||
$printer -> text("Partial cut\n(not available on all printers)\n");
|
||||
$printer -> cut(Printer::CUT_PARTIAL);
|
||||
$printer -> text("Full cut\n");
|
||||
$printer -> cut(Printer::CUT_FULL);
|
||||
|
||||
/* Emphasis */
|
||||
for ($i = 0; $i < 2; $i++) {
|
||||
$printer -> setEmphasis($i == 1);
|
||||
$printer -> text("The quick brown fox jumps over the lazy dog\n");
|
||||
}
|
||||
$printer -> setEmphasis(false); // Reset
|
||||
$printer -> cut();
|
||||
|
||||
/* Double-strike (looks basically the same as emphasis) */
|
||||
for ($i = 0; $i < 2; $i++) {
|
||||
$printer -> setDoubleStrike($i == 1);
|
||||
$printer -> text("The quick brown fox jumps over the lazy dog\n");
|
||||
}
|
||||
$printer -> setDoubleStrike(false);
|
||||
$printer -> cut();
|
||||
|
||||
/* Fonts (many printers do not have a 'Font C') */
|
||||
$fonts = array(
|
||||
Printer::FONT_A,
|
||||
Printer::FONT_B,
|
||||
Printer::FONT_C);
|
||||
for ($i = 0; $i < count($fonts); $i++) {
|
||||
$printer -> setFont($fonts[$i]);
|
||||
$printer -> text("The quick brown fox jumps over the lazy dog\n");
|
||||
}
|
||||
$printer -> setFont(); // Reset
|
||||
$printer -> cut();
|
||||
|
||||
/* Justification */
|
||||
$justification = array(
|
||||
Printer::JUSTIFY_LEFT,
|
||||
Printer::JUSTIFY_CENTER,
|
||||
Printer::JUSTIFY_RIGHT);
|
||||
for ($i = 0; $i < count($justification); $i++) {
|
||||
$printer -> setJustification($justification[$i]);
|
||||
$printer -> text("A man a plan a canal panama\n");
|
||||
}
|
||||
$printer -> setJustification(); // Reset
|
||||
$printer -> cut();
|
||||
|
||||
/* Barcodes - see barcode.php for more detail */
|
||||
$printer -> setBarcodeHeight(80);
|
||||
$printer->setBarcodeTextPosition(Printer::BARCODE_TEXT_BELOW);
|
||||
$printer -> barcode("9876");
|
||||
$printer -> feed();
|
||||
$printer -> cut();
|
||||
|
||||
/* Graphics - this demo will not work on some non-Epson printers */
|
||||
try {
|
||||
$logo = EscposImage::load("resources/escpos-php.png", false);
|
||||
$imgModes = array(
|
||||
Printer::IMG_DEFAULT,
|
||||
Printer::IMG_DOUBLE_WIDTH,
|
||||
Printer::IMG_DOUBLE_HEIGHT,
|
||||
Printer::IMG_DOUBLE_WIDTH | Printer::IMG_DOUBLE_HEIGHT
|
||||
);
|
||||
foreach ($imgModes as $mode) {
|
||||
$printer -> graphics($logo, $mode);
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
/* Images not supported on your PHP, or image file not found */
|
||||
$printer -> text($e -> getMessage() . "\n");
|
||||
}
|
||||
$printer -> cut();
|
||||
|
||||
/* Bit image */
|
||||
try {
|
||||
$logo = EscposImage::load("resources/escpos-php.png", false);
|
||||
$imgModes = array(
|
||||
Printer::IMG_DEFAULT,
|
||||
Printer::IMG_DOUBLE_WIDTH,
|
||||
Printer::IMG_DOUBLE_HEIGHT,
|
||||
Printer::IMG_DOUBLE_WIDTH | Printer::IMG_DOUBLE_HEIGHT
|
||||
);
|
||||
foreach ($imgModes as $mode) {
|
||||
$printer -> bitImage($logo, $mode);
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
/* Images not supported on your PHP, or image file not found */
|
||||
$printer -> text($e -> getMessage() . "\n");
|
||||
}
|
||||
$printer -> cut();
|
||||
|
||||
/* QR Code - see also the more in-depth demo at qr-code.php */
|
||||
$testStr = "Testing 123";
|
||||
$models = array(
|
||||
Printer::QR_MODEL_1 => "QR Model 1",
|
||||
Printer::QR_MODEL_2 => "QR Model 2 (default)",
|
||||
Printer::QR_MICRO => "Micro QR code\n(not supported on all printers)");
|
||||
foreach ($models as $model => $name) {
|
||||
$printer -> qrCode($testStr, Printer::QR_ECLEVEL_L, 3, $model);
|
||||
$printer -> text("$name\n");
|
||||
$printer -> feed();
|
||||
}
|
||||
$printer -> cut();
|
||||
|
||||
/* Pulse */
|
||||
$printer -> pulse();
|
||||
|
||||
/* Always close the printer! On some PrintConnectors, no actual
|
||||
* data is sent until the printer is closed. */
|
||||
$printer -> close();
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
/* Print-outs using the newer graphics print command */
|
||||
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\EscposImage;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
|
||||
try {
|
||||
$tux = EscposImage::load("resources/tux.png", false);
|
||||
|
||||
$printer -> graphics($tux);
|
||||
$printer -> text("Regular Tux.\n");
|
||||
$printer -> feed();
|
||||
|
||||
$printer -> graphics($tux, Printer::IMG_DOUBLE_WIDTH);
|
||||
$printer -> text("Wide Tux.\n");
|
||||
$printer -> feed();
|
||||
|
||||
$printer -> graphics($tux, Printer::IMG_DOUBLE_HEIGHT);
|
||||
$printer -> text("Tall Tux.\n");
|
||||
$printer -> feed();
|
||||
|
||||
$printer -> graphics($tux, Printer::IMG_DOUBLE_WIDTH | Printer::IMG_DOUBLE_HEIGHT);
|
||||
$printer -> text("Large Tux in correct proportion.\n");
|
||||
|
||||
$printer -> cut();
|
||||
} catch (Exception $e) {
|
||||
/* Images not supported on your PHP, or image file not found */
|
||||
$printer -> text($e -> getMessage() . "\n");
|
||||
}
|
||||
|
||||
$printer -> close();
|
||||
@@ -0,0 +1,8 @@
|
||||
Interfaces
|
||||
----------
|
||||
This directory contains boilerpalte code to show you how to open a print connector
|
||||
to printers which are connected in different ways.
|
||||
|
||||
To get a list of supported interfaces and operating systems, see the main README.md file for the project.
|
||||
|
||||
If you have a printer interface with no example, and you want to help put one together, then please lodge a request on the bug tracker: https://github.com/mike42/escpos-php/issues
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
/* Change to the correct path if you copy this example! */
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\CupsPrintConnector;
|
||||
|
||||
try {
|
||||
$connector = new CupsPrintConnector("EPSON_TM-T20");
|
||||
|
||||
/* Print a "Hello world" receipt" */
|
||||
$printer = new Printer($connector);
|
||||
$printer -> text("Hello World!\n");
|
||||
$printer -> cut();
|
||||
|
||||
/* Close printer */
|
||||
$printer -> close();
|
||||
} catch (Exception $e) {
|
||||
echo "Couldn't print to this printer: " . $e -> getMessage() . "\n";
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
/* Change to the correct path if you copy this example! */
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\NetworkPrintConnector;
|
||||
|
||||
/* Most printers are open on port 9100, so you just need to know the IP
|
||||
* address of your receipt printer, and then fsockopen() it on that port.
|
||||
*/
|
||||
try {
|
||||
$connector = new NetworkPrintConnector("10.x.x.x", 9100);
|
||||
|
||||
/* Print a "Hello world" receipt" */
|
||||
$printer = new Printer($connector);
|
||||
$printer -> text("Hello World!\n");
|
||||
$printer -> cut();
|
||||
|
||||
/* Close printer */
|
||||
$printer -> close();
|
||||
} catch (Exception $e) {
|
||||
echo "Couldn't print to this printer: " . $e -> getMessage() . "\n";
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
/* Change to the correct path if you copy this example! */
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
/**
|
||||
* On Linux, use the usblp module to make your printer available as a device
|
||||
* file. This is generally the default behaviour if you don't install any
|
||||
* vendor drivers.
|
||||
*
|
||||
* Once this is done, use a FilePrintConnector to open the device.
|
||||
*
|
||||
* Troubleshooting: On Debian, you must be in the lp group to access this file.
|
||||
* dmesg to see what happens when you plug in your printer to make sure no
|
||||
* other drivers are unloading the module.
|
||||
*/
|
||||
try {
|
||||
// Enter the device file for your USB printer here
|
||||
$connector = new FilePrintConnector("/dev/usb/lp0");
|
||||
//$connector = new FilePrintConnector("/dev/usb/lp1");
|
||||
//$connector = new FilePrintConnector("/dev/usb/lp2");
|
||||
|
||||
/* Print a "Hello world" receipt" */
|
||||
$printer = new Printer($connector);
|
||||
$printer -> text("Hello World!\n");
|
||||
$printer -> cut();
|
||||
|
||||
/* Close printer */
|
||||
$printer -> close();
|
||||
} catch (Exception $e) {
|
||||
echo "Couldn't print to this printer: " . $e -> getMessage() . "\n";
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
/* Change to the correct path if you copy this example! */
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
|
||||
|
||||
/**
|
||||
* Install the printer using USB printing support, and the "Generic / Text Only" driver,
|
||||
* then share it.
|
||||
*
|
||||
* Use a WindowsPrintConnector with the share name to print. This works on either
|
||||
* Windows or Linux.
|
||||
*
|
||||
* Troubleshooting: Fire up a command prompt/terminal, and ensure that (if your printer is
|
||||
* shared as "Receipt Printer"), the following commands work.
|
||||
*
|
||||
* Windows: (use an appropriate "net use" command if you need authentication)
|
||||
* echo "Hello World" > testfile
|
||||
* ## If you need authentication, use "net use" to hook up the printer:
|
||||
* # net use "\\computername\Receipt Printer" /user:Guest
|
||||
* # net use "\\computername\Receipt Printer" /user:Bob secret
|
||||
* # net use "\\computername\Receipt Printer" /user:workgroup\Bob secret
|
||||
* copy testfile "\\computername\Receipt Printer"
|
||||
* del testfile
|
||||
*
|
||||
* GNU/Linux:
|
||||
* # No authentication
|
||||
* echo "Hello World" | smbclient "//computername/Receipt Printer" -c "print -" -N
|
||||
* # Guest login
|
||||
* echo "Hello World" | smbclient "//computername/Receipt Printer" -U Guest -c "print -" -N
|
||||
* # Basic username/password
|
||||
* echo "Hello World" | smbclient "//computername/Receipt Printer" secret -U "Bob" -c "print -"
|
||||
* # Including domain name
|
||||
* echo "Hello World" | smbclient "//computername/Receipt Printer" secret -U "workgroup\\Bob" -c "print -"
|
||||
*/
|
||||
try {
|
||||
// Enter the share name for your printer here, as a smb:// url format
|
||||
$connector = new WindowsPrintConnector("smb://computername/Receipt Printer");
|
||||
//$connector = new WindowsPrintConnector("smb://Guest@computername/Receipt Printer");
|
||||
//$connector = new WindowsPrintConnector("smb://FooUser:secret@computername/workgroup/Receipt Printer");
|
||||
//$connector = new WindowsPrintConnector("smb://User:secret@computername/Receipt Printer");
|
||||
|
||||
/* Print a "Hello world" receipt" */
|
||||
$printer = new Printer($connector);
|
||||
$printer -> text("Hello World!\n");
|
||||
$printer -> cut();
|
||||
|
||||
/* Close printer */
|
||||
$printer -> close();
|
||||
} catch (Exception $e) {
|
||||
echo "Couldn't print to this printer: " . $e -> getMessage() . "\n";
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
/* Change to the correct path if you copy this example! */
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
|
||||
|
||||
/**
|
||||
* Assuming your printer is available at LPT1,
|
||||
* simpy instantiate a WindowsPrintConnector to it.
|
||||
*
|
||||
* When troubleshooting, make sure you can send it
|
||||
* data from the command-line first:
|
||||
* echo "Hello World" > LPT1
|
||||
*/
|
||||
try {
|
||||
$connector = new WindowsPrintConnector("LPT1");
|
||||
|
||||
// A FilePrintConnector will also work, but on non-Windows systems, writes
|
||||
// to an actual file called 'LPT1' rather than giving a useful error.
|
||||
// $connector = new FilePrintConnector("LPT1");
|
||||
|
||||
/* Print a "Hello world" receipt" */
|
||||
$printer = new Printer($connector);
|
||||
$printer -> text("Hello World!\n");
|
||||
$printer -> cut();
|
||||
|
||||
/* Close printer */
|
||||
$printer -> close();
|
||||
} catch (Exception $e) {
|
||||
echo "Couldn't print to this printer: " . $e -> getMessage() . "\n";
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
/* Change to the correct path if you copy this example! */
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
|
||||
|
||||
/**
|
||||
* Install the printer using USB printing support, and the "Generic / Text Only" driver,
|
||||
* then share it (you can use a firewall so that it can only be seen locally).
|
||||
*
|
||||
* Use a WindowsPrintConnector with the share name to print.
|
||||
*
|
||||
* Troubleshooting: Fire up a command prompt, and ensure that (if your printer is shared as
|
||||
* "Receipt Printer), the following commands work:
|
||||
*
|
||||
* echo "Hello World" > testfile
|
||||
* copy testfile "\\%COMPUTERNAME%\Receipt Printer"
|
||||
* del testfile
|
||||
*/
|
||||
try {
|
||||
// Enter the share name for your USB printer here
|
||||
$connector = null;
|
||||
//$connector = new WindowsPrintConnector("Receipt Printer");
|
||||
|
||||
/* Print a "Hello world" receipt" */
|
||||
$printer = new Printer($connector);
|
||||
$printer -> text("Hello World!\n");
|
||||
$printer -> cut();
|
||||
|
||||
/* Close printer */
|
||||
$printer -> close();
|
||||
} catch (Exception $e) {
|
||||
echo "Couldn't print to this printer: " . $e -> getMessage() . "\n";
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
/* Left margin & page width demo. */
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout"); // Add connector for your printer here.
|
||||
$printer = new Printer($connector);
|
||||
|
||||
/* Line spacing */
|
||||
/*
|
||||
$printer -> setEmphasis(true);
|
||||
$printer -> text("Line spacing\n");
|
||||
$printer -> setEmphasis(false);
|
||||
foreach(array(16, 32, 64, 128, 255) as $spacing) {
|
||||
$printer -> setLineSpacing($spacing);
|
||||
$printer -> text("Spacing $spacing: The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.\n");
|
||||
}
|
||||
$printer -> setLineSpacing(); // Back to default
|
||||
*/
|
||||
|
||||
/* Stuff around with left margin */
|
||||
$printer -> setEmphasis(true);
|
||||
$printer -> text("Left margin\n");
|
||||
$printer -> setEmphasis(false);
|
||||
$printer -> text("Default left\n");
|
||||
foreach(array(1, 2, 4, 8, 16, 32, 64, 128, 256, 512) as $margin) {
|
||||
$printer -> setPrintLeftMargin($margin);
|
||||
$printer -> text("left margin $margin\n");
|
||||
}
|
||||
/* Reset left */
|
||||
$printer -> setPrintLeftMargin(0);
|
||||
|
||||
/* Stuff around with page width */
|
||||
$printer -> setEmphasis(true);
|
||||
$printer -> text("Page width\n");
|
||||
$printer -> setEmphasis(false);
|
||||
$printer -> setJustification(Printer::JUSTIFY_RIGHT);
|
||||
$printer -> text("Default width\n");
|
||||
foreach(array(512, 256, 128, 64) as $width) {
|
||||
$printer -> setPrintWidth($width);
|
||||
$printer -> text("page width $width\n");
|
||||
}
|
||||
|
||||
/* Printer shutdown */
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
/* Demonstration of available options on the pdf417Code() command */
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
|
||||
// Most simple example
|
||||
title($printer, "PDF417 code demo\n");
|
||||
$testStr = "Testing 123";
|
||||
$printer -> pdf417Code($testStr);
|
||||
$printer -> text("Most simple example\n");
|
||||
$printer -> feed();
|
||||
|
||||
// Demo that alignment is the same as text
|
||||
$printer -> setJustification(Printer::JUSTIFY_CENTER);
|
||||
$printer -> pdf417Code($testStr, 3, 3, 2);
|
||||
$printer -> text("Same content, narrow and centred\n");
|
||||
$printer -> setJustification();
|
||||
$printer -> feed();
|
||||
|
||||
// Demo of error correction
|
||||
title($printer, "Error correction\n");
|
||||
$ec = array(0.1, 0.5, 1.0, 2.0, 4.0);
|
||||
foreach ($ec as $level) {
|
||||
$printer -> pdf417Code($testStr, 3, 3, 0, $level);
|
||||
$printer -> text("Error correction ratio $level\n");
|
||||
$printer -> feed();
|
||||
}
|
||||
|
||||
// Change size
|
||||
title($printer, "Pixel size\n");
|
||||
$sizes = array(
|
||||
2 => "(minimum)",
|
||||
3 => "(default)",
|
||||
4 => "",
|
||||
8 => "(maximum)");
|
||||
foreach ($sizes as $size => $label) {
|
||||
$printer -> pdf417Code($testStr, $size);
|
||||
$printer -> text("Module width $size dots $label\n");
|
||||
$printer -> feed();
|
||||
}
|
||||
|
||||
// Change height
|
||||
title($printer, "Height multiplier\n");
|
||||
$sizes = array(
|
||||
2 => "(minimum)",
|
||||
3 => "(default)",
|
||||
4 => "",
|
||||
8 => "(maximum)");
|
||||
foreach ($sizes as $size => $label) {
|
||||
$printer -> pdf417Code($testStr, 3, $size);
|
||||
$printer -> text("Height multiplier $size $label\n");
|
||||
$printer -> feed();
|
||||
}
|
||||
|
||||
// Chage data column count
|
||||
title($printer, "Data column count\n");
|
||||
$columnCounts = array(
|
||||
0 => "(auto, default)",
|
||||
1 => "",
|
||||
2 => "",
|
||||
3 => "",
|
||||
4 => "",
|
||||
5 => "",
|
||||
30 => "(maximum, doesnt fit!)");
|
||||
foreach ($columnCounts as $columnCount => $label) {
|
||||
$printer -> pdf417Code($testStr, 3, 3, $columnCount);
|
||||
$printer -> text("Column count $columnCount $label\n");
|
||||
$printer -> feed();
|
||||
}
|
||||
|
||||
// Change options
|
||||
title($printer, "Options\n");
|
||||
$models = array(
|
||||
Printer::PDF417_STANDARD => "Standard",
|
||||
Printer::PDF417_TRUNCATED => "Truncated");
|
||||
foreach ($models as $model => $name) {
|
||||
$printer -> pdf417Code($testStr, 3, 3, 0, 0.10, $model);
|
||||
$printer -> text("$name\n");
|
||||
$printer -> feed();
|
||||
}
|
||||
|
||||
// Cut & close
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
|
||||
function title(Printer $printer, $str)
|
||||
{
|
||||
$printer -> selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
|
||||
$printer -> text($str);
|
||||
$printer -> selectPrintMode();
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\EscposImage;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout"); // Add connector for your printer here.
|
||||
$printer = new Printer($connector);
|
||||
|
||||
/*
|
||||
* Due to its complxity, escpos-php does not support HTML input. To print HTML,
|
||||
* either convert it to calls on the Printer() object, or rasterise the page with
|
||||
* wkhtmltopdf, an external package which is designed to handle HTML efficiently.
|
||||
*
|
||||
* This example is provided to get you started: On Debian, first run-
|
||||
*
|
||||
* sudo apt-get install wkhtmltopdf xvfb
|
||||
*
|
||||
* Note: Depending on the height of your pages, it is suggested that you chop it
|
||||
* into smaller sections, as printers simply don't have the buffer capacity for
|
||||
* very large images.
|
||||
*
|
||||
* As always, you can trade off quality for capacity by halving the width
|
||||
* (550 -> 225 below) and printing w/ Escpos::IMG_DOUBLE_WIDTH | Escpos::IMG_DOUBLE_HEIGHT
|
||||
*/
|
||||
try {
|
||||
/* Set up command */
|
||||
$source = __DIR__ . "/resources/document.html";
|
||||
$width = 550;
|
||||
$dest = tempnam(sys_get_temp_dir(), 'escpos') . ".png";
|
||||
$command = sprintf(
|
||||
"xvfb-run wkhtmltoimage -n -q --width %s %s %s",
|
||||
escapeshellarg($width),
|
||||
escapeshellarg($source),
|
||||
escapeshellarg($dest)
|
||||
);
|
||||
|
||||
/* Test for dependencies */
|
||||
foreach (array("xvfb-run", "wkhtmltoimage") as $cmd) {
|
||||
$testCmd = sprintf("which %s", escapeshellarg($cmd));
|
||||
exec($testCmd, $testOut, $testStatus);
|
||||
if ($testStatus != 0) {
|
||||
throw new Exception("You require $cmd but it could not be found");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Run wkhtmltoimage */
|
||||
$descriptors = array(
|
||||
1 => array("pipe", "w"),
|
||||
2 => array("pipe", "w"),
|
||||
);
|
||||
$process = proc_open($command, $descriptors, $fd);
|
||||
if (is_resource($process)) {
|
||||
/* Read stdout */
|
||||
$outputStr = stream_get_contents($fd[1]);
|
||||
fclose($fd[1]);
|
||||
/* Read stderr */
|
||||
$errorStr = stream_get_contents($fd[2]);
|
||||
fclose($fd[2]);
|
||||
/* Finish up */
|
||||
$retval = proc_close($process);
|
||||
if ($retval != 0) {
|
||||
throw new Exception("Command $cmd failed: $outputStr $errorStr");
|
||||
}
|
||||
} else {
|
||||
throw new Exception("Command '$cmd' failed to start.");
|
||||
}
|
||||
|
||||
/* Load up the image */
|
||||
try {
|
||||
$img = EscposImage::load($dest);
|
||||
} catch (Exception $e) {
|
||||
unlink($dest);
|
||||
throw $e;
|
||||
}
|
||||
unlink($dest);
|
||||
|
||||
/* Print it */
|
||||
$printer -> bitImage($img); // bitImage() seems to allow larger images than graphics() on the TM-T20. bitImageColumnFormat() is another option.
|
||||
$printer -> cut();
|
||||
} catch (Exception $e) {
|
||||
echo $e -> getMessage();
|
||||
} finally {
|
||||
$printer -> close();
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\ImagickEscposImage;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
/*
|
||||
* This is three examples in one:
|
||||
* 1: Print an entire PDF, normal quality.
|
||||
* 2: Print at a lower quality for speed increase (CPU & transfer)
|
||||
* 3: Cache rendered documents for a speed increase (removes CPU image processing completely on subsequent prints)
|
||||
*/
|
||||
|
||||
/* 1: Print an entire PDF, start-to-finish (shorter form of the example) */
|
||||
$pdf = 'resources/document.pdf';
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
try {
|
||||
$pages = ImagickEscposImage::loadPdf($pdf);
|
||||
foreach ($pages as $page) {
|
||||
$printer -> graphics($page);
|
||||
}
|
||||
$printer -> cut();
|
||||
} catch (Exception $e) {
|
||||
/*
|
||||
* loadPdf() throws exceptions if files or not found, or you don't have the
|
||||
* imagick extension to read PDF's
|
||||
*/
|
||||
echo $e -> getMessage() . "\n";
|
||||
} finally {
|
||||
$printer -> close();
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* 2: Speed up printing by roughly halving the resolution, and printing double-size.
|
||||
* This gives a 75% speed increase at the expense of some quality.
|
||||
*
|
||||
* Reduce the page width further if necessary: if it extends past the printing area, your prints will be very slow.
|
||||
*/
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
$pdf = 'resources/document.pdf';
|
||||
$pages = ImagickEscposImage::loadPdf($pdf, 260);
|
||||
foreach ($pages as $page) {
|
||||
$printer -> graphics($page, Printer::IMG_DOUBLE_HEIGHT | Printer::IMG_DOUBLE_WIDTH);
|
||||
}
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
|
||||
/*
|
||||
* 3: PDF printing still too slow? If you regularly print the same files, serialize & compress your
|
||||
* EscposImage objects (after printing[1]), instead of throwing them away.
|
||||
*
|
||||
* (You can also do this to print logos on computers which don't have an
|
||||
* image processing library, by preparing a serialized version of your logo on your PC)
|
||||
*
|
||||
* [1]After printing, the pixels are loaded and formatted for the print command you used, so even a raspberry pi can print complex PDF's quickly.
|
||||
*/
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
$pdf = 'resources/document.pdf';
|
||||
$ser = 'resources/document.z';
|
||||
if (!file_exists($ser)) {
|
||||
$pages = ImagickEscposImage::loadPdf($pdf);
|
||||
} else {
|
||||
$pages = unserialize(gzuncompress(file_get_contents($ser)));
|
||||
}
|
||||
|
||||
foreach ($pages as $page) {
|
||||
$printer -> graphics($page);
|
||||
}
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
|
||||
if (!file_exists($ser)) {
|
||||
file_put_contents($ser, gzcompress(serialize($pages)));
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
/* Demonstration of available options on the qrCode() command */
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
|
||||
// Most simple example
|
||||
title($printer, "QR code demo\n");
|
||||
$testStr = "Testing 123";
|
||||
$printer -> qrCode($testStr);
|
||||
$printer -> text("Most simple example\n");
|
||||
$printer -> feed();
|
||||
|
||||
// Demo that alignment is the same as text
|
||||
$printer -> setJustification(Printer::JUSTIFY_CENTER);
|
||||
$printer -> qrCode($testStr);
|
||||
$printer -> text("Same example, centred\n");
|
||||
$printer -> setJustification();
|
||||
$printer -> feed();
|
||||
|
||||
// Demo of numeric data being packed more densly
|
||||
title($printer, "Data encoding\n");
|
||||
$test = array(
|
||||
"Numeric" => "0123456789012345678901234567890123456789",
|
||||
"Alphanumeric" => "abcdefghijklmnopqrstuvwxyzabcdefghijklmn",
|
||||
"Binary" => str_repeat("\0", 40));
|
||||
foreach ($test as $type => $data) {
|
||||
$printer -> qrCode($data);
|
||||
$printer -> text("$type\n");
|
||||
$printer -> feed();
|
||||
}
|
||||
|
||||
// Demo of error correction
|
||||
title($printer, "Error correction\n");
|
||||
$ec = array(
|
||||
Printer::QR_ECLEVEL_L => "L",
|
||||
Printer::QR_ECLEVEL_M => "M",
|
||||
Printer::QR_ECLEVEL_Q => "Q",
|
||||
Printer::QR_ECLEVEL_H => "H");
|
||||
foreach ($ec as $level => $name) {
|
||||
$printer -> qrCode($testStr, $level);
|
||||
$printer -> text("Error correction $name\n");
|
||||
$printer -> feed();
|
||||
}
|
||||
|
||||
// Change size
|
||||
title($printer, "Pixel size\n");
|
||||
$sizes = array(
|
||||
1 => "(minimum)",
|
||||
2 => "",
|
||||
3 => "(default)",
|
||||
4 => "",
|
||||
5 => "",
|
||||
10 => "",
|
||||
16 => "(maximum)");
|
||||
foreach ($sizes as $size => $label) {
|
||||
$printer -> qrCode($testStr, Printer::QR_ECLEVEL_L, $size);
|
||||
$printer -> text("Pixel size $size $label\n");
|
||||
$printer -> feed();
|
||||
}
|
||||
|
||||
// Change model
|
||||
title($printer, "QR model\n");
|
||||
$models = array(
|
||||
Printer::QR_MODEL_1 => "QR Model 1",
|
||||
Printer::QR_MODEL_2 => "QR Model 2 (default)",
|
||||
Printer::QR_MICRO => "Micro QR code\n(not supported on all printers)");
|
||||
foreach ($models as $model => $name) {
|
||||
$printer -> qrCode($testStr, Printer::QR_ECLEVEL_L, 3, $model);
|
||||
$printer -> text("$name\n");
|
||||
$printer -> feed();
|
||||
}
|
||||
|
||||
// Cut & close
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
|
||||
function title(Printer $printer, $str)
|
||||
{
|
||||
$printer -> selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
|
||||
$printer -> text($str);
|
||||
$printer -> selectPrintMode();
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>RawBT Integration Demo</title>
|
||||
<meta content="width=device-width, initial-scale=1" name="viewport">
|
||||
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
|
||||
<style>
|
||||
html {
|
||||
background-color: grey;
|
||||
padding: 32px;
|
||||
}
|
||||
|
||||
body {
|
||||
max-width: 640px;
|
||||
margin: 0 auto;
|
||||
padding: 32px;
|
||||
background-color: white;
|
||||
}
|
||||
|
||||
button {
|
||||
background-color: #6e89ff;
|
||||
color: white;
|
||||
padding: 16px;
|
||||
border: none;
|
||||
}
|
||||
|
||||
pre {
|
||||
background-color: #f0f0f0;
|
||||
border-left: #6e89ff solid 3px
|
||||
}
|
||||
|
||||
p {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #6e89ff;
|
||||
text-decoration: none;
|
||||
}
|
||||
a:before{
|
||||
content: '\1F855';
|
||||
margin-right:4px;
|
||||
}
|
||||
</style>
|
||||
<script>
|
||||
// for php demo call
|
||||
function ajax_print(url, btn) {
|
||||
b = $(btn);
|
||||
b.attr('data-old', b.text());
|
||||
b.text('wait');
|
||||
$.get(url, function (data) {
|
||||
window.location.href = data; // main action
|
||||
}).fail(function () {
|
||||
alert("ajax error");
|
||||
}).always(function () {
|
||||
b.text(b.attr('data-old'));
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<img src="resources/rawbtlogo.png" alt="black & white picture">
|
||||
<h1>RawBT Integration Demo</h1>
|
||||
<pre>
|
||||
|
||||
window.location.href = ajax_backend_data;
|
||||
|
||||
</pre>
|
||||
<br/>
|
||||
<button onclick="ajax_print('rawbt-receipt.php',this)">RECEIPT</button>
|
||||
|
||||
<p><a href="https://rawbt.ru/">Visit RawBT site</a></p>
|
||||
</body>
|
||||
</html>
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
<?php
|
||||
require __DIR__ . '/../autoload.php';
|
||||
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\EscposImage;
|
||||
use Mike42\Escpos\PrintConnectors\RawbtPrintConnector;
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
|
||||
try {
|
||||
$profile = CapabilityProfile::load("POS-5890");
|
||||
|
||||
/* Fill in your own connector here */
|
||||
$connector = new RawbtPrintConnector();
|
||||
|
||||
/* Information for the receipt */
|
||||
$items = array(
|
||||
new item("Example item #1", "4.00"),
|
||||
new item("Another thing", "3.50"),
|
||||
new item("Something else", "1.00"),
|
||||
new item("A final item", "4.45"),
|
||||
);
|
||||
$subtotal = new item('Subtotal', '12.95');
|
||||
$tax = new item('A local tax', '1.30');
|
||||
$total = new item('Total', '14.25', true);
|
||||
/* Date is kept the same for testing */
|
||||
// $date = date('l jS \of F Y h:i:s A');
|
||||
$date = "Monday 6th of April 2015 02:56:25 PM";
|
||||
|
||||
/* Start the printer */
|
||||
$logo = EscposImage::load("resources/rawbtlogo.png", false);
|
||||
$printer = new Printer($connector, $profile);
|
||||
|
||||
|
||||
/* Print top logo */
|
||||
if ($profile->getSupportsGraphics()) {
|
||||
$printer->graphics($logo);
|
||||
}
|
||||
if ($profile->getSupportsBitImageRaster() && !$profile->getSupportsGraphics()) {
|
||||
$printer->bitImage($logo);
|
||||
}
|
||||
|
||||
/* Name of shop */
|
||||
$printer->setJustification(Printer::JUSTIFY_CENTER);
|
||||
$printer->selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
|
||||
$printer->text("ExampleMart Ltd.\n");
|
||||
$printer->selectPrintMode();
|
||||
$printer->text("Shop No. 42.\n");
|
||||
$printer->feed();
|
||||
|
||||
|
||||
/* Title of receipt */
|
||||
$printer->setEmphasis(true);
|
||||
$printer->text("SALES INVOICE\n");
|
||||
$printer->setEmphasis(false);
|
||||
|
||||
/* Items */
|
||||
$printer->setJustification(Printer::JUSTIFY_LEFT);
|
||||
$printer->setEmphasis(true);
|
||||
$printer->text(new item('', '$'));
|
||||
$printer->setEmphasis(false);
|
||||
foreach ($items as $item) {
|
||||
$printer->text($item->getAsString(32)); // for 58mm Font A
|
||||
}
|
||||
$printer->setEmphasis(true);
|
||||
$printer->text($subtotal->getAsString(32));
|
||||
$printer->setEmphasis(false);
|
||||
$printer->feed();
|
||||
|
||||
/* Tax and total */
|
||||
$printer->text($tax->getAsString(32));
|
||||
$printer->selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
|
||||
$printer->text($total->getAsString(32));
|
||||
$printer->selectPrintMode();
|
||||
|
||||
/* Footer */
|
||||
$printer->feed(2);
|
||||
$printer->setJustification(Printer::JUSTIFY_CENTER);
|
||||
$printer->text("Thank you for shopping\n");
|
||||
$printer->text("at ExampleMart\n");
|
||||
$printer->text("For trading hours,\n");
|
||||
$printer->text("please visit example.com\n");
|
||||
$printer->feed(2);
|
||||
$printer->text($date . "\n");
|
||||
|
||||
/* Barcode Default look */
|
||||
|
||||
$printer->barcode("ABC", Printer::BARCODE_CODE39);
|
||||
$printer->feed();
|
||||
$printer->feed();
|
||||
|
||||
|
||||
// Demo that alignment QRcode is the same as text
|
||||
$printer2 = new Printer($connector); // dirty printer profile hack !!
|
||||
$printer2->setJustification(Printer::JUSTIFY_CENTER);
|
||||
$printer2->qrCode("https://rawbt.ru/mike42", Printer::QR_ECLEVEL_M, 8);
|
||||
$printer2->text("rawbt.ru/mike42\n");
|
||||
$printer2->setJustification();
|
||||
$printer2->feed();
|
||||
|
||||
|
||||
/* Cut the receipt and open the cash drawer */
|
||||
$printer->cut();
|
||||
$printer->pulse();
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo $e->getMessage();
|
||||
} finally {
|
||||
$printer->close();
|
||||
}
|
||||
|
||||
/* A wrapper to do organise item names & prices into columns */
|
||||
|
||||
class item
|
||||
{
|
||||
private $name;
|
||||
private $price;
|
||||
private $dollarSign;
|
||||
|
||||
public function __construct($name = '', $price = '', $dollarSign = false)
|
||||
{
|
||||
$this->name = $name;
|
||||
$this->price = $price;
|
||||
$this->dollarSign = $dollarSign;
|
||||
}
|
||||
|
||||
public function getAsString($width = 48)
|
||||
{
|
||||
$rightCols = 10;
|
||||
$leftCols = $width - $rightCols;
|
||||
if ($this->dollarSign) {
|
||||
$leftCols = $leftCols / 2 - $rightCols / 2;
|
||||
}
|
||||
$left = str_pad($this->name, $leftCols);
|
||||
|
||||
$sign = ($this->dollarSign ? '$ ' : '');
|
||||
$right = str_pad($sign . $this->price, $rightCols, ' ', STR_PAD_LEFT);
|
||||
return "$left$right\n";
|
||||
}
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
return $this->getAsString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\EscposImage;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
/* Fill in your own connector here */
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
|
||||
/* Information for the receipt */
|
||||
$items = array(
|
||||
new item("Example item #1", "4.00"),
|
||||
new item("Another thing", "3.50"),
|
||||
new item("Something else", "1.00"),
|
||||
new item("A final item", "4.45"),
|
||||
);
|
||||
$subtotal = new item('Subtotal', '12.95');
|
||||
$tax = new item('A local tax', '1.30');
|
||||
$total = new item('Total', '14.25', true);
|
||||
/* Date is kept the same for testing */
|
||||
// $date = date('l jS \of F Y h:i:s A');
|
||||
$date = "Monday 6th of April 2015 02:56:25 PM";
|
||||
|
||||
/* Start the printer */
|
||||
$logo = EscposImage::load("resources/escpos-php.png", false);
|
||||
$printer = new Printer($connector);
|
||||
|
||||
/* Print top logo */
|
||||
$printer -> setJustification(Printer::JUSTIFY_CENTER);
|
||||
$printer -> graphics($logo);
|
||||
|
||||
/* Name of shop */
|
||||
$printer -> selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
|
||||
$printer -> text("ExampleMart Ltd.\n");
|
||||
$printer -> selectPrintMode();
|
||||
$printer -> text("Shop No. 42.\n");
|
||||
$printer -> feed();
|
||||
|
||||
/* Title of receipt */
|
||||
$printer -> setEmphasis(true);
|
||||
$printer -> text("SALES INVOICE\n");
|
||||
$printer -> setEmphasis(false);
|
||||
|
||||
/* Items */
|
||||
$printer -> setJustification(Printer::JUSTIFY_LEFT);
|
||||
$printer -> setEmphasis(true);
|
||||
$printer -> text(new item('', '$'));
|
||||
$printer -> setEmphasis(false);
|
||||
foreach ($items as $item) {
|
||||
$printer -> text($item);
|
||||
}
|
||||
$printer -> setEmphasis(true);
|
||||
$printer -> text($subtotal);
|
||||
$printer -> setEmphasis(false);
|
||||
$printer -> feed();
|
||||
|
||||
/* Tax and total */
|
||||
$printer -> text($tax);
|
||||
$printer -> selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
|
||||
$printer -> text($total);
|
||||
$printer -> selectPrintMode();
|
||||
|
||||
/* Footer */
|
||||
$printer -> feed(2);
|
||||
$printer -> setJustification(Printer::JUSTIFY_CENTER);
|
||||
$printer -> text("Thank you for shopping at ExampleMart\n");
|
||||
$printer -> text("For trading hours, please visit example.com\n");
|
||||
$printer -> feed(2);
|
||||
$printer -> text($date . "\n");
|
||||
|
||||
/* Cut the receipt and open the cash drawer */
|
||||
$printer -> cut();
|
||||
$printer -> pulse();
|
||||
|
||||
$printer -> close();
|
||||
|
||||
/* A wrapper to do organise item names & prices into columns */
|
||||
class item
|
||||
{
|
||||
private $name;
|
||||
private $price;
|
||||
private $dollarSign;
|
||||
|
||||
public function __construct($name = '', $price = '', $dollarSign = false)
|
||||
{
|
||||
$this -> name = $name;
|
||||
$this -> price = $price;
|
||||
$this -> dollarSign = $dollarSign;
|
||||
}
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
$rightCols = 10;
|
||||
$leftCols = 38;
|
||||
if ($this -> dollarSign) {
|
||||
$leftCols = $leftCols / 2 - $rightCols / 2;
|
||||
}
|
||||
$left = str_pad($this -> name, $leftCols) ;
|
||||
|
||||
$sign = ($this -> dollarSign ? '$ ' : '');
|
||||
$right = str_pad($sign . $this -> price, $rightCols, ' ', STR_PAD_LEFT);
|
||||
return "$left$right\n";
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
/* All strings from EscposPrintBufferTest are included below- These are fully supported
|
||||
* on the default profile, so you can use them to test modified profiles (using the wrong
|
||||
* profile for a printer produces mojibake) */
|
||||
$inputsOk = array(
|
||||
"Danish" => "Quizdeltagerne spiste jordbær med fløde, mens cirkusklovnen Wolther spillede på xylofon.\n",
|
||||
"German" => "Falsches Üben von Xylophonmusik quält jeden größeren Zwerg.\n",
|
||||
"Greek" => "Ξεσκεπάζω την ψυχοφθόρα βδελυγμία\n",
|
||||
"English" => "The quick brown fox jumps over the lazy dog.\n",
|
||||
"Spanish" => "El pingüino Wenceslao hizo kilómetros bajo exhaustiva lluvia y frío, añoraba a su querido cachorro.\n",
|
||||
"French" => "Le cœur déçu mais l'âme plutôt naïve, Louÿs rêva de crapaüter en canoë au delà des îles, près du mälström où brûlent les novæ.\n",
|
||||
"Irish Gaelic" => "D'fhuascail Íosa, Úrmhac na hÓighe Beannaithe, pór Éava agus Ádhaimh.\n",
|
||||
"Hungarian" => "Árvíztűrő tükörfúrógép.\n",
|
||||
"Icelandic" => "Kæmi ný öxi hér ykist þjófum nú bæði víl og ádrepa.\n",
|
||||
"Latvian" => "Glāžšķūņa rūķīši dzērumā čiepj Baha koncertflīģeļu vākus.\n",
|
||||
"Polish" => "Pchnąć w tę łódź jeża lub ośm skrzyń fig.\n",
|
||||
"Russian" => "В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!\n",
|
||||
"Turkish" => "Pijamalı hasta, yağız şoföre çabucak güvendi.\n",
|
||||
"Japanese (Katakana half-width)" => implode("\n", array("イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム", "ウイノオクヤマ ケフコエテ アサキユメミシ エヒモセスン")) . "\n",
|
||||
"Vietnamese" => "Tiếng Việt, còn gọi tiếng Việt Nam hay Việt ngữ, là ngôn ngữ của người Việt (người Kinh) và là ngôn ngữ chính thức tại Việt Nam.\n"
|
||||
);
|
||||
|
||||
/*
|
||||
* These strings are not expected to print correctly, if at all, even on an Epson printer. This is due to a mix of
|
||||
* escpos driver, printer, and PHP language support issues.
|
||||
*
|
||||
* They are included here as a collection of things not yet implemented.
|
||||
*/
|
||||
$inputsNotOk = array(
|
||||
"Thai (No character encoder available)" => "นายสังฆภัณฑ์ เฮงพิทักษ์ฝั่ง ผู้เฒ่าซึ่งมีอาชีพเป็นฅนขายฃวด ถูกตำรวจปฏิบัติการจับฟ้องศาล ฐานลักนาฬิกาคุณหญิงฉัตรชฎา ฌานสมาธิ\n",
|
||||
"Japanese (Hiragana)" => implode("\n", array("いろはにほへとちりぬるを", " わかよたれそつねならむ", "うゐのおくやまけふこえて", "あさきゆめみしゑひもせす")) . "\n",
|
||||
"Japanese (Katakana full-width)" => implode("\n", array("イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム", "ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン")) . "\n",
|
||||
"Arabic (RTL not supported, encoding issues)" => "صِف خَلقَ خَودِ كَمِثلِ الشَمسِ إِذ بَزَغَت — يَحظى الضَجيعُ بِها نَجلاءَ مِعطارِ" . "\n",
|
||||
"Hebrew (RTL not supported, line break issues)" => "דג סקרן שט בים מאוכזב ולפתע מצא לו חברה איך הקליטה" . "\n"
|
||||
);
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 1.9 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 7.7 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.3 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 370 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 5.1 KiB |
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$a = "{A012323392982";
|
||||
$b = "{B012323392982";
|
||||
$c = "{C" . chr(01) . chr(23) . chr(23) . chr(39) . chr(29) . chr(82);
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
$printer -> setJustification(Printer::JUSTIFY_CENTER);
|
||||
$printer -> setBarcodeHeight(48);
|
||||
$printer->setBarcodeTextPosition(Printer::BARCODE_TEXT_BELOW);
|
||||
foreach(array($a, $b, $c) as $item) {
|
||||
$printer -> barcode($item, Printer::BARCODE_CODE128);
|
||||
$printer -> feed(1);
|
||||
}
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
/**
|
||||
* This example shows how to send a custom command to the printer
|
||||
*
|
||||
* "ESC ( B" is the barcode function for Epson LX300 series.
|
||||
* This is not part of standard ESC/POS, but it's a good example
|
||||
* of how to send some binary to the driver.
|
||||
*/
|
||||
|
||||
/* Barcode type is used in this script */
|
||||
const EAN13 = 0;
|
||||
|
||||
/* Barcode properties */
|
||||
$type = EAN13;
|
||||
$content = "0075678164125";
|
||||
|
||||
/*
|
||||
* Make the command.
|
||||
* This is documented on page A-14 of:
|
||||
* https://files.support.epson.com/pdf/lx300p/lx300pu1.pdf
|
||||
*/
|
||||
$m = chr(EAN13);
|
||||
$n = intLowHigh(strlen($content), 2);
|
||||
$barcodeCommand = Printer::ESC . "G(" . $m . $n . $content;
|
||||
|
||||
/* Send it off as usual */
|
||||
$connector = new FilePrintConnector("php://output");
|
||||
$printer = new Printer($connector);
|
||||
$printer->getPrintConnector()->write($barcodeCommand);
|
||||
$printer->cut();
|
||||
$printer->close();
|
||||
|
||||
/**
|
||||
* Generate two characters for a number: In lower and higher parts, or more parts as needed.
|
||||
*
|
||||
* @param int $input
|
||||
* Input number
|
||||
* @param int $length
|
||||
* The number of bytes to output (1 - 4).
|
||||
*/
|
||||
function intLowHigh($input, $length)
|
||||
{
|
||||
$outp = "";
|
||||
for ($i = 0; $i < $length; $i ++) {
|
||||
$outp .= chr($input % 256);
|
||||
$input = (int) ($input / 256);
|
||||
}
|
||||
return $outp;
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
/*
|
||||
* Example of one way you could load a PNG data URI into an EscposImage object
|
||||
* without using a file.
|
||||
*/
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
use Mike42\Escpos\ImagickEscposImage;
|
||||
|
||||
// Data URI for a PNG image (red dot from https://en.wikipedia.org/wiki/Data_URI_scheme )
|
||||
$uri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
|
||||
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
|
||||
9TXL0Y4OHwAAAABJRU5ErkJggg==";
|
||||
|
||||
// Convert data URI to binary data
|
||||
$imageBlob = base64_decode(explode(",", $uri)[1]);
|
||||
|
||||
// Give Imagick a filename with the correct extension to stop it from attempting
|
||||
// to identify the format itself (this avoids CVE-2016–3714)
|
||||
$imagick = new Imagick();
|
||||
$imagick -> setResourceLimit(6, 1); // Prevent libgomp1 segfaults, grumble grumble.
|
||||
$imagick -> readImageBlob($imageBlob, "input.png");
|
||||
|
||||
// Load Imagick straight into an EscposImage object
|
||||
$im = new ImagickEscposImage();
|
||||
$im -> readImageFromImagick($imagick);
|
||||
|
||||
// Do a test print to make sure that this EscposImage object has the right data
|
||||
// (should see a tiny bullet point)
|
||||
$connector = new FilePrintConnector("php://output");
|
||||
$printer = new Printer($connector);
|
||||
$printer -> bitImage($im);
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
/*
|
||||
* Example showing how to return binary data back to the user.
|
||||
*
|
||||
* This is intended for the "Star TSP650IIcloudPRNT" printer.
|
||||
*/
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\DummyPrintConnector;
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
|
||||
// Make sure you load a Star print connector or you may get gibberish.
|
||||
$connector = new DummyPrintConnector();
|
||||
$profile = CapabilityProfile::load("TSP600");
|
||||
$printer = new Printer($connector);
|
||||
$printer -> text("Hello world!\n");
|
||||
$printer -> cut();
|
||||
|
||||
// Get the data out as a string
|
||||
$data = $connector -> getData();
|
||||
|
||||
// Return it, check the manual for specifics.
|
||||
header('Content-type: application/octet-stream');
|
||||
header('Content-Length: '.strlen($data));
|
||||
echo $data;
|
||||
|
||||
// Close the printer when done.
|
||||
$printer -> close();
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
use Mike42\Escpos\PrintBuffers\ImagePrintBuffer;
|
||||
|
||||
/* This example shows the printing of Latvian text on the Star TUP 592 printer */
|
||||
$profile = CapabilityProfile::load("SP2000");
|
||||
|
||||
/* Option 1: Native character encoding */
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector, $profile);
|
||||
$printer -> text("Glāžšķūņa rūķīši dzērumā čiepj Baha koncertflīģeļu vākus\n");
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
|
||||
/* Option 2: Image-based output (formatting not available using this output) */
|
||||
$buffer = new ImagePrintBuffer();
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector, $profile);
|
||||
$printer -> setPrintBuffer($buffer);
|
||||
$printer -> text("Glāžšķūņa rūķīši dzērumā čiepj Baha koncertflīģeļu vākus\n");
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
/*
|
||||
* This example shows how tok send a custom command to the printer-
|
||||
* The use case here is an Epson TM-T20II and German text.
|
||||
*
|
||||
* Background: Not all ESC/POS features are available in the driver, so sometimes
|
||||
* you might want to send a custom commnad. This is useful for testing
|
||||
* new features.
|
||||
*
|
||||
* The Escpos::text() function removes non-printable characters as a precaution,
|
||||
* so that commands cannot be injected into user input. To send raw data to
|
||||
* the printer, you need to write bytes to the underlying PrintConnector.
|
||||
*
|
||||
* If you get a new command working, please file an issue on GitHub with a code
|
||||
* snippet so that it can be incorporated into escpos-php.
|
||||
*/
|
||||
|
||||
/* Set up profile & connector */
|
||||
$connector = new FilePrintConnector("php://output");
|
||||
$profile = CapabilityProfile::load("default"); // Works for Epson printers
|
||||
|
||||
$printer = new Printer($connector, $profile);
|
||||
$cmd = Printer::ESC . "V" . chr(1); // Try out 90-degree rotation.
|
||||
$printer -> getPrintConnector() -> write($cmd);
|
||||
$printer -> text("Beispieltext in Deutsch\n");
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
/*
|
||||
* Hex-dump of output confirms that ESC V 1 being sent:
|
||||
*
|
||||
* 0000000 033 @ 033 V 001 B e i s p i e l t e x
|
||||
* 0000010 t i n D e u t s c h \n 035 V A
|
||||
* 0000020 003
|
||||
*/
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
/*
|
||||
* Example of printing Spanish text on SEYPOS PRP-300 thermal line printer.
|
||||
* The characters in Spanish are available in code page 437, so no special
|
||||
* code pages are needed in this case (SimpleCapabilityProfile).
|
||||
*
|
||||
* Use the hardware switch to activate "Two-byte Character Code"
|
||||
*/
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("php://output");
|
||||
$profile = CapabilityProfile::load("simple"); // Works for Epson printers
|
||||
$printer = new Printer($connector);
|
||||
$printer -> text("El pingüino Wenceslao hizo kilómetros bajo exhaustiva lluvia y frío, añoraba a su querido cachorro.\n");
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
/*
|
||||
* This is an example of printing chinese text. This is a bit different to other character encodings, because
|
||||
* the printer accepts a 2-byte character encoding (GBK), and formatting is handled differently while in this mode.
|
||||
*
|
||||
* At the time of writing, this is implemented separately as a textChinese() function, until chinese text
|
||||
* can be properly detected and printed alongside other encodings.
|
||||
*/
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("/dev/usb/lp1");
|
||||
$profile = CapabilityProfile::load("default");
|
||||
|
||||
$printer = new Printer($connector);
|
||||
|
||||
// Example text from #37
|
||||
$printer -> textChinese("艾德蒙 AOC E2450SWH 23.6吋 LED液晶寬螢幕特價$ 19900\n\n");
|
||||
|
||||
// Note that on the printer tested (ZJ5890), the font only contained simplified characters.
|
||||
$printer -> textChinese("示例文本打印机!\n\n");
|
||||
$printer -> close();
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
use Mike42\Escpos\PrintBuffers\ImagePrintBuffer;
|
||||
|
||||
$profile = CapabilityProfile::load("default");
|
||||
// This is a quick demo of currency symbol issues in #39.
|
||||
|
||||
/* Option 1: Native ESC/POS characters, depends on printer and is buggy. */
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector, $profile);
|
||||
$printer -> text("€ 9,95\n");
|
||||
$printer -> text("£ 9.95\n");
|
||||
$printer -> text("$ 9.95\n");
|
||||
$printer -> text("¥ 9.95\n");
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
|
||||
/* Option 2: Image-based output (formatting not available using this output). */
|
||||
$buffer = new ImagePrintBuffer();
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector, $profile);
|
||||
$printer -> setPrintBuffer($buffer);
|
||||
$printer -> text("€ 9,95\n");
|
||||
$printer -> text("£ 9.95\n");
|
||||
$printer -> text("$ 9.95\n");
|
||||
$printer -> text("¥ 9.95\n");
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
|
||||
/*
|
||||
Option 3: If the printer is configured to print in a specific code
|
||||
page, you can set up a CapabilityProfile which either references its
|
||||
iconv encoding name, or includes all of the available characters.
|
||||
|
||||
Here, we make use of CP858 for its inclusion of currency symbols which
|
||||
are not available in CP437. CP858 has good printer support, but is not
|
||||
included in all iconv builds.
|
||||
*/
|
||||
class CustomCapabilityProfile extends CapabilityProfile
|
||||
{
|
||||
function getCustomCodePages()
|
||||
{
|
||||
/*
|
||||
* Example to print in a specific, user-defined character set
|
||||
* on a printer which has been configured to use i
|
||||
*/
|
||||
return array(
|
||||
'CP858' => "ÇüéâäàåçêëèïîìÄÅ" .
|
||||
"ÉæÆôöòûùÿÖÜø£Ø×ƒ" .
|
||||
"áíóúñѪº¿®¬½¼¡«»" .
|
||||
"░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐" .
|
||||
"└┴┬├─┼ãÃ╚╔╩╦╠═╬¤" .
|
||||
"ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀" .
|
||||
"ÓßÔÒõÕµþÞÚÛÙýݯ´" .
|
||||
" ±‗¾¶§÷¸°¨·¹³²■ ");
|
||||
}
|
||||
|
||||
function getSupportedCodePages()
|
||||
{
|
||||
return array(
|
||||
0 => 'custom:CP858');
|
||||
}
|
||||
}
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$profile = CustomCapabilityProfile::getInstance();
|
||||
$printer = new Printer($connector, $profile);
|
||||
$printer -> text("€ 9,95\n");
|
||||
$printer -> text("£ 9.95\n");
|
||||
$printer -> text("$ 9.95\n");
|
||||
$printer -> text("¥ 9.95\n");
|
||||
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
/* Example of printing the GBP pound symbol on a STAR TSP650
|
||||
*
|
||||
* In this example, it's shown how to check that your PHP files are actually being
|
||||
* saved in unicode. Sections B) and C) are identical in UTF-8, but different
|
||||
* if you are saving to a retro format like Windows-1252.
|
||||
*/
|
||||
|
||||
// Adjust these to your environment
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
|
||||
// Start printer
|
||||
$profile = CapabilityProfile::load("simple");
|
||||
$printer = new Printer($connector, $profile);
|
||||
|
||||
// A) Raw pound symbol
|
||||
// This is the most likely thing to work, and bypasses all the fancy stuff.
|
||||
$printer -> textRaw("\x9C"); // based on position in CP437
|
||||
$printer -> text(" 1.95\n");
|
||||
|
||||
// B) Manually encoded UTF8 pound symbol. Tests that the driver correctly
|
||||
// encodes this as CP437.
|
||||
$printer -> text(base64_decode("wqM=") . " 2.95\n");
|
||||
|
||||
// C) Pasted in file. Tests that your files are being saved as UTF-8, which
|
||||
// escpos-php is able to convert automatically to a mix of code pages.
|
||||
$printer -> text("£ 3.95\n");
|
||||
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
/* Example of Greek text on the P-822D */
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
// Setup the printer
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$profile = CapabilityProfile::load("P822D");
|
||||
$printer = new Printer($connector, $profile);
|
||||
|
||||
// Print a Greek pangram
|
||||
$text = "Ξεσκεπάζω την ψυχοφθόρα βδελυγμία";
|
||||
$printer -> text($text . "\n");
|
||||
$printer -> cut();
|
||||
|
||||
// Close the connection
|
||||
$printer -> close();
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
/*
|
||||
* Example of calling ImageMagick 'convert' to manipulate an image prior to printing.
|
||||
*
|
||||
* Written as an example to remind you to do four things-
|
||||
* - escape your command-line arguments with escapeshellarg
|
||||
* - close the printer
|
||||
* - delete any temp files
|
||||
* - detect and handle external command failure
|
||||
*
|
||||
* Note that image operations are slow. You can and should serialise an EscposImage
|
||||
* object into some sort of cache if you will re-use the output.
|
||||
*/
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\EscposImage;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
// Paths to images to combine
|
||||
$img1_path = dirname(__FILE__) . "/../resources/tux.png";
|
||||
$img2_path = dirname(__FILE__) . "/../resources/escpos-php.png";
|
||||
|
||||
// Set up temp file with .png extension
|
||||
$tmpf_path = tempnam(sys_get_temp_dir(), 'escpos-php');
|
||||
$imgCombined_path = $tmpf_path . ".png";
|
||||
|
||||
try {
|
||||
// Convert, load image, remove temp files
|
||||
$cmd = sprintf(
|
||||
"convert %s %s +append %s",
|
||||
escapeshellarg($img1_path),
|
||||
escapeshellarg($img2_path),
|
||||
escapeshellarg($imgCombined_path)
|
||||
);
|
||||
exec($cmd, $outp, $retval);
|
||||
if ($retval != 0) {
|
||||
// Detect and handle command failure
|
||||
throw new Exception("Command \"$cmd\" returned $retval." . implode("\n", $outp));
|
||||
}
|
||||
$img = EscposImage::load($imgCombined_path);
|
||||
|
||||
// Setup the printer
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$profile = CapabilityProfile::load("default");
|
||||
|
||||
// Run the actual print
|
||||
$printer = new Printer($connector, $profile);
|
||||
try {
|
||||
$printer -> setJustification(Printer::JUSTIFY_CENTER);
|
||||
$printer -> graphics($img);
|
||||
$printer -> cut();
|
||||
} finally {
|
||||
// Always close the connection
|
||||
$printer -> close();
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
// Print out any errors: Eg. printer connection, image loading & external image manipulation.
|
||||
echo $e -> getMessage() . "\n";
|
||||
echo $e -> getTraceAsString();
|
||||
} finally {
|
||||
unlink($imgCombined_path);
|
||||
unlink($tmpf_path);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
/*
|
||||
* This example shows Arabic image-based output on the EPOS TEP 220m.
|
||||
*
|
||||
* Because escpos-php is not yet able to render Arabic correctly
|
||||
* on thermal line printers, small images are generated and sent
|
||||
* instead. This is a bit slower, and only limited formatting
|
||||
* is currently available in this mode.
|
||||
*
|
||||
* Requirements are:
|
||||
* - imagick extension (For the ImagePrintBuffer, which does not
|
||||
* support gd at the time of writing)
|
||||
* - ArPHP 4.0 (release date: Jan 8, 2016), available from SourceForge, for
|
||||
* handling the layout for this example.
|
||||
*/
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
use Mike42\Escpos\PrintBuffers\ImagePrintBuffer;
|
||||
|
||||
/*
|
||||
* Drop Ar-php into the folder listed below:
|
||||
*/
|
||||
require_once(dirname(__FILE__) . "/../../I18N/Arabic.php");
|
||||
$fontPath = dirname(__FILE__) . "/../../I18N/Arabic/Examples/GD/ae_AlHor.ttf";
|
||||
|
||||
/*
|
||||
* Inputs are some text, line wrapping options, and a font size.
|
||||
*/
|
||||
$textUtf8 = "صِف خَلقَ خَودِ كَمِثلِ الشَمسِ إِذ بَزَغَت — يَحظى الضَجيعُ بِها نَجلاءَ مِعطارِ";
|
||||
$maxChars = 50;
|
||||
$fontSize = 28;
|
||||
|
||||
/*
|
||||
* First, convert the text into LTR byte order with line wrapping,
|
||||
* Using the Ar-PHP library.
|
||||
*
|
||||
* The Ar-PHP library uses the default internal encoding, and can print
|
||||
* a lot of errors depending on the input, so be prepared to debug
|
||||
* the next four lines.
|
||||
*
|
||||
* Note that this output shows that numerals are converted to placeholder
|
||||
* characters, indicating that western numerals (123) have to be used instead.
|
||||
*/
|
||||
mb_internal_encoding("UTF-8");
|
||||
$Arabic = new I18N_Arabic('Glyphs');
|
||||
$textLtr = $Arabic -> utf8Glyphs($textUtf8, $maxChars);
|
||||
$textLine = explode("\n", $textLtr);
|
||||
|
||||
/*
|
||||
* Set up and use an image print buffer with a suitable font
|
||||
*/
|
||||
$buffer = new ImagePrintBuffer();
|
||||
$buffer -> setFont($fontPath);
|
||||
$buffer -> setFontSize($fontSize);
|
||||
|
||||
$profile = CapabilityProfile::load("TEP-200M");
|
||||
$connector = new FilePrintConnector("php://output");
|
||||
// = new WindowsPrintConnector("LPT2");
|
||||
// Windows LPT2 was used in the bug tracker
|
||||
|
||||
$printer = new Printer($connector, $profile);
|
||||
$printer -> setPrintBuffer($buffer);
|
||||
|
||||
$printer -> setJustification(Printer::JUSTIFY_RIGHT);
|
||||
foreach($textLine as $text) {
|
||||
// Print each line separately. We need to do this since Imagick thinks
|
||||
// text is left-to-right
|
||||
$printer -> text($text . "\n");
|
||||
}
|
||||
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
use Mike42\Escpos\CapabilityProfile;
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$profile = CapabilityProfile::load("default");
|
||||
$printer = new Printer($connector, $profile);
|
||||
|
||||
$printer -> text("Μιχάλης Νίκος\n");
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
|
||||
?>
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
/*
|
||||
* Example of two-color printing, tested on an epson TM-U220 with two-color ribbon installed.
|
||||
*/
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("/dev/usb/lp0");
|
||||
$printer = new Printer($connector);
|
||||
try {
|
||||
$printer -> text("Hello World!\n");
|
||||
$printer -> setColor(Printer::COLOR_2);
|
||||
$printer -> text("Red?!\n");
|
||||
$printer -> setColor(Printer::COLOR_1);
|
||||
$printer -> text("Default color again?!\n");
|
||||
$printer -> cut();
|
||||
} finally {
|
||||
/* Always close the printer! */
|
||||
$printer -> close();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
/*
|
||||
* Example of dithering used in EscposImage by default, if you have Imagick loaded.
|
||||
*/
|
||||
require __DIR__ . '/../../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\EscposImage;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("/dev/usb/lp0");
|
||||
$printer = new Printer($connector);
|
||||
try {
|
||||
/* Load with optimisations enabled. If you have Imagick, this will get you
|
||||
a nicely dithered image, which prints very quickly
|
||||
*/
|
||||
$img1 = EscposImage::load(__DIR__ . '/../resources/tulips.png');
|
||||
$printer -> bitImage($img1);
|
||||
|
||||
/* Load with optimisations disabled, forcing the use of PHP to convert the
|
||||
pixels, which uses a threshold and is much slower.
|
||||
*/
|
||||
$img2 = EscposImage::load(__DIR__ . '/../resources/tulips.png', false);
|
||||
$printer -> bitImage($img2);
|
||||
$printer -> cut();
|
||||
} finally {
|
||||
/* Always close the printer! */
|
||||
$printer -> close();
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
Specific examples
|
||||
-----------------
|
||||
|
||||
These examples are designed for specific combinations of language,
|
||||
printer and interface.
|
||||
|
||||
They are documented here because the general examples all set up the printer in a similar way.
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
/**
|
||||
* This print-out shows how large the available font sizes are. It is included
|
||||
* separately due to the amount of text it prints.
|
||||
*
|
||||
* @author Michael Billington <michael.billington@gmail.com>
|
||||
*/
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
|
||||
/* Initialize */
|
||||
$printer -> initialize();
|
||||
|
||||
/* Text of various (in-proportion) sizes */
|
||||
title($printer, "Change height & width\n");
|
||||
for ($i = 1; $i <= 8; $i++) {
|
||||
$printer -> setTextSize($i, $i);
|
||||
$printer -> text($i);
|
||||
}
|
||||
$printer -> text("\n");
|
||||
|
||||
/* Width changing only */
|
||||
title($printer, "Change width only (height=4):\n");
|
||||
for ($i = 1; $i <= 8; $i++) {
|
||||
$printer -> setTextSize($i, 4);
|
||||
$printer -> text($i);
|
||||
}
|
||||
$printer -> text("\n");
|
||||
|
||||
/* Height changing only */
|
||||
title($printer, "Change height only (width=4):\n");
|
||||
for ($i = 1; $i <= 8; $i++) {
|
||||
$printer -> setTextSize(4, $i);
|
||||
$printer -> text($i);
|
||||
}
|
||||
$printer -> text("\n");
|
||||
|
||||
/* Very narrow text */
|
||||
title($printer, "Very narrow text:\n");
|
||||
$printer -> setTextSize(1, 8);
|
||||
$printer -> text("The quick brown fox jumps over the lazy dog.\n");
|
||||
|
||||
/* Very flat text */
|
||||
title($printer, "Very wide text:\n");
|
||||
$printer -> setTextSize(4, 1);
|
||||
$printer -> text("Hello world!\n");
|
||||
|
||||
/* Very large text */
|
||||
title($printer, "Largest possible text:\n");
|
||||
$printer -> setTextSize(8, 8);
|
||||
$printer -> text("Hello\nworld!\n");
|
||||
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
|
||||
function title(Printer $printer, $text)
|
||||
{
|
||||
$printer -> selectPrintMode(Printer::MODE_EMPHASIZED);
|
||||
$printer -> text("\n" . $text);
|
||||
$printer -> selectPrintMode(); // Reset
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\Experimental\Unifont\UnifontPrintBuffer;
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
|
||||
// Use Unifont to render text
|
||||
$unifontBuffer = new UnifontPrintBuffer("/usr/share/unifont/unifont.hex");
|
||||
$printer -> setPrintBuffer($unifontBuffer);
|
||||
|
||||
// Most simple example
|
||||
$printer->text("Hello\n");
|
||||
$printer->setUpsideDown(true);
|
||||
$printer->text("World\n");
|
||||
$printer->cut();
|
||||
$printer->close();
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
/* Demonstration of upside-down printing */
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
|
||||
|
||||
$connector = new FilePrintConnector("php://stdout");
|
||||
$printer = new Printer($connector);
|
||||
|
||||
// Most simple example
|
||||
$printer -> text("Hello\n");
|
||||
$printer -> setUpsideDown(true);
|
||||
$printer -> text("World\n");
|
||||
$printer -> cut();
|
||||
$printer -> close();
|
||||
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
<phpunit bootstrap="test/bootstrap.php"
|
||||
timeoutForSmallTests="1"
|
||||
timeoutForMediumTests="10"
|
||||
timeoutForLargeTests="60"
|
||||
verbose="true"
|
||||
|
||||
>
|
||||
<testsuites>
|
||||
<testsuite name="unit">
|
||||
<directory>test/unit</directory>
|
||||
</testsuite>
|
||||
<testsuite name="integration">
|
||||
<directory>test/integration</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
<filter>
|
||||
<whitelist processUncoveredFilesFromWhitelist="true">
|
||||
<directory suffix=".php">src</directory>
|
||||
</whitelist>
|
||||
</filter>
|
||||
</phpunit>
|
||||
@@ -0,0 +1,350 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos;
|
||||
|
||||
use \InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Store compatibility information about one printer.
|
||||
*/
|
||||
class CapabilityProfile
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
* @var string $codePageCacheKey
|
||||
* Hash of the code page data structure, to identify it for caching.
|
||||
*/
|
||||
protected $codePageCacheKey;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var array $codePages
|
||||
* Associtive array of CodePage objects, indicating which encodings the printer supports.
|
||||
*/
|
||||
protected $codePages;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var array $colors
|
||||
* Not used.
|
||||
*/
|
||||
protected $colors;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var array $features
|
||||
* Feature values.
|
||||
*/
|
||||
protected $features;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var array $fonts
|
||||
* Not used
|
||||
*/
|
||||
protected $fonts;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var array $media
|
||||
* Not used
|
||||
*/
|
||||
protected $media;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var string $name
|
||||
* Name of the profile, including model number.
|
||||
*/
|
||||
protected $name;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var string $notes
|
||||
* Notes on the profile, null if not set.
|
||||
*/
|
||||
protected $notes;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var string $profileId
|
||||
* ID of the profile.
|
||||
*/
|
||||
protected $profileId;
|
||||
|
||||
|
||||
/**
|
||||
* @var string $vendor
|
||||
* Name of manufacturer.
|
||||
*/
|
||||
protected $vendor;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var array $encodings
|
||||
* Data structure containing encodings loaded from disk, null if not loaded yet.
|
||||
*/
|
||||
protected static $encodings = null;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var array $profiles
|
||||
* Data structure containing profiles loaded from disk, null if not loaded yet.
|
||||
*/
|
||||
protected static $profiles = null;
|
||||
|
||||
/**
|
||||
* Construct new CapabilityProfile.
|
||||
* The encoding data must be loaded from disk before calling.
|
||||
*
|
||||
* @param string $profileId
|
||||
* ID of the profile
|
||||
* @param array $profileData
|
||||
* Profile data from disk.
|
||||
*/
|
||||
protected function __construct(string $profileId, array $profileData)
|
||||
{
|
||||
// Basic primitive fields
|
||||
$this->profileId = $profileId;
|
||||
$this->name = $profileData['name'];
|
||||
$this->notes = $profileData['notes'];
|
||||
$this->vendor = $profileData['vendor'];
|
||||
// More complex fields that are not currently loaded into custom objects
|
||||
$this->features = $profileData['features'];
|
||||
$this->colors = $profileData['colors'];
|
||||
$this->fonts = $profileData['fonts'];
|
||||
$this->media = $profileData['media'];
|
||||
// More complex fields that are loaded into custom objects
|
||||
$this->codePages = [];
|
||||
$this->codePageCacheKey = md5(json_encode($profileData['codePages']));
|
||||
foreach ($profileData['codePages'] as $k => $v) {
|
||||
$this->codePages[$k] = new CodePage($v, self::$encodings[$v]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return string Hash of the code page data structure, to identify it for caching.
|
||||
*/
|
||||
public function getCodePageCacheKey() : string
|
||||
{
|
||||
return $this->codePageCacheKey;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return array Associative array of CodePage objects, indicating which encodings the printer supports.
|
||||
*/
|
||||
public function getCodePages() : array
|
||||
{
|
||||
return $this->codePages;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param string $featureName
|
||||
* Name of the feature to retrieve.
|
||||
* @throws \InvalidArgumentException Where the feature does not exist.
|
||||
* The exception will contain suggestions for the closest-named features.
|
||||
* @return mixed feature value.
|
||||
*/
|
||||
public function getFeature($featureName)
|
||||
{
|
||||
if (isset($this->features[$featureName])) {
|
||||
return $this->features[$featureName];
|
||||
}
|
||||
$suggestionsArr = $this->suggestFeatureName($featureName);
|
||||
$suggestionsStr = implode(", ", $suggestionsArr);
|
||||
$str = "The feature '$featureName' does not exist. Try one that does exist, such as $suggestionsStr";
|
||||
throw new \InvalidArgumentException($str);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return string ID of the profile.
|
||||
*/
|
||||
public function getId() : string
|
||||
{
|
||||
return $this->profileId;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return string Name of the printer.
|
||||
*/
|
||||
public function getName() : string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return boolean True if Barcode B command is supported, false otherwise
|
||||
*/
|
||||
public function getSupportsBarcodeB() : bool
|
||||
{
|
||||
return $this->getFeature('barcodeB') === true;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return boolean True if Bit Image Raster command is supported, false otherwise
|
||||
*/
|
||||
public function getSupportsBitImageRaster() : bool
|
||||
{
|
||||
return $this->getFeature('bitImageRaster') === true;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return boolean True if Graphics command is supported, false otherwise
|
||||
*/
|
||||
public function getSupportsGraphics() : bool
|
||||
{
|
||||
return $this->getFeature('graphics') === true;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return boolean True if PDF417 code command is supported, false otherwise
|
||||
*/
|
||||
public function getSupportsPdf417Code() : bool
|
||||
{
|
||||
return $this->getFeature('pdf417Code') === true;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return boolean True if QR code command is supported, false otherwise
|
||||
*/
|
||||
public function getSupportsQrCode(): bool
|
||||
{
|
||||
return $this->getFeature('qrCode') === true;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return boolean True if Star mode commands are supported, false otherwise
|
||||
*/
|
||||
public function getSupportsStarCommands(): bool
|
||||
{
|
||||
return $this->getFeature('starCommands') === true;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return string Vendor of this printer.
|
||||
*/
|
||||
public function getVendor() : string
|
||||
{
|
||||
return $this->vendor;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param string $featureName
|
||||
* Feature that does not exist
|
||||
* @return array Three most similar feature names that do exist.
|
||||
*/
|
||||
protected function suggestFeatureName(string $featureName) : array
|
||||
{
|
||||
return self::suggestNearest($featureName, array_keys($this->features), 3);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return array Names of all profiles that exist.
|
||||
*/
|
||||
public static function getProfileNames() : array
|
||||
{
|
||||
self::loadCapabilitiesDataFile();
|
||||
return array_keys(self::$profiles);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the CapabilityProfile with the given ID.
|
||||
*
|
||||
* @param string $profileName
|
||||
* The ID of the profile to load.
|
||||
* @throws InvalidArgumentException Where the ID does not exist. Some similarly-named profiles will be suggested in the Exception text.
|
||||
* @return CapabilityProfile The CapabilityProfile that was requested.
|
||||
*/
|
||||
public static function load(string $profileName)
|
||||
{
|
||||
self::loadCapabilitiesDataFile();
|
||||
if (! isset(self::$profiles[$profileName])) {
|
||||
$suggestionsArray = self::suggestProfileName($profileName);
|
||||
$suggestionsStr = implode(", ", $suggestionsArray);
|
||||
throw new InvalidArgumentException("The CapabilityProfile '$profileName' does not exist. Try one that does exist, such as $suggestionsStr.");
|
||||
}
|
||||
return new CapabilityProfile($profileName, self::$profiles[$profileName]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure that the capabilities.json data file has been loaded.
|
||||
*/
|
||||
protected static function loadCapabilitiesDataFile()
|
||||
{
|
||||
if (self::$profiles === null) {
|
||||
$filename = dirname(__FILE__) . "/resources/capabilities.json";
|
||||
$capabilitiesData = json_decode(file_get_contents($filename), true);
|
||||
self::$profiles = $capabilitiesData['profiles'];
|
||||
self::$encodings = $capabilitiesData['encodings'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return choices with smallest edit distance to an invalid input.
|
||||
*
|
||||
* @param string $input
|
||||
* Input that is not a valid choice
|
||||
* @param array $choices
|
||||
* Array of valid choices.
|
||||
* @param int $num
|
||||
* Number of suggestions to return
|
||||
*/
|
||||
public static function suggestNearest(string $input, array $choices, int $num) : array
|
||||
{
|
||||
$distances = array_fill_keys($choices, PHP_INT_MAX);
|
||||
foreach ($distances as $word => $_) {
|
||||
$distances[$word] = levenshtein($input, $word);
|
||||
}
|
||||
asort($distances);
|
||||
return array_slice(array_keys($distances), 0, min($num, count($choices)));
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param string $profileName
|
||||
* profile name that does not exist
|
||||
* @return array Three similar profile names that do exist, plus 'simple' and 'default' for good measure.
|
||||
*/
|
||||
protected static function suggestProfileName(string $profileName) : array
|
||||
{
|
||||
$suggestions = self::suggestNearest($profileName, array_keys(self::$profiles), 3);
|
||||
$alwaysSuggest = [
|
||||
'simple',
|
||||
'default'
|
||||
];
|
||||
foreach ($alwaysSuggest as $item) {
|
||||
if (array_search($item, $suggestions) === false) {
|
||||
array_push($suggestions, $item);
|
||||
}
|
||||
}
|
||||
return $suggestions;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
<?php declare(strict_types=1);
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
namespace Mike42\Escpos;
|
||||
|
||||
use \InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Class to handle data about a particular CodePage, as loaded from the receipt print
|
||||
* database.
|
||||
*
|
||||
* Also computes map between UTF-8 and this encoding if necessary, using the intl library.
|
||||
*/
|
||||
class CodePage
|
||||
{
|
||||
/**
|
||||
* Value to use when no character is set. This is a space in ASCII.
|
||||
*/
|
||||
const MISSING_CHAR_CODE = 0x20;
|
||||
|
||||
/**
|
||||
* @var array|null $data
|
||||
* Data string, null if not known (can be computed with iconv)
|
||||
*/
|
||||
protected $data;
|
||||
|
||||
/**
|
||||
* @var string|null $iconv
|
||||
* Iconv encoding name, null if not known
|
||||
*/
|
||||
protected $iconv;
|
||||
|
||||
/**
|
||||
* @var string $id
|
||||
* Internal ID of the CodePage
|
||||
*/
|
||||
protected $id;
|
||||
|
||||
/**
|
||||
* @var string $name
|
||||
* Name of the code page. Substituted with the ID if not set.
|
||||
*/
|
||||
protected $name;
|
||||
|
||||
/**
|
||||
* @var string|null $notes
|
||||
* Notes on this code page, or null if not set.
|
||||
*/
|
||||
protected $notes;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param string $id
|
||||
* Unique internal identifier for the CodePage.
|
||||
* @param array $codePageData
|
||||
* Associative array of CodePage data, as
|
||||
* specified by the upstream receipt-print-hq/escpos-printer-db database.
|
||||
* May contain 'name', 'data', 'iconv', and 'notes' fields.
|
||||
*/
|
||||
public function __construct($id, array $codePageData)
|
||||
{
|
||||
$this->id = $id;
|
||||
$this->name = isset($codePageData['name']) ? $codePageData['name'] : $id;
|
||||
$this->data = isset($codePageData['data']) ? self::encodingArrayFromData($codePageData['data']) : null;
|
||||
$this->iconv = isset($codePageData['iconv']) ? $codePageData['iconv'] : null;
|
||||
$this->notes = isset($codePageData['notes']) ? $codePageData['notes'] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a 128-entry array of unicode code-points from this code page.
|
||||
*
|
||||
* @throws InvalidArgumentException Where the data is now known or computable.
|
||||
* @return array Data for this encoding.
|
||||
*/
|
||||
public function getDataArray() : array
|
||||
{
|
||||
// Make string
|
||||
if ($this->data !== null) {
|
||||
// Return data if known
|
||||
return $this->data;
|
||||
}
|
||||
if ($this->iconv !== null) {
|
||||
// Calculate with iconv if we know the encoding name
|
||||
$this->data = self::generateEncodingArray($this->iconv);
|
||||
return $this->data;
|
||||
}
|
||||
// Can't encode..
|
||||
throw new InvalidArgumentException("Cannot encode this code page");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return string|null Iconv encoding name, or null if not set.
|
||||
*/
|
||||
public function getIconv()
|
||||
{
|
||||
return $this->iconv;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return string Unique identifier of the code page.
|
||||
*/
|
||||
public function getId() : string
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string Name of the code page.
|
||||
*/
|
||||
public function getName() : string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* The notes may explain quirks about a code-page, such as a source if it's non-standard or un-encodeable.
|
||||
*
|
||||
* @return string|null Notes on the code page, or null if not set.
|
||||
*/
|
||||
public function getNotes()
|
||||
{
|
||||
return $this->notes;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return boolean True if we can encode with this code page (ie, we know what data it holds).
|
||||
*
|
||||
* Many printers contain vendor-specific code pages, which are named but have not been identified or
|
||||
* typed out. For our purposes, this is an "un-encodeable" code page.
|
||||
*/
|
||||
public function isEncodable()
|
||||
{
|
||||
return $this->iconv !== null || $this->data !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an ICU encoding name, generate a 128-entry array, with the unicode code points
|
||||
* for the character at positions 128-255 in this code page.
|
||||
*
|
||||
* @param string $encodingName Name of the encoding
|
||||
* @return array 128-entry array of code points
|
||||
*/
|
||||
protected static function generateEncodingArray(string $encodingName) : array
|
||||
{
|
||||
// Set up converter for encoding
|
||||
$missingChar = chr(self::MISSING_CHAR_CODE);
|
||||
// Throws a lot of warnings for ambiguous code pages, but fallbacks seem fine.
|
||||
$converter = @new \UConverter("UTF-8", $encodingName);
|
||||
$converter -> setSubstChars($missingChar);
|
||||
// Loop through 128 code points
|
||||
$intArray = array_fill(0, 128, self::MISSING_CHAR_CODE);
|
||||
for ($char = 128; $char <= 255; $char++) {
|
||||
// Try to identify the UTF-8 character at this position in the code page
|
||||
$encodingChar = chr($char);
|
||||
$utf8 = $converter ->convert($encodingChar, false);
|
||||
if ($utf8 === $missingChar || $utf8 === false) {
|
||||
// Cannot be mapped to unicode
|
||||
continue;
|
||||
}
|
||||
$reverse = $converter ->convert($utf8, true);
|
||||
if ($reverse !== $encodingChar) {
|
||||
// Avoid conversions which don't reverse well (eg. multi-byte code pages)
|
||||
continue;
|
||||
}
|
||||
// Replace space with the correct character if we found it
|
||||
$intArray[$char - 128] = \IntlChar::ord($utf8);
|
||||
}
|
||||
assert(count($intArray) == 128);
|
||||
return $intArray;
|
||||
}
|
||||
|
||||
|
||||
private static function encodingArrayFromData(array $data) : array
|
||||
{
|
||||
$text = implode("", $data); // Join lines
|
||||
$codePointIterator = \IntlBreakIterator::createCodePointInstance();
|
||||
$codePointIterator -> setText($text);
|
||||
$ret = array_fill(0, 128, self::MISSING_CHAR_CODE);
|
||||
for ($i = 0; ($codePointIterator -> next() > 0) && ($i < 128); $i++) {
|
||||
$codePoint = $codePointIterator -> getLastCodePoint();
|
||||
$ret[$i] = $codePoint;
|
||||
}
|
||||
assert(count($ret) == 128);
|
||||
return $ret;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\Devices;
|
||||
|
||||
use Mike42\Escpos\Printer;
|
||||
|
||||
/**
|
||||
* A class for sending ESC/POS-like code to an Aures customer display.
|
||||
* The display has some features that printers do not, such as an ability to "clear" the screen.
|
||||
*/
|
||||
class AuresCustomerDisplay extends Printer
|
||||
{
|
||||
|
||||
/**
|
||||
* Indicates that the text should wrap and type over
|
||||
* existing text on the screen, rather than scroll.
|
||||
*/
|
||||
const TEXT_OVERWRITE = 1;
|
||||
|
||||
/**
|
||||
* Indicates that overflowing text should cause the
|
||||
* display to scroll vertically, like a computer terminal.
|
||||
*/
|
||||
const TEXT_VERTICAL_SCROLL = 2;
|
||||
|
||||
/**
|
||||
* Indicates that overflowing text should cause the
|
||||
* display to scroll horizontally, like a news ticker.
|
||||
*/
|
||||
const TEXT_HORIZONTAL_SCROLL = 3;
|
||||
|
||||
/**
|
||||
*
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @see \Mike42\Escpos\Printer::initialize()
|
||||
*/
|
||||
public function initialize()
|
||||
{
|
||||
// Select ESC/POS mode first
|
||||
$this->selectEscposMode();
|
||||
parent::initialize();
|
||||
// ESC @ does not reset character table on this printer
|
||||
$this->selectCharacterTable(0);
|
||||
// Default to horizontal scroll mode. Behaves most like a printer.
|
||||
$this->selectTextScrollMode(AuresCustomerDisplay::TEXT_VERTICAL_SCROLL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects ESC/POS mode.
|
||||
*
|
||||
* This device supports other modes, which are not used.
|
||||
*/
|
||||
protected function selectEscposMode()
|
||||
{
|
||||
$this->connector->write("\x02\x05\x43\x31\x03");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param int $mode
|
||||
* The text scroll mode to use. One of
|
||||
* AuresCustomerDisplay::TEXT_OVERWRITE,
|
||||
* AuresCustomerDisplay::TEXT_VERTICAL_SCROLL or
|
||||
* AuresCustomerDisplay::TEXT_HORIZONTAL_SCROLL
|
||||
*/
|
||||
public function selectTextScrollMode(int $mode = AuresCustomerDisplay::TEXT_VERTICAL_SCROLL)
|
||||
{
|
||||
self::validateInteger($mode, 1, 3, __FUNCTION__);
|
||||
$this->connector->write("\x1F" . chr($mode));
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the display.
|
||||
*/
|
||||
public function clear()
|
||||
{
|
||||
$this->connector->write("\x0c");
|
||||
}
|
||||
|
||||
/**
|
||||
* Instruct the display to show the firmware version.
|
||||
*/
|
||||
public function showFirmwareVersion()
|
||||
{
|
||||
$this->connector->write("\x02\x05\x56\x01\x03");
|
||||
}
|
||||
|
||||
/**
|
||||
* Instruct the display to begin a self-test/demo sequence.
|
||||
*/
|
||||
public function selfTest()
|
||||
{
|
||||
$this->connector->write("\x02\x05\x44\x08\x03");
|
||||
}
|
||||
|
||||
/**
|
||||
* Instruct the display to show a pre-loaded logo.
|
||||
*
|
||||
* Note that this driver is not capable of uploading a
|
||||
* logo, but that the vendor supplies software
|
||||
* which has this function.
|
||||
*/
|
||||
public function showLogo()
|
||||
{
|
||||
$this->connector->write("\x02\xFC\x55\xAA\x55\xAA");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @see \Mike42\Escpos\Printer::text()
|
||||
*/
|
||||
public function text(string $str)
|
||||
{
|
||||
// Need to intercept line-feeds, since "\n" is insufficient on this device.
|
||||
foreach (explode("\n", $str) as $id => $line) {
|
||||
if ($id > 0) {
|
||||
$this->feed();
|
||||
}
|
||||
parent::text($line);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @see \Mike42\Escpos\Printer::feed()
|
||||
*/
|
||||
public function feed(int $lines = 1)
|
||||
{
|
||||
self::validateInteger($lines, 1, 255, __FUNCTION__);
|
||||
for ($i = 0; $i < $lines; $i ++) {
|
||||
$this->connector->write("\r\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos;
|
||||
|
||||
use Exception;
|
||||
use InvalidArgumentException;
|
||||
use Mike42\Escpos\GdEscposImage;
|
||||
use Mike42\Escpos\ImagickEscposImage;
|
||||
use Mike42\Escpos\NativeEscposImage;
|
||||
|
||||
/**
|
||||
* This class deals with images in raster formats, and converts them into formats
|
||||
* which are suitable for use on thermal receipt printers. Currently, only PNG
|
||||
* images (in) and ESC/POS raster format (out) are implemeted.
|
||||
*
|
||||
* Input formats:
|
||||
* - Currently, only PNG is supported.
|
||||
* - Other easily read raster formats (jpg, gif) will be added at a later date, as this is not complex.
|
||||
* - The BMP format can be directly read by some commands, but this has not yet been implemented.
|
||||
*
|
||||
* Output formats:
|
||||
* - Currently, only ESC/POS raster format is supported
|
||||
* - ESC/POS 'column format' support is partially implemented, but is not yet used by Escpos.php library.
|
||||
* - Output as multiple rows of column format image is not yet in the works.
|
||||
*
|
||||
* Libraries:
|
||||
* - Currently, php-gd is used to read the input. Support for imagemagick where gd is not installed is
|
||||
* also not complex to add, and is a likely future feature.
|
||||
* - Support for native use of the BMP format is a goal, for maximum compatibility with target environments.
|
||||
*/
|
||||
abstract class EscposImage
|
||||
{
|
||||
/**
|
||||
* @var int $imgHeight
|
||||
* height of the image.
|
||||
*/
|
||||
protected $imgHeight = 0;
|
||||
|
||||
/**
|
||||
* @var int $imgWidth
|
||||
* width of the image
|
||||
*/
|
||||
protected $imgWidth = 0;
|
||||
|
||||
/**
|
||||
* @var string $imgData
|
||||
* Image data in rows: 1 for black, 0 for white.
|
||||
*/
|
||||
private $imgData = null;
|
||||
|
||||
/**
|
||||
* @var array:string $imgColumnData
|
||||
* Cached column-format data to avoid re-computation
|
||||
*/
|
||||
private $imgColumnData = [];
|
||||
|
||||
/**
|
||||
* @var string $imgRasterData
|
||||
* Cached raster format data to avoid re-computation
|
||||
*/
|
||||
private $imgRasterData = null;
|
||||
|
||||
/**
|
||||
* @var string $filename
|
||||
* Filename of image on disk - null if not loaded from disk.
|
||||
*/
|
||||
private $filename = null;
|
||||
|
||||
/**
|
||||
* @var boolean $allowOptimisations
|
||||
* True to allow faster library-specific rendering shortcuts, false to always just use
|
||||
* image libraries to read pixels (more reproducible between systems).
|
||||
*/
|
||||
private $allowOptimisations = true;
|
||||
|
||||
/**
|
||||
* Construct a new EscposImage.
|
||||
*
|
||||
* @param string $filename Path to image filename, or null to create an empty image.
|
||||
* @param boolean $allowOptimisations True (default) to use any library-specific tricks
|
||||
* to speed up rendering, false to force the image to be read in pixel-by-pixel,
|
||||
* which is easier to unit test and more reproducible between systems, but slower.
|
||||
*/
|
||||
public function __construct($filename = null, $allowOptimisations = true)
|
||||
{
|
||||
$this -> filename = $filename;
|
||||
$this -> allowOptimisations = $allowOptimisations;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int height of the image in pixels
|
||||
*/
|
||||
public function getHeight()
|
||||
{
|
||||
return $this -> imgHeight;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int Number of bytes to represent a row of this image
|
||||
*/
|
||||
public function getHeightBytes()
|
||||
{
|
||||
return (int)(($this -> imgHeight + 7) / 8);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int Width of the image
|
||||
*/
|
||||
public function getWidth()
|
||||
{
|
||||
return $this -> imgWidth;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int Number of bytes to represent a row of this image
|
||||
*/
|
||||
public function getWidthBytes()
|
||||
{
|
||||
return (int)(($this -> imgWidth + 7) / 8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Output the image in raster (row) format. This can result in padding on the
|
||||
* right of the image, if its width is not divisible by 8.
|
||||
*
|
||||
* @throws Exception Where the generated data is unsuitable for the printer
|
||||
* (indicates a bug or oversized image).
|
||||
* @return string The image in raster format.
|
||||
*/
|
||||
public function toRasterFormat()
|
||||
{
|
||||
// Just wraps implementations for caching & lazy loading
|
||||
if ($this -> imgRasterData !== null) {
|
||||
/* Return cached value */
|
||||
return $this -> imgRasterData;
|
||||
}
|
||||
if ($this -> allowOptimisations) {
|
||||
/* Use optimised code if allowed */
|
||||
$this -> imgRasterData = $this -> getRasterFormatFromFile($this -> filename);
|
||||
}
|
||||
if ($this -> imgRasterData === null) {
|
||||
/* Load in full image and render the slow way if no faster implementation
|
||||
is available, or if we've been asked not to use it */
|
||||
if ($this -> imgData === null) {
|
||||
$this -> loadImageData($this -> filename);
|
||||
}
|
||||
$this -> imgRasterData = $this -> getRasterFormat();
|
||||
}
|
||||
return $this -> imgRasterData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Output the image in column format.
|
||||
*
|
||||
* @param boolean $doubleDensity True for double density (24px) lines, false for single-density (8px) lines.
|
||||
* @return string[] an array, one item per line of output. All lines will be of equal size.
|
||||
*/
|
||||
public function toColumnFormat($doubleDensity = false)
|
||||
{
|
||||
$densityIdx = $doubleDensity ? 1 : 0;
|
||||
// Just wraps implementations for caching and lazy loading
|
||||
if (isset($this -> imgColumnData[$densityIdx])) {
|
||||
/* Return cached value */
|
||||
return $this -> imgColumnData[$densityIdx];
|
||||
}
|
||||
$this -> imgColumnData[$densityIdx] = null;
|
||||
if ($this -> allowOptimisations) {
|
||||
/* Use optimised code if allowed */
|
||||
$data = $this -> getColumnFormatFromFile($this -> filename, $doubleDensity);
|
||||
$this -> imgColumnData[$densityIdx] = $data;
|
||||
}
|
||||
if ($this -> imgColumnData[$densityIdx] === null) {
|
||||
/* Load in full image and render the slow way if no faster implementation
|
||||
is available, or if we've been asked not to use it */
|
||||
if ($this -> imgData === null) {
|
||||
$this -> loadImageData($this -> filename);
|
||||
}
|
||||
$this -> imgColumnData[$densityIdx] = $this -> getColumnFormat($doubleDensity);
|
||||
}
|
||||
return $this -> imgColumnData[$densityIdx];
|
||||
}
|
||||
|
||||
/**
|
||||
* Load an image from disk. This default implementation always gives a zero-sized image.
|
||||
*
|
||||
* @param string|null $filename Filename to load from.
|
||||
*/
|
||||
protected function loadImageData(string $filename = null)
|
||||
{
|
||||
// Load image in to string of 1's and 0's, also set width & height
|
||||
$this -> setImgWidth(0);
|
||||
$this -> setImgHeight(0);
|
||||
$this -> setImgData("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Set image data.
|
||||
*
|
||||
* @param string $data Image data to use, string of 1's (black) and 0's (white) in row-major order.
|
||||
*/
|
||||
protected function setImgData($data)
|
||||
{
|
||||
$this -> imgData = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set image width.
|
||||
*
|
||||
* @param int $width width of the image
|
||||
*/
|
||||
protected function setImgWidth($width)
|
||||
{
|
||||
$this -> imgWidth = $width;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set image height.
|
||||
*
|
||||
* @param int $height height of the image.
|
||||
*/
|
||||
protected function setImgHeight($height)
|
||||
{
|
||||
$this -> imgHeight = $height;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $filename
|
||||
* Filename to load from
|
||||
* @return string|NULL
|
||||
* Raster format data, or NULL if no optimised renderer is available in
|
||||
* this implementation.
|
||||
*/
|
||||
protected function getRasterFormatFromFile($filename = null)
|
||||
{
|
||||
// No optimised implementation to provide
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $filename
|
||||
* Filename to load from
|
||||
* @param boolean $highDensityVertical
|
||||
* True for high density output (24px lines), false for regular density (8px)
|
||||
* @return string[]|NULL
|
||||
* Column format data as array, or NULL if optimised renderer isn't
|
||||
* available in this implementation.
|
||||
*/
|
||||
protected function getColumnFormatFromFile($filename = null, $highDensityVertical = true)
|
||||
{
|
||||
// No optimised implementation to provide
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get column fromat from loaded image pixels, line by line.
|
||||
*
|
||||
* @throws Exception
|
||||
* Where wrong number of bytes has been generated.
|
||||
* @return string
|
||||
* Raster format data
|
||||
*/
|
||||
private function getRasterFormat()
|
||||
{
|
||||
/* Loop through and convert format */
|
||||
$widthPixels = $this -> getWidth();
|
||||
$heightPixels = $this -> getHeight();
|
||||
$widthBytes = $this -> getWidthBytes();
|
||||
$heightBytes = $this -> getHeightBytes();
|
||||
$x = $y = $bit = $byte = $byteVal = 0;
|
||||
$data = str_repeat("\0", $widthBytes * $heightPixels);
|
||||
if (strlen($data) == 0) {
|
||||
return $data;
|
||||
}
|
||||
do {
|
||||
$byteVal |= (int)$this -> imgData[$y * $widthPixels + $x] << (7 - $bit);
|
||||
$x++;
|
||||
$bit++;
|
||||
if ($x >= $widthPixels) {
|
||||
$x = 0;
|
||||
$y++;
|
||||
$bit = 8;
|
||||
if ($y >= $heightPixels) {
|
||||
$data[$byte] = chr($byteVal);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($bit >= 8) {
|
||||
$data[$byte] = chr($byteVal);
|
||||
$byteVal = 0;
|
||||
$bit = 0;
|
||||
$byte++;
|
||||
}
|
||||
} while (true);
|
||||
if (strlen($data) != ($this -> getWidthBytes() * $this -> getHeight())) {
|
||||
throw new Exception("Bug in " . __FUNCTION__ . ", wrong number of bytes.");
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get column fromat from loaded image pixels, line by line.
|
||||
*
|
||||
* @param boolean $highDensity
|
||||
* True for high density output (24px lines), false for regular density (8px)
|
||||
* @return string[]
|
||||
* Array of column format data, one item per row.
|
||||
*/
|
||||
private function getColumnFormat(bool $highDensity)
|
||||
{
|
||||
$out = [];
|
||||
$i = 0;
|
||||
while (($line = $this -> getColumnFormatLine($i, $highDensity)) !== null) {
|
||||
$out[] = $line;
|
||||
$i++;
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Output image in column format. Must be called once for each line of output.
|
||||
*
|
||||
* @param int $lineNo
|
||||
* Line number to retrieve
|
||||
* @param bool $highDensity
|
||||
* True for high density output (24px lines), false for regular density (8px)
|
||||
* @throws Exception
|
||||
* Where wrong number of bytes has been generated.
|
||||
* @return NULL|string
|
||||
* Column format data, or null if there is no more data (when iterating)
|
||||
*/
|
||||
private function getColumnFormatLine(int $lineNo, bool $highDensity)
|
||||
{
|
||||
// Currently double density in both directions, very experimental
|
||||
$widthPixels = $this -> getWidth();
|
||||
$heightPixels = $this -> getHeight();
|
||||
$widthBytes = $this -> getWidthBytes();
|
||||
$heightBytes = $this -> getHeightBytes();
|
||||
$lineHeight = $highDensity ? 3 : 1; // Vertical density. 1 or 3 (for 8 and 24 pixel lines)
|
||||
// Initialise to zero
|
||||
$x = $y = $bit = $byte = $byteVal = 0;
|
||||
$data = str_repeat("\x00", $widthPixels * $lineHeight);
|
||||
$yStart = $lineHeight * 8 * $lineNo;
|
||||
if ($yStart >= $heightPixels) {
|
||||
return null;
|
||||
}
|
||||
if (strlen($data) == 0) {
|
||||
return $data;
|
||||
}
|
||||
do {
|
||||
$yReal = $y + $yStart;
|
||||
if ($yReal < $heightPixels) {
|
||||
$byteVal |= (int)$this -> imgData[$yReal * $widthPixels + $x] << (7 - $bit);
|
||||
}
|
||||
$y++;
|
||||
$bit++;
|
||||
if ($y >= $lineHeight * 8) {
|
||||
$y = 0;
|
||||
$x++;
|
||||
$bit = 8;
|
||||
if ($x >= $widthPixels) {
|
||||
$data[$byte] = chr($byteVal);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($bit >= 8) {
|
||||
$data[$byte] = chr($byteVal);
|
||||
$byteVal = 0;
|
||||
$bit = 0;
|
||||
$byte++;
|
||||
}
|
||||
} while (true);
|
||||
if (strlen($data) != $widthPixels * $lineHeight) {
|
||||
throw new Exception("Bug in " . __FUNCTION__ . ", wrong number of bytes.");
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean True if GD is loaded, false otherwise
|
||||
*/
|
||||
public static function isGdLoaded()
|
||||
{
|
||||
return extension_loaded('gd');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean True if Imagick is loaded, false otherwise
|
||||
*/
|
||||
public static function isImagickLoaded()
|
||||
{
|
||||
return extension_loaded('imagick');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This is a convinience method to load an image from file, auto-selecting
|
||||
* an EscposImage implementation which uses an available library.
|
||||
*
|
||||
* The sub-classes can be constructed directly if you know that you will
|
||||
* have Imagick or GD on the print server.
|
||||
*
|
||||
* @param string $filename
|
||||
* File to load from
|
||||
* @param bool $allowOptimisations
|
||||
* True to allow the fastest rendering shortcuts, false to force the library
|
||||
* to read the image into an internal raster format and use PHP to render
|
||||
* the image (slower but less fragile).
|
||||
* @param array $preferred
|
||||
* Order to try to load libraries in- escpos-php supports pluggable image
|
||||
* libraries. Items can be 'imagick', 'gd', 'native'.
|
||||
* @throws Exception
|
||||
* Where no suitable library could be found for the type of file being loaded.
|
||||
* @return EscposImage
|
||||
*
|
||||
*/
|
||||
public static function load(
|
||||
string $filename,
|
||||
bool $allowOptimisations = true,
|
||||
array $preferred = ['imagick', 'gd', 'native']
|
||||
) {
|
||||
/* Fail early if file is not readble */
|
||||
if (!file_exists($filename) || !is_readable($filename)) {
|
||||
throw new Exception("File '$filename' does not exist, or is not readable.");
|
||||
}
|
||||
$ext = pathinfo($filename, PATHINFO_EXTENSION);
|
||||
/* Choose the first implementation which can handle this format */
|
||||
foreach ($preferred as $implementation) {
|
||||
if ($implementation === 'imagick') {
|
||||
if (!self::isImagickLoaded()) {
|
||||
// Skip option if Imagick is not loaded
|
||||
continue;
|
||||
}
|
||||
return new ImagickEscposImage($filename, $allowOptimisations);
|
||||
} elseif ($implementation === 'gd') {
|
||||
if (!self::isGdLoaded()) {
|
||||
// Skip option if GD not loaded
|
||||
continue;
|
||||
}
|
||||
return new GdEscposImage($filename, $allowOptimisations);
|
||||
} elseif ($implementation === 'native') {
|
||||
if (!in_array($ext, ['bmp', 'gif', 'pbm', 'png', 'ppm', 'pgm', 'wbmp'])) {
|
||||
// Pure PHP may also be fastest way to generate raster output from wbmp and pbm formats.
|
||||
continue;
|
||||
}
|
||||
return new NativeEscposImage($filename, $allowOptimisations);
|
||||
} else {
|
||||
// Something else on the 'preferred' list.
|
||||
throw new InvalidArgumentException("'$implementation' is not a known EscposImage implementation");
|
||||
}
|
||||
}
|
||||
throw new InvalidArgumentException("No suitable EscposImage implementation found for '$filename'.");
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\Experimental\Unifont;
|
||||
|
||||
class ColumnFormatGlyph
|
||||
{
|
||||
public $width;
|
||||
public $data;
|
||||
|
||||
public function segment(int $maxWidth)
|
||||
{
|
||||
if ($this->width <= $maxWidth) {
|
||||
return [$this];
|
||||
}
|
||||
$dataChunks = str_split($this->data, $maxWidth * 3);
|
||||
$ret = [];
|
||||
foreach ($dataChunks as $chunk) {
|
||||
$g = new ColumnFormatGlyph();
|
||||
$g->data = $chunk;
|
||||
$g->width = strlen($chunk) / 3;
|
||||
$ret[] = $g;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
}
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\Experimental\Unifont;
|
||||
|
||||
interface ColumnFormatGlyphFactory
|
||||
{
|
||||
public function getGlyph($codePoint);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\Experimental\Unifont;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Mike42\Escpos\Printer;
|
||||
|
||||
class FontMap
|
||||
{
|
||||
protected $printer;
|
||||
|
||||
const MIN = 0x20;
|
||||
const MAX = 0x7E;
|
||||
const FONT_A_WIDTH = 12;
|
||||
const FONT_B_WIDTH = 9;
|
||||
|
||||
// Map memory locations to code points
|
||||
protected $memory;
|
||||
|
||||
// Map unicode code points to bytes
|
||||
protected $chars;
|
||||
|
||||
// next available slot
|
||||
protected $next = 0;
|
||||
|
||||
public function __construct(ColumnFormatGlyphFactory $glyphFactory, Printer $printer)
|
||||
{
|
||||
$this -> printer = $printer;
|
||||
$this -> glyphFactory = $glyphFactory;
|
||||
$this -> reset();
|
||||
}
|
||||
|
||||
public function cacheChars(array $codePoints)
|
||||
{
|
||||
// TODO flush existing cache to fill with these chars.
|
||||
}
|
||||
|
||||
public function writeChar(int $codePoint)
|
||||
{
|
||||
if (!$this -> addChar($codePoint, true)) {
|
||||
throw new InvalidArgumentException("Code point $codePoint not available");
|
||||
}
|
||||
$data = implode($this -> chars[$codePoint]);
|
||||
$this -> printer -> getPrintConnector() -> write($data);
|
||||
}
|
||||
|
||||
public function reset()
|
||||
{
|
||||
$this -> chars = [];
|
||||
$this -> memory = array_fill(0, (\Mike42\Escpos\Experimental\Unifont\FontMap::MAX - FontMap::MIN) + 1, -1);
|
||||
}
|
||||
|
||||
public function occupied($id)
|
||||
{
|
||||
return $this -> memory[$id] !== -1;
|
||||
}
|
||||
|
||||
public function evict($id)
|
||||
{
|
||||
if (!$this -> occupied($id)) {
|
||||
return true;
|
||||
}
|
||||
unset($this -> chars[$this -> memory[$id]]);
|
||||
$this -> memory[$id] = -1;
|
||||
return true;
|
||||
}
|
||||
|
||||
public function addChar(int $codePoint, $evict = true)
|
||||
{
|
||||
if (isset($this -> chars[$codePoint])) {
|
||||
// Char already available
|
||||
return true;
|
||||
}
|
||||
// Get glyph
|
||||
$glyph = $this -> glyphFactory -> getGlyph($codePoint);
|
||||
$glyphParts = $glyph -> segment(self::FONT_B_WIDTH);
|
||||
//print_r($glyphParts);
|
||||
//
|
||||
// Clear count($glyphParts) of space from $start
|
||||
$start = $this -> next;
|
||||
$chars = [];
|
||||
$submit = [];
|
||||
for ($i = 0; $i < count($glyphParts); $i++) {
|
||||
$id = ($this -> next + $i) % count($this -> memory);
|
||||
if ($this -> occupied($id)) {
|
||||
if ($evict) {
|
||||
$this -> evict($id);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
$thisChar = $id + self::MIN;
|
||||
$chars[] = chr($thisChar);
|
||||
$submit[$thisChar] = $glyphParts[$i];
|
||||
}
|
||||
|
||||
// Success in locating memory space, move along counters
|
||||
$this -> next = ($this -> next + count($glyphParts)) % count($this -> memory);
|
||||
$this -> submitCharsToPrinterFont($submit);
|
||||
$this -> memory[$start] = $codePoint;
|
||||
$this -> chars[$codePoint] = $chars;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function submitCharsToPrinterFont(array $chars)
|
||||
{
|
||||
ksort($chars);
|
||||
// TODO We can sort into batches of contiguous characters here.
|
||||
foreach ($chars as $char => $glyph) {
|
||||
$verticalBytes = 3;
|
||||
$data = Printer::ESC . "&" . chr($verticalBytes) . chr($char) . chr($char) . chr($glyph -> width) . $glyph -> data;
|
||||
$this -> printer -> getPrintConnector() -> write($data);
|
||||
}
|
||||
}
|
||||
}
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\Experimental\Unifont;
|
||||
|
||||
class UnifontGlyphFactory implements ColumnFormatGlyphFactory
|
||||
{
|
||||
protected $unifontFile;
|
||||
|
||||
public static function colFormat16(array $in)
|
||||
{
|
||||
// Map 16 x 16 bit unifont (32 bytes) to 16 x 24 ESC/POS column format image (48 bytes).
|
||||
return UnifontGlyphFactory::colFormat8($in, 2, 1) . UnifontGlyphFactory::colFormat8($in, 2, 2);
|
||||
}
|
||||
|
||||
public static function colFormat8(array $in, $chars = 1, $idx = 1)
|
||||
{
|
||||
// Map 8 x 16 bit unifont (32 bytes) to 8 x 24 ESC/POS column format image (24 bytes).
|
||||
return implode([
|
||||
chr(
|
||||
(($in[0 * $chars + $idx] & 0x80)) |
|
||||
(($in[1 * $chars + $idx] & 0x80) >> 1) |
|
||||
(($in[2 * $chars + $idx] & 0x80) >> 2) |
|
||||
(($in[3 * $chars + $idx] & 0x80) >> 3) |
|
||||
(($in[4 * $chars + $idx] & 0x80) >> 4) |
|
||||
(($in[5 * $chars + $idx] & 0x80) >> 5) |
|
||||
(($in[6 * $chars + $idx] & 0x80) >> 6) |
|
||||
(($in[7 * $chars + $idx] & 0x80) >> 7)
|
||||
),
|
||||
chr(
|
||||
(($in[8 * $chars + $idx] & 0x80)) |
|
||||
(($in[9 * $chars + $idx] & 0x80) >> 1) |
|
||||
(($in[10 * $chars + $idx] & 0x80) >> 2) |
|
||||
(($in[11 * $chars + $idx] & 0x80) >> 3) |
|
||||
(($in[12 * $chars + $idx] & 0x80) >> 4) |
|
||||
(($in[13 * $chars + $idx] & 0x80) >> 5) |
|
||||
(($in[14 * $chars + $idx] & 0x80) >> 6) |
|
||||
(($in[15 * $chars + $idx] & 0x80) >> 7)
|
||||
),
|
||||
chr(0),
|
||||
chr(
|
||||
(($in[0 * $chars + $idx] & 0x40) << 1) |
|
||||
(($in[1 * $chars + $idx] & 0x40)) |
|
||||
(($in[2 * $chars + $idx] & 0x40) >> 1) |
|
||||
(($in[3 * $chars + $idx] & 0x40) >> 2) |
|
||||
(($in[4 * $chars + $idx] & 0x40) >> 3) |
|
||||
(($in[5 * $chars + $idx] & 0x40) >> 4) |
|
||||
(($in[6 * $chars + $idx] & 0x40) >> 5) |
|
||||
(($in[7 * $chars + $idx] & 0x40) >> 6)
|
||||
),
|
||||
chr(
|
||||
(($in[8 * $chars + $idx] & 0x40) << 1) |
|
||||
(($in[9 * $chars + $idx] & 0x40) >> 0) |
|
||||
(($in[10 * $chars + $idx] & 0x40) >> 1) |
|
||||
(($in[11 * $chars + $idx] & 0x40) >> 2) |
|
||||
(($in[12 * $chars + $idx] & 0x40) >> 3) |
|
||||
(($in[13 * $chars + $idx] & 0x40) >> 4) |
|
||||
(($in[14 * $chars + $idx] & 0x40) >> 5) |
|
||||
(($in[15 * $chars + $idx] & 0x40) >> 6)
|
||||
),
|
||||
chr(0),
|
||||
chr(
|
||||
(($in[0 * $chars + $idx] & 0x20) << 2) |
|
||||
(($in[1 * $chars + $idx] & 0x20) << 1) |
|
||||
(($in[2 * $chars + $idx] & 0x20)) |
|
||||
(($in[3 * $chars + $idx] & 0x20) >> 1) |
|
||||
(($in[4 * $chars + $idx] & 0x20) >> 2) |
|
||||
(($in[5 * $chars + $idx] & 0x20) >> 3) |
|
||||
(($in[6 * $chars + $idx] & 0x20) >> 4) |
|
||||
(($in[7 * $chars + $idx] & 0x20) >> 5)
|
||||
),
|
||||
chr(
|
||||
(($in[8 * $chars + $idx] & 0x20) << 2) |
|
||||
(($in[9 * $chars + $idx] & 0x20) << 1) |
|
||||
(($in[10 * $chars + $idx] & 0x20)) |
|
||||
(($in[11 * $chars + $idx] & 0x20) >> 1) |
|
||||
(($in[12 * $chars + $idx] & 0x20) >> 2) |
|
||||
(($in[13 * $chars + $idx] & 0x20) >> 3) |
|
||||
(($in[14 * $chars + $idx] & 0x20) >> 4) |
|
||||
(($in[15 * $chars + $idx] & 0x20) >> 5)
|
||||
),
|
||||
chr(0),
|
||||
chr(
|
||||
(($in[0 * $chars + $idx] & 0x10) << 3) |
|
||||
(($in[1 * $chars + $idx] & 0x10) << 2) |
|
||||
(($in[2 * $chars + $idx] & 0x10) << 1) |
|
||||
(($in[3 * $chars + $idx] & 0x10)) |
|
||||
(($in[4 * $chars + $idx] & 0x10) >> 1) |
|
||||
(($in[5 * $chars + $idx] & 0x10) >> 2) |
|
||||
(($in[6 * $chars + $idx] & 0x10) >> 3) |
|
||||
(($in[7 * $chars + $idx] & 0x10) >> 4)
|
||||
),
|
||||
chr(
|
||||
(($in[8 * $chars + $idx] & 0x10) << 3) |
|
||||
(($in[9 * $chars + $idx] & 0x10) << 2) |
|
||||
(($in[10 * $chars + $idx] & 0x10) << 1) |
|
||||
(($in[11 * $chars + $idx] & 0x10)) |
|
||||
(($in[12 * $chars + $idx] & 0x10) >> 1) |
|
||||
(($in[13 * $chars + $idx] & 0x10) >> 2) |
|
||||
(($in[14 * $chars + $idx] & 0x10) >> 3) |
|
||||
(($in[15 * $chars + $idx] & 0x10) >> 4)
|
||||
),
|
||||
chr(0),
|
||||
chr(
|
||||
(($in[0 * $chars + $idx] & 0x08) << 4) |
|
||||
(($in[1 * $chars + $idx] & 0x08) << 3) |
|
||||
(($in[2 * $chars + $idx] & 0x08) << 2) |
|
||||
(($in[3 * $chars + $idx] & 0x08) << 1) |
|
||||
(($in[4 * $chars + $idx] & 0x08)) |
|
||||
(($in[5 * $chars + $idx] & 0x08) >> 1) |
|
||||
(($in[6 * $chars + $idx] & 0x08) >> 2) |
|
||||
(($in[7 * $chars + $idx] & 0x08) >> 3)
|
||||
),
|
||||
chr(
|
||||
(($in[8 * $chars + $idx] & 0x08) << 4) |
|
||||
(($in[9 * $chars + $idx] & 0x08) << 3) |
|
||||
(($in[10 * $chars + $idx] & 0x08) << 2) |
|
||||
(($in[11 * $chars + $idx] & 0x08) << 1) |
|
||||
(($in[12 * $chars + $idx] & 0x08)) |
|
||||
(($in[13 * $chars + $idx] & 0x08) >> 1) |
|
||||
(($in[14 * $chars + $idx] & 0x08) >> 2) |
|
||||
(($in[15 * $chars + $idx] & 0x08) >> 3)
|
||||
),
|
||||
chr(0),
|
||||
chr(
|
||||
(($in[0 * $chars + $idx] & 0x04) << 5) |
|
||||
(($in[1 * $chars + $idx] & 0x04) << 4) |
|
||||
(($in[2 * $chars + $idx] & 0x04) << 3) |
|
||||
(($in[3 * $chars + $idx] & 0x04) << 2) |
|
||||
(($in[4 * $chars + $idx] & 0x04) << 1) |
|
||||
(($in[5 * $chars + $idx] & 0x04)) |
|
||||
(($in[6 * $chars + $idx] & 0x04) >> 1) |
|
||||
(($in[7 * $chars + $idx] & 0x04) >> 2)
|
||||
),
|
||||
chr(
|
||||
(($in[8 * $chars + $idx] & 0x04) << 5) |
|
||||
(($in[9 * $chars + $idx] & 0x04) << 4) |
|
||||
(($in[10 * $chars + $idx] & 0x04) << 3) |
|
||||
(($in[11 * $chars + $idx] & 0x04) << 2) |
|
||||
(($in[12 * $chars + $idx] & 0x04) << 1) |
|
||||
(($in[13 * $chars + $idx] & 0x04)) |
|
||||
(($in[14 * $chars + $idx] & 0x04) >> 1) |
|
||||
(($in[15 * $chars + $idx] & 0x04) >> 2)
|
||||
),
|
||||
chr(0),
|
||||
chr(
|
||||
(($in[0 * $chars + $idx] & 0x02) << 6) |
|
||||
(($in[1 * $chars + $idx] & 0x02) << 5) |
|
||||
(($in[2 * $chars + $idx] & 0x02) << 4) |
|
||||
(($in[3 * $chars + $idx] & 0x02) << 3) |
|
||||
(($in[4 * $chars + $idx] & 0x02) << 2) |
|
||||
(($in[5 * $chars + $idx] & 0x02) << 1) |
|
||||
(($in[6 * $chars + $idx] & 0x02)) |
|
||||
(($in[7 * $chars + $idx] & 0x02) >> 1)
|
||||
),
|
||||
chr(
|
||||
(($in[8 * $chars + $idx] & 0x02) << 6) |
|
||||
(($in[9 * $chars + $idx] & 0x02) << 5) |
|
||||
(($in[10 * $chars + $idx] & 0x02) << 4) |
|
||||
(($in[11 * $chars + $idx] & 0x02) << 3) |
|
||||
(($in[12 * $chars + $idx] & 0x02) << 2) |
|
||||
(($in[13 * $chars + $idx] & 0x02) << 1) |
|
||||
(($in[14 * $chars + $idx] & 0x02)) |
|
||||
(($in[15 * $chars + $idx] & 0x02) >> 1)
|
||||
),
|
||||
chr(0),
|
||||
chr(
|
||||
(($in[0 * $chars + $idx] & 0x01) << 7) |
|
||||
(($in[1 * $chars + $idx] & 0x01) << 6) |
|
||||
(($in[2 * $chars + $idx] & 0x01) << 5) |
|
||||
(($in[3 * $chars + $idx] & 0x01) << 4) |
|
||||
(($in[4 * $chars + $idx] & 0x01) << 3) |
|
||||
(($in[5 * $chars + $idx] & 0x01) << 2) |
|
||||
(($in[6 * $chars + $idx] & 0x01) << 1) |
|
||||
(($in[7 * $chars + $idx] & 0x01))
|
||||
),
|
||||
chr(
|
||||
(($in[8 * $chars + $idx] & 0x01) << 7) |
|
||||
(($in[9 * $chars + $idx] & 0x01) << 6) |
|
||||
(($in[10 * $chars + $idx] & 0x01) << 5) |
|
||||
(($in[11 * $chars + $idx] & 0x01) << 4) |
|
||||
(($in[12 * $chars + $idx] & 0x01) << 3) |
|
||||
(($in[13 * $chars + $idx] & 0x01) << 2) |
|
||||
(($in[14 * $chars + $idx] & 0x01) >> 1) |
|
||||
(($in[15 * $chars + $idx] & 0x01))
|
||||
),
|
||||
chr(0)
|
||||
]);
|
||||
}
|
||||
|
||||
public function __construct(array $unifontFile)
|
||||
{
|
||||
$this -> unifontFile = $unifontFile;
|
||||
}
|
||||
|
||||
public function getGlyph($codePoint)
|
||||
{
|
||||
// Binary search for correct line.
|
||||
$min = 0;
|
||||
$max = count($this -> unifontFile) - 1;
|
||||
$foundId = 0;
|
||||
// Bias toward low side if file is > 255.
|
||||
$m = min(count($this -> unifontFile) - 1, 255);
|
||||
while ($min <= $max) {
|
||||
$thisCodePoint = hexdec(substr($this -> unifontFile[$m], 0, 4));
|
||||
if ($codePoint === $thisCodePoint) {
|
||||
$foundId = $m;
|
||||
break;
|
||||
} elseif ($codePoint < $thisCodePoint) {
|
||||
$max = $m - 1;
|
||||
} else {
|
||||
$min = $m + 1;
|
||||
}
|
||||
$m = floor(($min + $max) / 2);
|
||||
}
|
||||
$unifontLine = $this -> unifontFile[$foundId];
|
||||
|
||||
// Convert to column format
|
||||
$binStr = unpack("C*", pack("H*", substr($unifontLine, 5)));
|
||||
$bytes = count($binStr);
|
||||
if ($bytes == 32) {
|
||||
$width = 16;
|
||||
$colFormat = UnifontGlyphFactory::colFormat16($binStr);
|
||||
} elseif ($bytes == 16) {
|
||||
$width = 8;
|
||||
$colFormat = UnifontGlyphFactory::colFormat8($binStr);
|
||||
}
|
||||
// Write to obj
|
||||
$glyph = new ColumnFormatGlyph();
|
||||
$glyph -> width = $width;
|
||||
$glyph -> data = $colFormat;
|
||||
return $glyph;
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\Experimental\Unifont;
|
||||
|
||||
use Mike42\Escpos\PrintBuffers\PrintBuffer;
|
||||
use Mike42\Escpos\Printer;
|
||||
|
||||
class UnifontPrintBuffer implements PrintBuffer
|
||||
{
|
||||
private $printer;
|
||||
private $fontMap;
|
||||
private $started;
|
||||
private $unifont;
|
||||
|
||||
public function __construct(string $unifontFilename)
|
||||
{
|
||||
// Create UnifontGlyphFactory by reading from file
|
||||
$unifont = file_get_contents($unifontFilename);
|
||||
if ($unifont === false) {
|
||||
throw new \Exception("Could not read $unifontFilename");
|
||||
}
|
||||
$unifontFileLines = explode("\n", $unifont);
|
||||
$this -> unifont = new UnifontGlyphFactory($unifontFileLines);
|
||||
// Everything else is null
|
||||
$this -> printer = null;
|
||||
$this -> fontMap = null;
|
||||
$this -> started = false;
|
||||
}
|
||||
|
||||
public function writeChar(int $codePoint)
|
||||
{
|
||||
if ($codePoint == 10) {
|
||||
$this -> write("\n");
|
||||
} elseif ($codePoint == 13) {
|
||||
// Ignore CR char
|
||||
} else {
|
||||
// Straight column-format prints
|
||||
$this -> fontMap -> writeChar($codePoint);
|
||||
}
|
||||
}
|
||||
|
||||
public function writeText(string $text)
|
||||
{
|
||||
if (!$this -> started) {
|
||||
$mode = Printer::MODE_FONT_B | Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH;
|
||||
$this -> printer -> getPrintConnector() -> write(Printer::ESC . "!" . chr($mode));
|
||||
$this -> printer -> selectUserDefinedCharacterSet(true);
|
||||
}
|
||||
// Normalize text - this replaces combining characters with composed glyphs, and also helps us eliminated bad UTF-8 early
|
||||
$text = \Normalizer::normalize($text);
|
||||
if ($text === false) {
|
||||
throw new \Exception("Input must be UTF-8");
|
||||
}
|
||||
// Iterate code points
|
||||
$codePointIterator = \IntlBreakIterator::createCodePointInstance();
|
||||
$codePointIterator->setText($text);
|
||||
while ($codePointIterator->next() > 0) {
|
||||
$codePoint = $codePointIterator->getLastCodePoint();
|
||||
$this->writeChar($codePoint);
|
||||
}
|
||||
}
|
||||
|
||||
public function flush()
|
||||
{
|
||||
}
|
||||
|
||||
public function setPrinter(Printer $printer = null)
|
||||
{
|
||||
$this -> printer = $printer;
|
||||
$this -> fontMap = new FontMap($this -> unifont, $this -> printer);
|
||||
}
|
||||
|
||||
public function writeTextRaw(string $text)
|
||||
{
|
||||
}
|
||||
|
||||
public function getPrinter()
|
||||
{
|
||||
return $this -> printer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data to the underlying connector.
|
||||
*
|
||||
* @param string $data
|
||||
*/
|
||||
private function write($data)
|
||||
{
|
||||
$this -> printer -> getPrintConnector() -> write($data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Implementation of EscposImage using the GD PHP plugin.
|
||||
*/
|
||||
class GdEscposImage extends EscposImage
|
||||
{
|
||||
/**
|
||||
* Load an image from disk, into memory, using GD.
|
||||
*
|
||||
* @param string|null $filename The filename to load from
|
||||
* @throws Exception if the image format is not supported,
|
||||
* or the file cannot be opened.
|
||||
*/
|
||||
protected function loadImageData(string $filename = null)
|
||||
{
|
||||
if ($filename === null) {
|
||||
/* Set to blank image */
|
||||
return parent::loadImageData($filename);
|
||||
}
|
||||
|
||||
$ext = pathinfo($filename, PATHINFO_EXTENSION);
|
||||
switch ($ext) {
|
||||
case "png":
|
||||
$im = @imagecreatefrompng($filename);
|
||||
break;
|
||||
case "jpg":
|
||||
$im = @imagecreatefromjpeg($filename);
|
||||
break;
|
||||
case "gif":
|
||||
$im = @imagecreatefromgif($filename);
|
||||
break;
|
||||
default:
|
||||
throw new Exception("Image format not supported in GD");
|
||||
}
|
||||
$this -> readImageFromGdResource($im);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load actual image pixels from GD resource.
|
||||
*
|
||||
* @param resource $im GD resource to use
|
||||
* @throws Exception Where the image can't be read.
|
||||
*/
|
||||
public function readImageFromGdResource($im)
|
||||
{
|
||||
if (!is_resource($im) && !$im instanceof \GdImage) {
|
||||
throw new Exception("Failed to load image.");
|
||||
} elseif (!EscposImage::isGdLoaded()) {
|
||||
throw new Exception(__FUNCTION__ . " requires 'gd' extension.");
|
||||
}
|
||||
/* Make a string of 1's and 0's */
|
||||
$imgHeight = imagesy($im);
|
||||
$imgWidth = imagesx($im);
|
||||
$imgData = str_repeat("\0", $imgHeight * $imgWidth);
|
||||
for ($y = 0; $y < $imgHeight; $y++) {
|
||||
for ($x = 0; $x < $imgWidth; $x++) {
|
||||
/* Faster to average channels, blend alpha and negate the image here than via filters (tested!) */
|
||||
$cols = imagecolorsforindex($im, imagecolorat($im, $x, $y));
|
||||
// 1 for white, 0 for black, ignoring transparency
|
||||
$greyness = (int)(($cols['red'] + $cols['green'] + $cols['blue']) / 3) >> 7;
|
||||
// 1 for black, 0 for white, taking into account transparency
|
||||
$black = (1 - $greyness) >> ($cols['alpha'] >> 6);
|
||||
$imgData[$y * $imgWidth + $x] = $black;
|
||||
}
|
||||
}
|
||||
$this -> setImgWidth($imgWidth);
|
||||
$this -> setImgHeight($imgHeight);
|
||||
$this -> setImgData($imgData);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
<?php declare(strict_types=1);
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
namespace Mike42\Escpos;
|
||||
|
||||
use Exception;
|
||||
use Imagick;
|
||||
|
||||
/**
|
||||
* Implementation of EscposImage using the Imagick PHP plugin.
|
||||
*/
|
||||
class ImagickEscposImage extends EscposImage
|
||||
{
|
||||
/**
|
||||
* Load actual image pixels from Imagick object
|
||||
*
|
||||
* @param Imagick $im Image to load from
|
||||
*/
|
||||
public function readImageFromImagick(Imagick $im)
|
||||
{
|
||||
/* Strip transparency */
|
||||
$im = self::alphaRemove($im);
|
||||
/* Threshold */
|
||||
$im -> setImageType(Imagick::IMGTYPE_TRUECOLOR); // Remove transparency (good for PDF's)
|
||||
$max = $im->getQuantumRange();
|
||||
$max = $max["quantumRangeLong"];
|
||||
$im -> thresholdImage(0.5 * $max);
|
||||
/* Make a string of 1's and 0's */
|
||||
$imgHeight = $im -> getimageheight();
|
||||
$imgWidth = $im -> getimagewidth();
|
||||
$imgData = str_repeat("\0", $imgHeight * $imgWidth);
|
||||
for ($y = 0; $y < $imgHeight; $y++) {
|
||||
for ($x = 0; $x < $imgWidth; $x++) {
|
||||
/* Faster to average channels, blend alpha and negate the image here than via filters (tested!) */
|
||||
$cols = $im -> getImagePixelColor($x, $y);
|
||||
$cols = $cols -> getcolor();
|
||||
$greyness = (int)(($cols['r'] + $cols['g'] + $cols['b']) / 3) >> 7; // 1 for white, 0 for black
|
||||
$imgData[$y * $imgWidth + $x] = (1 - $greyness); // 1 for black, 0 for white
|
||||
}
|
||||
}
|
||||
$this -> setImgWidth($imgWidth);
|
||||
$this -> setImgHeight($imgHeight);
|
||||
$this -> setImgData($imgData);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $filename
|
||||
* Filename to load from
|
||||
* @param boolean $highDensityVertical
|
||||
* True for high density output (24px lines), false for regular density (8px)
|
||||
* @return string[]|NULL
|
||||
* Column format data as array, or NULL if optimised renderer isn't
|
||||
* available in this implementation.
|
||||
*/
|
||||
protected function getColumnFormatFromFile($filename = null, $highDensityVertical = true)
|
||||
{
|
||||
if ($filename === null) {
|
||||
return null;
|
||||
}
|
||||
$im = $this -> getImageFromFile($filename);
|
||||
$this -> setImgWidth($im -> getimagewidth());
|
||||
$this -> setImgHeight($im -> getimageheight());
|
||||
|
||||
/* Strip transparency */
|
||||
$im = self::alphaRemove($im);
|
||||
$im -> setformat('pbm');
|
||||
$im -> getimageblob(); // Forces 1-bit rendering now, so that subsequent operations are faster
|
||||
$im -> rotateImage('#fff', 90.0);
|
||||
$im -> flopImage();
|
||||
$lineHeight = $highDensityVertical ? 3 : 1;
|
||||
$blobs = $this -> getColumnFormatFromImage($im, $lineHeight * 8);
|
||||
return $blobs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load an image from disk, into memory, using Imagick.
|
||||
*
|
||||
* @param string|null $filename The filename to load from
|
||||
* @throws Exception if the image format is not supported,
|
||||
* or the file cannot be opened.
|
||||
*/
|
||||
protected function loadImageData(string $filename = null)
|
||||
{
|
||||
if ($filename === null) {
|
||||
/* Set to blank image */
|
||||
return parent::loadImageData($filename);
|
||||
}
|
||||
|
||||
$im = $this -> getImageFromFile($filename);
|
||||
$this -> readImageFromImagick($im);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return data in column format as array of slices.
|
||||
* Operates recursively to save cloning larger image many times.
|
||||
*
|
||||
* @param Imagick $im
|
||||
* @param int $lineHeight
|
||||
* Height of printed line in dots. 8 or 24.
|
||||
* @return string[]
|
||||
*/
|
||||
private function getColumnFormatFromImage(Imagick $im, int $lineHeight)
|
||||
{
|
||||
$imgWidth = $im->getimagewidth();
|
||||
if ($imgWidth == $lineHeight) {
|
||||
// Return glob of this panel
|
||||
return [$this -> getRasterBlobFromImage($im)];
|
||||
} elseif ($imgWidth > $lineHeight) {
|
||||
// Calculations
|
||||
$slicesLeft = (int)ceil($imgWidth / $lineHeight / 2); // TODO avoid use of floats with intdiv()
|
||||
$widthLeft = $slicesLeft * $lineHeight;
|
||||
$widthRight = $imgWidth - $widthLeft;
|
||||
// Slice up (left)
|
||||
$left = clone $im;
|
||||
$left -> extentimage($widthLeft, $left -> getimageheight(), 0, 0);
|
||||
// Slice up (right - ensure width is divisible by lineHeight also)
|
||||
$right = clone $im;
|
||||
$widthRightRounded = $widthRight < $lineHeight ? $lineHeight : $widthRight;
|
||||
$right -> extentimage($widthRightRounded, $right -> getimageheight(), $widthLeft, 0);
|
||||
// Recurse
|
||||
$leftBlobs = $this -> getColumnFormatFromImage($left, $lineHeight);
|
||||
$rightBlobs = $this -> getColumnFormatFromImage($right, $lineHeight);
|
||||
return array_merge($leftBlobs, $rightBlobs);
|
||||
} else {
|
||||
/* Image is smaller than full width */
|
||||
$im -> extentimage($lineHeight, $im -> getimageheight(), 0, 0);
|
||||
return [$this -> getRasterBlobFromImage($im)];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load Imagick file from image
|
||||
*
|
||||
* @param string $filename Filename to load
|
||||
* @throws Exception Wrapped Imagick error if image can't be loaded
|
||||
* @return Imagick Loaded image
|
||||
*/
|
||||
private function getImageFromFile($filename)
|
||||
{
|
||||
$im = new Imagick();
|
||||
try {
|
||||
$im -> setResourceLimit(6, 1); // Prevent libgomp1 segfaults, grumble grumble.
|
||||
$im -> readimage($filename);
|
||||
} catch (\ImagickException $e) {
|
||||
/* Re-throw as normal exception */
|
||||
throw new Exception($e -> getMessage());
|
||||
}
|
||||
return $im;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull blob (from PBM-formatted image only!), and spit out a blob or raster data.
|
||||
* Will crash out on anything which is not a valid 'P4' file.
|
||||
*
|
||||
* @param Imagick $im Image which has format PBM.
|
||||
* @return string raster data from the image
|
||||
*/
|
||||
private function getRasterBlobFromImage(Imagick $im)
|
||||
{
|
||||
$blob = $im -> getimageblob();
|
||||
/* Find where header ends */
|
||||
$i = strpos($blob, "P4\n") + 2;
|
||||
while ($blob[$i + 1] == '#') {
|
||||
$i = strpos($blob, "\n", $i + 1);
|
||||
}
|
||||
$i = strpos($blob, "\n", $i + 1);
|
||||
/* Return raster data only */
|
||||
$subBlob = substr($blob, $i + 1);
|
||||
return $subBlob;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $filename
|
||||
* Filename to load from
|
||||
* @return string|NULL
|
||||
* Raster format data, or NULL if no optimised renderer is available in
|
||||
* this implementation.
|
||||
*/
|
||||
protected function getRasterFormatFromFile($filename = null)
|
||||
{
|
||||
if ($filename === null) {
|
||||
return null;
|
||||
}
|
||||
$im = $this -> getImageFromFile($filename);
|
||||
$this -> setImgWidth($im -> getimagewidth());
|
||||
$this -> setImgHeight($im -> getimageheight());
|
||||
/* Convert to PBM and extract raster portion */
|
||||
$im = self::alphaRemove($im);
|
||||
$im -> setFormat('pbm');
|
||||
return $this -> getRasterBlobFromImage($im);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a PDF for use on the printer
|
||||
*
|
||||
* @param string $pdfFile
|
||||
* The file to load
|
||||
* @param int $pageWidth
|
||||
* The width, in pixels, of the printer's output. The first page of the
|
||||
* PDF will be scaled to approximately fit in this area.
|
||||
* @throws Exception Where Imagick is not loaded, or where a missing file
|
||||
* or invalid page number is requested.
|
||||
* @return array Array of images, retrieved from the PDF file.
|
||||
*/
|
||||
public static function loadPdf($pdfFile, int $pageWidth = 550)
|
||||
{
|
||||
if (!EscposImage::isImagickLoaded()) {
|
||||
throw new Exception(__FUNCTION__ . " requires imagick extension.");
|
||||
}
|
||||
/*
|
||||
* Load first page at very low density (resolution), to figure out what
|
||||
* density to use to achieve $pageWidth
|
||||
*/
|
||||
try {
|
||||
$image = new Imagick();
|
||||
$testRes = 2; // Test resolution
|
||||
$image -> setresolution($testRes, $testRes);
|
||||
/* Load document just to measure geometry */
|
||||
$image -> readimage($pdfFile);
|
||||
$geo = $image -> getimagegeometry();
|
||||
$image -> destroy();
|
||||
$width = $geo['width'];
|
||||
$newRes = $pageWidth / $width * $testRes;
|
||||
/* Load entire document in */
|
||||
$image -> setresolution($newRes, $newRes);
|
||||
$image -> readImage($pdfFile);
|
||||
$pages = $image -> getNumberImages();
|
||||
/* Convert images to Escpos objects */
|
||||
$ret = [];
|
||||
for ($i = 0; $i < $pages; $i++) {
|
||||
$image -> setIteratorIndex($i);
|
||||
$ep = new ImagickEscposImage();
|
||||
$ep -> readImageFromImagick($image);
|
||||
$ret[] = $ep;
|
||||
}
|
||||
return $ret;
|
||||
} catch (\ImagickException $e) {
|
||||
/* Wrap in normal exception, so that classes which call this do not
|
||||
* themselves require imagick as a dependency. */
|
||||
throw new Exception($e -> getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Paste image over white canvas to stip transparency reliably on different
|
||||
* versions of ImageMagick.
|
||||
*
|
||||
* There are other methods for this:
|
||||
* - flattenImages() is deprecated
|
||||
* - setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE) is not available on
|
||||
* ImageMagick < 6.8.
|
||||
*
|
||||
* @param Imagick $im Image to flatten
|
||||
* @return Imagick Flattened image
|
||||
*/
|
||||
private static function alphaRemove(Imagick $im)
|
||||
{
|
||||
$flat = new Imagick();
|
||||
$flat -> newImage($im -> getimagewidth(), $im -> getimageheight(), "white", $im -> getimageformat());
|
||||
$flat -> compositeimage($im, Imagick::COMPOSITE_OVER, 0, 0);
|
||||
return $flat;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos;
|
||||
|
||||
use Mike42\GfxPhp\Image;
|
||||
|
||||
/**
|
||||
* Implementation of EscposImage using only native PHP.
|
||||
*/
|
||||
class NativeEscposImage extends EscposImage
|
||||
{
|
||||
protected function loadImageData(string $filename = null)
|
||||
{
|
||||
$image = Image::fromFile($filename) -> toRgb() -> toBlackAndWhite();
|
||||
$imgHeight = $image -> getHeight();
|
||||
$imgWidth = $image -> getWidth();
|
||||
$imgData = str_repeat("\0", $imgHeight * $imgWidth);
|
||||
for ($y = 0; $y < $imgHeight; $y++) {
|
||||
for ($x = 0; $x < $imgWidth; $x++) {
|
||||
$imgData[$y * $imgWidth + $x] = $image -> getPixel($x, $y) == 0 ? 0: 1;
|
||||
}
|
||||
}
|
||||
$this -> setImgWidth($imgWidth);
|
||||
$this -> setImgHeight($imgHeight);
|
||||
$this -> setImgData($imgData);
|
||||
}
|
||||
}
|
||||
+304
@@ -0,0 +1,304 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\PrintBuffers;
|
||||
|
||||
use LogicException;
|
||||
use Mike42\Escpos\CodePage;
|
||||
use Mike42\Escpos\Printer;
|
||||
|
||||
/**
|
||||
* This class manages newlines and character encoding for the target printer, and
|
||||
* can be interchanged for an image-bassed buffer (ImagePrintBuffer) if you can't
|
||||
* get it operating properly on your machine.
|
||||
*/
|
||||
class EscposPrintBuffer implements PrintBuffer
|
||||
{
|
||||
/**
|
||||
* True to cache output as .z, false to leave un-compressed (useful for debugging)
|
||||
*/
|
||||
const COMPRESS_CACHE = true;
|
||||
|
||||
/**
|
||||
* Un-recognised characters will be replaced with this.
|
||||
*/
|
||||
const REPLACEMENT_CHAR = "?";
|
||||
|
||||
/**
|
||||
* @var array $available
|
||||
* Map code points to printer-specific code page numbers which contain them
|
||||
*/
|
||||
private $available = null;
|
||||
|
||||
/**
|
||||
* @var array $encode
|
||||
* Map code pages to a map of code points to encoding-specific characters 128-255
|
||||
*/
|
||||
private $encode = null;
|
||||
|
||||
/**
|
||||
* @var Printer|null $printer
|
||||
* Printer for output
|
||||
*/
|
||||
private $printer;
|
||||
|
||||
/**
|
||||
* Empty print buffer.
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this -> printer = null;
|
||||
}
|
||||
|
||||
public function flush()
|
||||
{
|
||||
if ($this -> printer == null) {
|
||||
throw new LogicException("Not attached to a printer.");
|
||||
}
|
||||
// TODO Not yet implemented for this buffer: This indicates that the printer needs the current line to be ended.
|
||||
}
|
||||
|
||||
public function getPrinter()
|
||||
{
|
||||
return $this -> printer;
|
||||
}
|
||||
|
||||
public function setPrinter(Printer $printer = null)
|
||||
{
|
||||
$this -> printer = $printer;
|
||||
if ($printer != null) {
|
||||
$this -> loadAvailableCharacters();
|
||||
}
|
||||
}
|
||||
|
||||
public function writeText(string $text)
|
||||
{
|
||||
if ($this->printer == null) {
|
||||
throw new LogicException("Not attached to a printer.");
|
||||
}
|
||||
// Normalize text - this replaces combining characters with composed glyphs, and also helps us eliminated bad UTF-8 early
|
||||
$text = \Normalizer::normalize($text);
|
||||
if ($text === false) {
|
||||
throw new \Exception("Input must be UTF-8");
|
||||
}
|
||||
// Iterate code points
|
||||
$codePointIterator = \IntlBreakIterator::createCodePointInstance();
|
||||
$codePointIterator->setText($text);
|
||||
$encoding = $this->printer->getCharacterTable();
|
||||
$currentBlock = [];
|
||||
while ($codePointIterator->next() > 0) {
|
||||
// Write each code point
|
||||
$codePoint = $codePointIterator->getLastCodePoint();
|
||||
// See if we need to change code pages
|
||||
$matching = !isset($this->available[$codePoint]) || isset($this->encode[$encoding][$codePoint]);
|
||||
if ($matching) {
|
||||
$currentBlock[] = $codePoint;
|
||||
} else {
|
||||
// Write what we have
|
||||
$this->writeTextUsingEncoding($currentBlock, $encoding);
|
||||
// New encoding..
|
||||
$encoding = self::identifyText($codePoint);
|
||||
$currentBlock = [$codePoint];
|
||||
}
|
||||
}
|
||||
// Write out last bytes
|
||||
if (count($currentBlock) != 0) {
|
||||
$this->writeTextUsingEncoding($currentBlock, $encoding);
|
||||
}
|
||||
}
|
||||
|
||||
public function writeTextRaw(string $text)
|
||||
{
|
||||
if ($this -> printer == null) {
|
||||
throw new LogicException("Not attached to a printer.");
|
||||
}
|
||||
if (strlen($text) == 0) {
|
||||
return;
|
||||
}
|
||||
// Pass only printable characters
|
||||
$j = 0;
|
||||
$l = strlen($text);
|
||||
$outp = str_repeat(self::REPLACEMENT_CHAR, $l);
|
||||
for ($i = 0; $i < $l; $i++) {
|
||||
$c = substr($text, $i, 1);
|
||||
if ($c == "\r") {
|
||||
/* Skip past Windows line endings (raw usage). */
|
||||
continue;
|
||||
} elseif (self::asciiCheck($c, true)) {
|
||||
$outp[$j] = $c;
|
||||
}
|
||||
$j++;
|
||||
}
|
||||
$this -> write(substr($outp, 0, $j));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an encoding which we can start to use for outputting this text.
|
||||
* Later parts of the text need not be included in the returned code page.
|
||||
*
|
||||
* @param int $codePoint Code point to check.
|
||||
* @return boolean|integer Code page number, or FALSE if the text is not
|
||||
* printable on any supported encoding.
|
||||
*/
|
||||
private function identifyText(int $codePoint)
|
||||
{
|
||||
if (!isset($this -> available[$codePoint])) {
|
||||
/* Character not available anywhere */
|
||||
return false;
|
||||
}
|
||||
return $this -> available[$codePoint];
|
||||
}
|
||||
|
||||
/**
|
||||
* Based on the printer's connector, compute (or load a cached copy of) maps
|
||||
* of UTF character to unicode characters for later use.
|
||||
*/
|
||||
private function loadAvailableCharacters()
|
||||
{
|
||||
$profile = $this -> printer -> getPrinterCapabilityProfile();
|
||||
$supportedCodePages = $profile -> getCodePages();
|
||||
$profileName = $profile -> getId();
|
||||
$cacheFile = dirname(__FILE__) . "/cache/Characters-" . $profileName . ".ser" .
|
||||
(self::COMPRESS_CACHE ? ".z" : "");
|
||||
$cacheKey = $profile -> getCodePageCacheKey();
|
||||
/* Check for pre-generated file */
|
||||
if (file_exists($cacheFile)) {
|
||||
$cacheData = file_get_contents($cacheFile);
|
||||
if (self::COMPRESS_CACHE) {
|
||||
$cacheData = gzuncompress($cacheData);
|
||||
}
|
||||
if ($cacheData) {
|
||||
$dataArray = unserialize($cacheData);
|
||||
if (isset($dataArray["key"]) && isset($dataArray["available"]) &&
|
||||
isset($dataArray["encode"]) && $dataArray["key"] == $cacheKey) {
|
||||
$this -> available = $dataArray["available"];
|
||||
$this -> encode = $dataArray["encode"];
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Generate conversion tables */
|
||||
$encodeLegacy = [];
|
||||
$encode = [];
|
||||
$available = [];
|
||||
|
||||
foreach ($supportedCodePages as $num => $codePage) {
|
||||
$encodeLegacy[$num] = [];
|
||||
if (!$codePage -> isEncodable()) {
|
||||
continue;
|
||||
}
|
||||
$map = $codePage -> getDataArray();
|
||||
$encodeMap = [];
|
||||
for ($char = 128; $char <= 255; $char++) {
|
||||
$codePoint = $map[$char - 128];
|
||||
if ($codePoint == CodePage::MISSING_CHAR_CODE) { // Skip placeholders
|
||||
continue;
|
||||
}
|
||||
$encodeMap[$codePoint] = $char;
|
||||
if (!isset($available[$codePoint])) {
|
||||
$available[$codePoint] = $num;
|
||||
}
|
||||
}
|
||||
$encode[$num] = $encodeMap;
|
||||
}
|
||||
|
||||
/* Use generated data */
|
||||
$dataArray = [
|
||||
"available" => $available,
|
||||
"encode" => $encode,
|
||||
"key" => $cacheKey
|
||||
];
|
||||
$this -> available = $available;
|
||||
$this -> encode = $encode;
|
||||
|
||||
$cacheData = serialize($dataArray);
|
||||
if (self::COMPRESS_CACHE) {
|
||||
$cacheData = gzcompress($cacheData);
|
||||
}
|
||||
/* Attempt to cache, but don't worry if we can't */
|
||||
@file_put_contents($cacheFile, $cacheData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a block of text using the specified map, and write it to the printer.
|
||||
*
|
||||
* @param array $codePoints Text to print, as list of unicode code points
|
||||
* @param integer $encodingNo Encoding number to use- assumed to exist.
|
||||
*/
|
||||
private function writeTextUsingEncoding(array $codePoints, int $encodingNo)
|
||||
{
|
||||
$encodeMap = $this -> encode[$encodingNo];
|
||||
$len = count($codePoints);
|
||||
|
||||
$rawText = str_repeat(self::REPLACEMENT_CHAR, $len);
|
||||
$bytesWritten = 0;
|
||||
$cr = 0x0D; // extra character from line endings on Windows
|
||||
for ($i = 0; $i < $len; $i++) {
|
||||
$codePoint = $codePoints[$i];
|
||||
if (isset($encodeMap[$codePoint])) {
|
||||
// Printable via selected code page
|
||||
$rawText[$bytesWritten] = chr($encodeMap[$codePoint]);
|
||||
} elseif (($codePoint > 31 && $codePoint < 127) || $codePoint == 10) {
|
||||
// Printable as ASCII
|
||||
$rawText[$bytesWritten] = chr($codePoint);
|
||||
} elseif ($codePoint === $cr) {
|
||||
// Skip past Windows line endings, LF is fine
|
||||
continue;
|
||||
}
|
||||
$bytesWritten++;
|
||||
}
|
||||
if ($this -> printer -> getCharacterTable() != $encodingNo) {
|
||||
$this -> printer -> selectCharacterTable($encodingNo);
|
||||
}
|
||||
$this -> writeTextRaw(substr($rawText, 0, $bytesWritten));
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data to the underlying printer.
|
||||
*
|
||||
* @param string $data
|
||||
*/
|
||||
private function write(string $data)
|
||||
{
|
||||
$this -> printer -> getPrintConnector() -> write($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if a character is an ASCII printable character.
|
||||
*
|
||||
* @param string $char Character to check
|
||||
* @param boolean $extended True to allow 128-256 values also (excluded by default)
|
||||
* @return boolean True if the character is printable, false if it is not.
|
||||
*/
|
||||
private static function asciiCheck(string $char, bool $extended = false)
|
||||
{
|
||||
if (strlen($char) != 1) {
|
||||
// Multi-byte string
|
||||
return false;
|
||||
}
|
||||
$num = ord($char);
|
||||
if ($num > 31 && $num < 127) { // Printable
|
||||
return true;
|
||||
}
|
||||
if ($num == 10) { // New-line (printer will take these)
|
||||
return true;
|
||||
}
|
||||
if ($extended && $num > 127) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\PrintBuffers;
|
||||
|
||||
use Exception;
|
||||
use LogicException;
|
||||
use Mike42\Escpos\Printer;
|
||||
use Mike42\Escpos\EscposImage;
|
||||
use Mike42\Escpos\ImagickEscposImage;
|
||||
|
||||
/**
|
||||
* This class renders text to small images on-the-fly. It attempts to mimic the
|
||||
* behaviour of text output, whilst supporting any fonts & character encodings
|
||||
* which your system can handle. This class currently requires Imagick.
|
||||
*/
|
||||
class ImagePrintBuffer implements PrintBuffer
|
||||
{
|
||||
private $printer;
|
||||
|
||||
/**
|
||||
* @var string|null font to use
|
||||
*/
|
||||
private $font;
|
||||
|
||||
private $fontSize;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
if (!EscposImage::isImagickLoaded()) {
|
||||
throw new Exception("ImagePrintBuffer requires the imagick extension");
|
||||
}
|
||||
$this -> font = null;
|
||||
$this -> fontSize = 24;
|
||||
}
|
||||
|
||||
public function flush()
|
||||
{
|
||||
if ($this -> printer == null) {
|
||||
throw new LogicException("Not attached to a printer.");
|
||||
}
|
||||
}
|
||||
|
||||
public function getPrinter()
|
||||
{
|
||||
return $this -> printer;
|
||||
}
|
||||
|
||||
public function setPrinter(Printer $printer = null)
|
||||
{
|
||||
$this -> printer = $printer;
|
||||
}
|
||||
|
||||
public function writeText(string $text)
|
||||
{
|
||||
if ($this -> printer == null) {
|
||||
throw new LogicException("Not attached to a printer.");
|
||||
}
|
||||
if ($text == null) {
|
||||
return;
|
||||
}
|
||||
$text = trim($text, "\n");
|
||||
/* Create Imagick objects */
|
||||
$image = new \Imagick();
|
||||
$draw = new \ImagickDraw();
|
||||
$color = new \ImagickPixel('#000000');
|
||||
$background = new \ImagickPixel('white');
|
||||
|
||||
/* Create annotation */
|
||||
if ($this->font !== null) {
|
||||
// Allow fallback on defaults as necessary
|
||||
$draw->setFont($this->font);
|
||||
}
|
||||
/* In Arial, size 21 looks good as a substitute for FONT_B, 24 for FONT_A */
|
||||
$draw -> setFontSize($this -> fontSize);
|
||||
$draw -> setFillColor($color);
|
||||
$draw -> setStrokeAntialias(true);
|
||||
$draw -> setTextAntialias(true);
|
||||
$metrics = $image -> queryFontMetrics($draw, $text);
|
||||
$draw -> annotation(0, $metrics['ascender'], $text);
|
||||
|
||||
/* Create image & draw annotation on it */
|
||||
$image -> newImage($metrics['textWidth'], $metrics['textHeight'], $background);
|
||||
$image -> setImageFormat('png');
|
||||
$image -> drawImage($draw);
|
||||
// debugging if you want to view the images yourself
|
||||
//$image -> writeImage("test.png");
|
||||
|
||||
/* Save image */
|
||||
$escposImage = new ImagickEscposImage();
|
||||
$escposImage -> readImageFromImagick($image);
|
||||
$size = Printer::IMG_DEFAULT;
|
||||
$this -> printer -> bitImage($escposImage, $size);
|
||||
}
|
||||
|
||||
public function writeTextRaw(string $text)
|
||||
{
|
||||
if ($this -> printer == null) {
|
||||
throw new LogicException("Not attached to a printer.");
|
||||
}
|
||||
$this -> printer -> getPrintConnector() -> write($text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set path on disk to TTF font that will be used to render text to image,
|
||||
* or 'null' to use a default.
|
||||
*
|
||||
* ImageMagick will also accept a font name, but this will not port as well
|
||||
* between systems.
|
||||
*
|
||||
* @param string $font
|
||||
* Font name or a filename
|
||||
*/
|
||||
public function setFont(string $font)
|
||||
{
|
||||
$this->font = $font;
|
||||
}
|
||||
|
||||
/**
|
||||
* Numeric font size for rendering text to image
|
||||
*/
|
||||
public function setFontSize(int $fontSize)
|
||||
{
|
||||
$this->fontSize = $fontSize;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\PrintBuffers;
|
||||
|
||||
use Mike42\Escpos\Printer;
|
||||
|
||||
/**
|
||||
* Print buffers manage newlines and character encoding for the target printer.
|
||||
* They are used as a swappable component: text or image-based output.
|
||||
*
|
||||
* - Text output (EscposPrintBuffer) is the fast default, and is recommended for
|
||||
* most people, as the text output can be more directly manipulated by ESC/POS
|
||||
* commands.
|
||||
* - Image output (ImagePrintBuffer) is designed to accept more encodings than the
|
||||
* physical printer supports, by rendering the text to small images on-the-fly.
|
||||
* This takes a lot more CPU than sending text, but is necessary for some users.
|
||||
* - If your use case fits outside these, then a further speed/flexibility trade-off
|
||||
* can be made by printing directly from generated HTML or PDF.
|
||||
*/
|
||||
interface PrintBuffer
|
||||
{
|
||||
/**
|
||||
* Cause the buffer to send any partial input and wait on a newline.
|
||||
* If the printer is already on a new line, this does nothing.
|
||||
*/
|
||||
public function flush();
|
||||
|
||||
/**
|
||||
* Used by Escpos to check if a printer is set.
|
||||
*/
|
||||
public function getPrinter();
|
||||
|
||||
/**
|
||||
* Used by Escpos to hook up one-to-one link between buffers and printers.
|
||||
*
|
||||
* @param Printer|null $printer New printer
|
||||
*/
|
||||
public function setPrinter(Printer $printer = null);
|
||||
|
||||
/**
|
||||
* Accept UTF-8 text for printing.
|
||||
*
|
||||
* @param string $text Text to print
|
||||
*/
|
||||
public function writeText(string $text);
|
||||
|
||||
/**
|
||||
* Accept 8-bit text in the current encoding and add it to the buffer.
|
||||
*
|
||||
* @param string $text Text to print, already the target encoding.
|
||||
*/
|
||||
public function writeTextRaw(string $text);
|
||||
}
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
+188
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\PrintConnectors;
|
||||
|
||||
use Exception;
|
||||
use BadMethodCallException;
|
||||
|
||||
/**
|
||||
* Print connector that passes print data to CUPS print commands.
|
||||
* Your printer mut be installed on the local CUPS instance to use this connector.
|
||||
*/
|
||||
class CupsPrintConnector implements PrintConnector
|
||||
{
|
||||
|
||||
/**
|
||||
* @var array $buffer
|
||||
* Buffer of accumilated data.
|
||||
*/
|
||||
private $buffer;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var string $printerName
|
||||
* The name of the target printer.
|
||||
*/
|
||||
private $printerName;
|
||||
|
||||
/**
|
||||
* Construct new CUPS print connector.
|
||||
*
|
||||
* @param string $dest
|
||||
* The CUPS printer name to print to. This must be loaded using a raw driver.
|
||||
* @throws BadMethodCallException
|
||||
*/
|
||||
public function __construct($dest)
|
||||
{
|
||||
$valid = $this->getLocalPrinters();
|
||||
if (count($valid) == 0) {
|
||||
throw new BadMethodCallException("You do not have any printers installed on " .
|
||||
"this system via CUPS. Check 'lpr -a'.");
|
||||
}
|
||||
|
||||
if (array_search($dest, $valid, true) === false) {
|
||||
throw new BadMethodCallException("'$dest' is not a printer on this system. " .
|
||||
"Printers are: [" . implode(", ", $valid) . "]");
|
||||
}
|
||||
$this->buffer = array ();
|
||||
$this->printerName = $dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cause a NOTICE if deconstructed before the job was printed.
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
if ($this->buffer !== null) {
|
||||
trigger_error("Print connector was not finalized. Did you forget to close the printer?", E_USER_NOTICE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send job to printer.
|
||||
*/
|
||||
public function finalize()
|
||||
{
|
||||
$data = implode($this->buffer);
|
||||
$this->buffer = null;
|
||||
|
||||
// Build command to work on data
|
||||
$tmpfname = tempnam(sys_get_temp_dir(), 'print-');
|
||||
if ($tmpfname === false) {
|
||||
throw new Exception("Failed to create temp file for printing.");
|
||||
}
|
||||
file_put_contents($tmpfname, $data);
|
||||
$cmd = sprintf(
|
||||
"lp -d %s %s",
|
||||
escapeshellarg($this->printerName),
|
||||
escapeshellarg($tmpfname)
|
||||
);
|
||||
try {
|
||||
$this->getCmdOutput($cmd);
|
||||
} catch (Exception $e) {
|
||||
unlink($tmpfname);
|
||||
throw $e;
|
||||
}
|
||||
unlink($tmpfname);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a command and throw an exception if it fails, or return the output if it works.
|
||||
* (Basically exec() with good error handling)
|
||||
*
|
||||
* @param string $cmd
|
||||
* Command to run
|
||||
*/
|
||||
protected function getCmdOutput($cmd)
|
||||
{
|
||||
$descriptors = array (
|
||||
1 => array (
|
||||
"pipe",
|
||||
"w"
|
||||
),
|
||||
2 => array (
|
||||
"pipe",
|
||||
"w"
|
||||
)
|
||||
);
|
||||
$process = proc_open($cmd, $descriptors, $fd);
|
||||
if (! is_resource($process)) {
|
||||
throw new Exception("Command '$cmd' failed to start.");
|
||||
}
|
||||
/* Read stdout */
|
||||
$outputStr = stream_get_contents($fd [1]);
|
||||
fclose($fd [1]);
|
||||
/* Read stderr */
|
||||
$errorStr = stream_get_contents($fd [2]);
|
||||
fclose($fd [2]);
|
||||
/* Finish up */
|
||||
$retval = proc_close($process);
|
||||
if ($retval != 0) {
|
||||
throw new Exception("Command $cmd failed: $errorStr");
|
||||
}
|
||||
return $outputStr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read data from the printer.
|
||||
*
|
||||
* @param string $len Length of data to read.
|
||||
* @return string Data read from the printer, or false where reading is not possible.
|
||||
*/
|
||||
public function read($len)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $data
|
||||
*/
|
||||
public function write($data)
|
||||
{
|
||||
$this->buffer [] = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a list of CUPS printers.
|
||||
*
|
||||
* @return array A list of printer names installed on this system. Any item
|
||||
* on this list is valid for constructing a printer.
|
||||
*/
|
||||
protected function getLocalPrinters()
|
||||
{
|
||||
$outpStr = $this->getCmdOutput("lpstat -a");
|
||||
$outpLines = explode("\n", trim($outpStr));
|
||||
foreach ($outpLines as $line) {
|
||||
$ret [] = $this->chopLpstatLine($line);
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the item before the first space in a string
|
||||
*
|
||||
* @param string $line
|
||||
* @return string the string, up to the first space, or the whole string if it contains no spaces.
|
||||
*/
|
||||
private function chopLpstatLine($line)
|
||||
{
|
||||
if (($pos = strpos($line, " ")) === false) {
|
||||
return $line;
|
||||
} else {
|
||||
return substr($line, 0, $pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\PrintConnectors;
|
||||
|
||||
/**
|
||||
* Print connector that writes to nowhere, but allows the user to retrieve the
|
||||
* buffered data. Used for testing.
|
||||
*/
|
||||
final class DummyPrintConnector implements PrintConnector
|
||||
{
|
||||
/**
|
||||
* @var array $buffer
|
||||
* Buffer of accumilated data.
|
||||
*/
|
||||
private $buffer;
|
||||
|
||||
/**
|
||||
* @var string data which the printer will provide on next read
|
||||
*/
|
||||
private $readData;
|
||||
|
||||
/**
|
||||
* Create new print connector
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this -> buffer = [];
|
||||
}
|
||||
|
||||
public function clear()
|
||||
{
|
||||
$this -> buffer = [];
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
if ($this -> buffer !== null) {
|
||||
trigger_error("Print connector was not finalized. Did you forget to close the printer?", E_USER_NOTICE);
|
||||
}
|
||||
}
|
||||
|
||||
public function finalize()
|
||||
{
|
||||
$this -> buffer = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string Get the accumulated data that has been sent to this buffer.
|
||||
*/
|
||||
public function getData()
|
||||
{
|
||||
return implode($this -> buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @see PrintConnector::read()
|
||||
*/
|
||||
public function read($len)
|
||||
{
|
||||
return $len >= strlen($this -> readData) ? $this -> readData : substr($this -> readData, 0, $len);
|
||||
}
|
||||
|
||||
public function write($data)
|
||||
{
|
||||
$this -> buffer[] = $data;
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\PrintConnectors;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* PrintConnector for passing print data to a file.
|
||||
*/
|
||||
class FilePrintConnector implements PrintConnector
|
||||
{
|
||||
/**
|
||||
* @var resource $fp
|
||||
* The file pointer to send data to.
|
||||
*/
|
||||
protected $fp;
|
||||
|
||||
/**
|
||||
* Construct new connector, given a filename
|
||||
*
|
||||
* @param string $filename
|
||||
*/
|
||||
public function __construct($filename)
|
||||
{
|
||||
$this -> fp = fopen($filename, "wb+");
|
||||
if ($this -> fp === false) {
|
||||
throw new Exception("Cannot initialise FilePrintConnector.");
|
||||
}
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
if ($this -> fp !== false) {
|
||||
trigger_error("Print connector was not finalized. Did you forget to close the printer?", E_USER_NOTICE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close file pointer
|
||||
*/
|
||||
public function finalize()
|
||||
{
|
||||
if ($this -> fp !== false) {
|
||||
fclose($this -> fp);
|
||||
$this -> fp = false;
|
||||
}
|
||||
}
|
||||
|
||||
/* (non-PHPdoc)
|
||||
* @see PrintConnector::read()
|
||||
*/
|
||||
public function read($len)
|
||||
{
|
||||
if ($this -> fp === false) {
|
||||
throw new Exception("PrintConnector has been closed, cannot read input.");
|
||||
}
|
||||
return fread($this -> fp, $len);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data to the file
|
||||
*
|
||||
* @param string $data
|
||||
*/
|
||||
public function write($data)
|
||||
{
|
||||
if ($this -> fp === false) {
|
||||
throw new Exception("PrintConnector has been closed, cannot send output.");
|
||||
}
|
||||
fwrite($this -> fp, $data);
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\PrintConnectors;
|
||||
|
||||
/**
|
||||
* Wrap multiple connectors up, to print to several printers at the same time.
|
||||
*/
|
||||
class MultiplePrintConnector implements PrintConnector
|
||||
{
|
||||
private $connectors;
|
||||
|
||||
public function __construct(PrintConnector ...$connectors)
|
||||
{
|
||||
$this -> connectors = $connectors;
|
||||
}
|
||||
|
||||
public function finalize()
|
||||
{
|
||||
foreach ($this -> connectors as $connector) {
|
||||
$connector -> finalize();
|
||||
}
|
||||
}
|
||||
|
||||
public function read($len)
|
||||
{
|
||||
// Cannot write
|
||||
return false;
|
||||
}
|
||||
|
||||
public function write($data)
|
||||
{
|
||||
foreach ($this -> connectors as $connector) {
|
||||
$connector -> write($data);
|
||||
}
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
// Do nothing
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
<?php declare(strict_types=1);
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
namespace Mike42\Escpos\PrintConnectors;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* PrintConnector for directly opening a network socket to a printer to send it commands.
|
||||
*/
|
||||
class NetworkPrintConnector extends FilePrintConnector
|
||||
{
|
||||
/**
|
||||
* Construct a new NetworkPrintConnector
|
||||
*
|
||||
* @param string $ip IP address or hostname to use.
|
||||
* @param int $port The port number to connect on.
|
||||
* @param int $timeout The connection timeout, in seconds.
|
||||
* @throws Exception Where the socket cannot be opened.
|
||||
*/
|
||||
public function __construct(string $ip, int $port = 9100, int $timeout = -1)
|
||||
{
|
||||
// Note: Once the minimum PHP version is PHP 7.0 or higher, we can type $timeout as '?int' to make it optional
|
||||
// instead of using -1.
|
||||
if ($timeout == -1) {
|
||||
$this -> fp = @fsockopen($ip, $port, $errno, $errstr);
|
||||
} else {
|
||||
$this -> fp = @fsockopen($ip, $port, $errno, $errstr, (float)$timeout);
|
||||
}
|
||||
if ($this -> fp === false) {
|
||||
throw new Exception("Cannot initialise NetworkPrintConnector: " . $errstr);
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\PrintConnectors;
|
||||
|
||||
/**
|
||||
* Interface passed to Escpos class for receiving print data. Print connectors
|
||||
* are responsible for transporting this to the actual printer.
|
||||
*/
|
||||
interface PrintConnector
|
||||
{
|
||||
/**
|
||||
* Print connectors should cause a NOTICE if they are deconstructed
|
||||
* when they have not been finalized.
|
||||
*/
|
||||
public function __destruct();
|
||||
|
||||
/**
|
||||
* Finish using this print connector (close file, socket, send
|
||||
* accumulated output, etc).
|
||||
*/
|
||||
public function finalize();
|
||||
|
||||
/**
|
||||
* Read data from the printer.
|
||||
*
|
||||
* @param string $len Length of data to read.
|
||||
* @return string Data read from the printer, or false where reading is not possible.
|
||||
*/
|
||||
public function read($len);
|
||||
|
||||
/**
|
||||
* Write data to the print connector.
|
||||
*
|
||||
* @param string $data The data to write
|
||||
*/
|
||||
public function write($data);
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\PrintConnectors;
|
||||
|
||||
/**
|
||||
* Print connector for android RawBT application
|
||||
* https://play.google.com/store/apps/details?id=ru.a402d.rawbtprinter
|
||||
*/
|
||||
final class RawbtPrintConnector implements PrintConnector
|
||||
{
|
||||
/**
|
||||
* @var array $buffer
|
||||
* Buffer of accumilated data.
|
||||
*/
|
||||
private $buffer;
|
||||
|
||||
/**
|
||||
* @var string data which the printer will provide on next read
|
||||
*/
|
||||
private $readData;
|
||||
|
||||
/**
|
||||
* Create new print connector
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
ob_start();
|
||||
$this->buffer = [];
|
||||
}
|
||||
|
||||
public function clear()
|
||||
{
|
||||
$this->buffer = [];
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
if ($this->buffer !== null) {
|
||||
trigger_error("Print connector was not finalized. Did you forget to close the printer?", E_USER_NOTICE);
|
||||
}
|
||||
}
|
||||
|
||||
public function finalize()
|
||||
{
|
||||
ob_end_clean();
|
||||
echo "intent:base64," . base64_encode($this->getData()) . "#Intent;scheme=rawbt;package=ru.a402d.rawbtprinter;end;";
|
||||
$this->buffer = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string Get the accumulated data that has been sent to this buffer.
|
||||
*/
|
||||
public function getData()
|
||||
{
|
||||
return implode($this->buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* @see PrintConnector::read()
|
||||
*/
|
||||
public function read($len)
|
||||
{
|
||||
return $len >= strlen($this->readData) ? $this->readData : substr($this->readData, 0, $len);
|
||||
}
|
||||
|
||||
public function write($data)
|
||||
{
|
||||
$this->buffer[] = $data;
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\PrintConnectors;
|
||||
|
||||
class UriPrintConnector
|
||||
{
|
||||
const URI_ASSEMBLER_PATTERN = "~^(.+):/{2}(.+?)(?::(\d{1,4}))?$~";
|
||||
|
||||
public static function get($uri)
|
||||
{
|
||||
// Parse URI
|
||||
$is_uri = preg_match(self::URI_ASSEMBLER_PATTERN, $uri, $uri_parts);
|
||||
if ($is_uri !== 1) {
|
||||
throw new \InvalidArgumentException("Malformed connector URI: {$uri}");
|
||||
}
|
||||
// Extract parts
|
||||
$protocol = $uri_parts[1];
|
||||
$printer = $uri_parts[2];
|
||||
$port = isset($uri_parts[3]) ? $uri_parts[3] : 9100;
|
||||
// Initialise the most applicable print connector
|
||||
switch ($protocol) {
|
||||
case "file":
|
||||
return new FilePrintConnector($printer);
|
||||
case "tcp":
|
||||
return new NetworkPrintConnector($printer, $port);
|
||||
case "smb":
|
||||
return new WindowsPrintConnector($uri);
|
||||
}
|
||||
// Fallthrough
|
||||
throw new \InvalidArgumentException("URI sheme is not supported: {$protocol}://");
|
||||
}
|
||||
}
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of escpos-php: PHP receipt printer library for use with
|
||||
* ESC/POS-compatible thermal and impact printers.
|
||||
*
|
||||
* Copyright (c) 2014-20 Michael Billington < michael.billington@gmail.com >,
|
||||
* incorporating modifications by others. See CONTRIBUTORS.md for a full list.
|
||||
*
|
||||
* This software is distributed under the terms of the MIT license. See LICENSE.md
|
||||
* for details.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Mike42\Escpos\PrintConnectors;
|
||||
|
||||
use Exception;
|
||||
use BadMethodCallException;
|
||||
|
||||
/**
|
||||
* Connector for sending print jobs to
|
||||
* - local ports on windows (COM1, LPT1, etc)
|
||||
* - shared (SMB) printers from any platform (smb://server/foo)
|
||||
* For USB printers or other ports, the trick is to share the printer with a
|
||||
* generic text driver, then connect to the shared printer locally.
|
||||
*/
|
||||
class WindowsPrintConnector implements PrintConnector
|
||||
{
|
||||
/**
|
||||
* @var array $buffer
|
||||
* Accumulated lines of output for later use.
|
||||
*/
|
||||
private $buffer;
|
||||
|
||||
/**
|
||||
* @var string $hostname
|
||||
* The hostname of the target machine, or null if this is a local connection.
|
||||
*/
|
||||
private $hostname;
|
||||
|
||||
/**
|
||||
* @var boolean $isLocal
|
||||
* True if a port is being used directly (must be Windows), false if network shares will be used.
|
||||
*/
|
||||
private $isLocal;
|
||||
|
||||
/**
|
||||
* @var int $platform
|
||||
* Platform we're running on, for selecting different commands. See PLATFORM_* constants.
|
||||
*/
|
||||
private $platform;
|
||||
|
||||
/**
|
||||
* @var string $printerName
|
||||
* The name of the target printer (eg "Foo Printer") or port ("COM1", "LPT1").
|
||||
*/
|
||||
private $printerName;
|
||||
|
||||
/**
|
||||
* @var string $userName
|
||||
* Login name for network printer, or null if not using authentication.
|
||||
*/
|
||||
private $userName;
|
||||
|
||||
/**
|
||||
* @var string $userPassword
|
||||
* Password for network printer, or null if no password is required.
|
||||
*/
|
||||
private $userPassword;
|
||||
|
||||
/**
|
||||
* @var string $workgroup
|
||||
* Workgroup that the printer is located on
|
||||
*/
|
||||
private $workgroup;
|
||||
|
||||
/**
|
||||
* Represents Linux
|
||||
*/
|
||||
const PLATFORM_LINUX = 0;
|
||||
|
||||
/**
|
||||
* Represents Mac
|
||||
*/
|
||||
const PLATFORM_MAC = 1;
|
||||
|
||||
/**
|
||||
* Represents Windows
|
||||
*/
|
||||
const PLATFORM_WIN = 2;
|
||||
|
||||
/**
|
||||
* Valid local ports.
|
||||
*/
|
||||
const REGEX_LOCAL = "/^(LPT\d|COM\d)$/";
|
||||
|
||||
/**
|
||||
* Valid printer name.
|
||||
*/
|
||||
const REGEX_PRINTERNAME = "/^[\d\w-]+(\s[\d\w-]+)*$/";
|
||||
|
||||
/**
|
||||
* Valid smb:// URI containing hostname & printer with optional user & optional password only.
|
||||
*/
|
||||
const REGEX_SMB = "/^smb:\/\/([\s\d\w-]+(:[\s\d\w+-]+)?@)?([\d\w-]+\.)*[\d\w-]+\/([\d\w-]+\/)?[\d\w-]+(\s[\d\w-]+)*$/";
|
||||
|
||||
/**
|
||||
* @param string $dest
|
||||
* @throws BadMethodCallException
|
||||
*/
|
||||
public function __construct($dest)
|
||||
{
|
||||
$this -> platform = $this -> getCurrentPlatform();
|
||||
$this -> isLocal = false;
|
||||
$this -> buffer = null;
|
||||
$this -> userName = null;
|
||||
$this -> userPassword = null;
|
||||
$this -> workgroup = null;
|
||||
if (preg_match(self::REGEX_LOCAL, $dest) == 1) {
|
||||
// Straight to LPT1, COM1 or other local port. Allowed only if we are actually on windows.
|
||||
if ($this -> platform !== self::PLATFORM_WIN) {
|
||||
throw new BadMethodCallException("WindowsPrintConnector can only be " .
|
||||
"used to print to a local printer ('".$dest."') on a Windows computer.");
|
||||
}
|
||||
$this -> isLocal = true;
|
||||
$this -> hostname = null;
|
||||
$this -> printerName = $dest;
|
||||
} elseif (preg_match(self::REGEX_SMB, $dest) == 1) {
|
||||
// Connect to samba share, eg smb://host/printer
|
||||
$part = parse_url($dest);
|
||||
$this -> hostname = $part['host'];
|
||||
/* Printer name and optional workgroup */
|
||||
$path = ltrim($part['path'], '/');
|
||||
if (strpos($path, "/") !== false) {
|
||||
$pathPart = explode("/", $path);
|
||||
$this -> workgroup = $pathPart[0];
|
||||
$this -> printerName = $pathPart[1];
|
||||
} else {
|
||||
$this -> printerName = $path;
|
||||
}
|
||||
/* Username and password if set */
|
||||
if (isset($part['user'])) {
|
||||
$this -> userName = $part['user'];
|
||||
if (isset($part['pass'])) {
|
||||
$this -> userPassword = $part['pass'];
|
||||
}
|
||||
}
|
||||
} elseif (preg_match(self::REGEX_PRINTERNAME, $dest) == 1) {
|
||||
// Just got a printer name. Assume it's on the current computer.
|
||||
$hostname = gethostname();
|
||||
if (!$hostname) {
|
||||
$hostname = "localhost";
|
||||
}
|
||||
$this -> hostname = $hostname;
|
||||
$this -> printerName = $dest;
|
||||
} else {
|
||||
throw new BadMethodCallException("Printer '" . $dest . "' is not a valid " .
|
||||
"printer name. Use local port (LPT1, COM1, etc) or smb://computer/printer notation.");
|
||||
}
|
||||
$this -> buffer = [];
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
if ($this -> buffer !== null) {
|
||||
trigger_error("Print connector was not finalized. Did you forget to close the printer?", E_USER_NOTICE);
|
||||
}
|
||||
}
|
||||
|
||||
public function finalize()
|
||||
{
|
||||
$data = implode($this -> buffer);
|
||||
$this -> buffer = null;
|
||||
if ($this -> platform == self::PLATFORM_WIN) {
|
||||
$this -> finalizeWin($data);
|
||||
} elseif ($this -> platform == self::PLATFORM_LINUX) {
|
||||
$this -> finalizeLinux($data);
|
||||
} else {
|
||||
$this -> finalizeMac($data);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send job to printer -- platform-specific Linux code.
|
||||
*
|
||||
* @param string $data Print data
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function finalizeLinux($data)
|
||||
{
|
||||
/* Non-Windows samba printing */
|
||||
$device = "//" . $this -> hostname . "/" . $this -> printerName;
|
||||
if ($this -> userName !== null) {
|
||||
$user = ($this -> workgroup != null ? ($this -> workgroup . "\\") : "") . $this -> userName;
|
||||
if ($this -> userPassword == null) {
|
||||
// No password
|
||||
$command = sprintf(
|
||||
"smbclient %s -U %s -c %s -N -m SMB2",
|
||||
escapeshellarg($device),
|
||||
escapeshellarg($user),
|
||||
escapeshellarg("print -")
|
||||
);
|
||||
$redactedCommand = $command;
|
||||
} else {
|
||||
// With password
|
||||
$command = sprintf(
|
||||
"smbclient %s %s -U %s -c %s -m SMB2",
|
||||
escapeshellarg($device),
|
||||
escapeshellarg($this -> userPassword),
|
||||
escapeshellarg($user),
|
||||
escapeshellarg("print -")
|
||||
);
|
||||
$redactedCommand = sprintf(
|
||||
"smbclient %s %s -U %s -c %s -m SMB2",
|
||||
escapeshellarg($device),
|
||||
escapeshellarg("*****"),
|
||||
escapeshellarg($user),
|
||||
escapeshellarg("print -")
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// No authentication information at all
|
||||
$command = sprintf(
|
||||
"smbclient %s -c %s -N -m SMB2",
|
||||
escapeshellarg($device),
|
||||
escapeshellarg("print -")
|
||||
);
|
||||
$redactedCommand = $command;
|
||||
}
|
||||
$retval = $this -> runCommand($command, $outputStr, $errorStr, $data);
|
||||
if ($retval != 0) {
|
||||
throw new Exception("Failed to print. Command \"$redactedCommand\" " .
|
||||
"failed with exit code $retval: " . trim($errorStr) . trim($outputStr));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send job to printer -- platform-specific Mac code.
|
||||
*
|
||||
* @param string $data Print data
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function finalizeMac($data)
|
||||
{
|
||||
throw new Exception("Mac printing not implemented.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Send data to printer -- platform-specific Windows code.
|
||||
*
|
||||
* @param string $data
|
||||
*/
|
||||
protected function finalizeWin($data)
|
||||
{
|
||||
/* Windows-friendly printing of all sorts */
|
||||
if (!$this -> isLocal) {
|
||||
/* Networked printing */
|
||||
$device = "\\\\" . $this -> hostname . "\\" . $this -> printerName;
|
||||
if ($this -> userName !== null) {
|
||||
/* Log in */
|
||||
$user = "/user:" . ($this -> workgroup != null ? ($this -> workgroup . "\\") : "") . $this -> userName;
|
||||
if ($this -> userPassword == null) {
|
||||
$command = sprintf(
|
||||
"net use %s %s",
|
||||
escapeshellarg($device),
|
||||
escapeshellarg($user)
|
||||
);
|
||||
$redactedCommand = $command;
|
||||
} else {
|
||||
$command = sprintf(
|
||||
"net use %s %s %s",
|
||||
escapeshellarg($device),
|
||||
escapeshellarg($user),
|
||||
escapeshellarg($this -> userPassword)
|
||||
);
|
||||
$redactedCommand = sprintf(
|
||||
"net use %s %s %s",
|
||||
escapeshellarg($device),
|
||||
escapeshellarg($user),
|
||||
escapeshellarg("*****")
|
||||
);
|
||||
}
|
||||
$retval = $this -> runCommand($command, $outputStr, $errorStr);
|
||||
if ($retval != 0) {
|
||||
throw new Exception("Failed to print. Command \"$redactedCommand\" " .
|
||||
"failed with exit code $retval: " . trim($errorStr));
|
||||
}
|
||||
}
|
||||
/* Final print-out */
|
||||
$filename = tempnam(sys_get_temp_dir(), "escpos");
|
||||
if ($filename === false) {
|
||||
throw new Exception("Failed to create temp file for printing.");
|
||||
}
|
||||
file_put_contents($filename, $data);
|
||||
if (!$this -> runCopy($filename, $device)) {
|
||||
throw new Exception("Failed to copy file to printer");
|
||||
}
|
||||
unlink($filename);
|
||||
} else {
|
||||
/* Drop data straight on the printer */
|
||||
if (!$this -> runWrite($data, $this -> printerName)) {
|
||||
throw new Exception("Failed to write file to printer at " . $this -> printerName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string Current platform. Separated out for testing purposes.
|
||||
*/
|
||||
protected function getCurrentPlatform()
|
||||
{
|
||||
if (PHP_OS == "WINNT") {
|
||||
return self::PLATFORM_WIN;
|
||||
}
|
||||
if (PHP_OS == "Darwin") {
|
||||
return self::PLATFORM_MAC;
|
||||
}
|
||||
return self::PLATFORM_LINUX;
|
||||
}
|
||||
|
||||
/* (non-PHPdoc)
|
||||
* @see PrintConnector::read()
|
||||
*/
|
||||
public function read($len)
|
||||
{
|
||||
/* Two-way communication is not supported */
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a command, pass it data, and retrieve its return value, standard output, and standard error.
|
||||
*
|
||||
* @param string $command the command to run.
|
||||
* @param string $outputStr variable to fill with standard output.
|
||||
* @param string $errorStr variable to fill with standard error.
|
||||
* @param string $inputStr text to pass to the command's standard input (optional).
|
||||
* @return number
|
||||
*/
|
||||
protected function runCommand($command, &$outputStr, &$errorStr, $inputStr = null)
|
||||
{
|
||||
$descriptors = [
|
||||
0 => ["pipe", "r"],
|
||||
1 => ["pipe", "w"],
|
||||
2 => ["pipe", "w"],
|
||||
];
|
||||
$process = proc_open($command, $descriptors, $fd);
|
||||
if (is_resource($process)) {
|
||||
/* Write to input */
|
||||
if ($inputStr !== null) {
|
||||
fwrite($fd[0], $inputStr);
|
||||
}
|
||||
fclose($fd[0]);
|
||||
/* Read stdout */
|
||||
$outputStr = stream_get_contents($fd[1]);
|
||||
fclose($fd[1]);
|
||||
/* Read stderr */
|
||||
$errorStr = stream_get_contents($fd[2]);
|
||||
fclose($fd[2]);
|
||||
/* Finish up */
|
||||
$retval = proc_close($process);
|
||||
return $retval;
|
||||
} else {
|
||||
/* Method calling this should notice a non-zero exit and print an error */
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy a file. Separated out so that nothing is actually printed during test runs.
|
||||
*
|
||||
* @param string $from Source file
|
||||
* @param string $to Destination file
|
||||
* @return boolean True if copy was successful, false otherwise
|
||||
*/
|
||||
protected function runCopy($from, $to)
|
||||
{
|
||||
return copy($from, $to);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data to a file. Separated out so that nothing is actually printed during test runs.
|
||||
*
|
||||
* @param string $data Data to print
|
||||
* @param string $filename Destination file
|
||||
* @return boolean True if write was successful, false otherwise
|
||||
*/
|
||||
protected function runWrite($data, $filename)
|
||||
{
|
||||
return file_put_contents($filename, $data) !== false;
|
||||
}
|
||||
|
||||
public function write($data)
|
||||
{
|
||||
$this -> buffer[] = $data;
|
||||
}
|
||||
}
|
||||
+1200
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+34
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 1);
|
||||
|
||||
$composer_autoload = __DIR__ . "/../vendor/autoload.php";
|
||||
require_once($composer_autoload);
|
||||
|
||||
/**
|
||||
* Used in many of the tests to to output known-correct
|
||||
* strings for use in tests.
|
||||
*/
|
||||
function friendlyBinary($in)
|
||||
{
|
||||
if (is_array($in)) {
|
||||
$out = array();
|
||||
foreach ($in as $line) {
|
||||
$out[] = friendlyBinary($line);
|
||||
}
|
||||
return "[" . implode(", ", $out) . "]";
|
||||
}
|
||||
if (strlen($in) == 0) {
|
||||
return $in;
|
||||
}
|
||||
/* Print out binary data with PHP \x00 escape codes,
|
||||
for builting test cases. */
|
||||
$chars = str_split($in);
|
||||
foreach ($chars as $i => $c) {
|
||||
$code = ord($c);
|
||||
if ($code < 32 || $code > 126) {
|
||||
$chars[$i] = "\\x" . bin2hex($c);
|
||||
}
|
||||
}
|
||||
return implode($chars);
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
<?php
|
||||
use Mike42\Escpos\EscposImage;
|
||||
|
||||
class ExampleTest extends PHPUnit\Framework\TestCase
|
||||
{
|
||||
/* Verify that the examples don't fizzle out with fatal errors */
|
||||
private $exampleDir;
|
||||
|
||||
public function setUp(): void
|
||||
{
|
||||
$this -> exampleDir = dirname(__FILE__) . "/../../example/";
|
||||
}
|
||||
|
||||
/**
|
||||
* @medium
|
||||
*/
|
||||
public function testBitImage()
|
||||
{
|
||||
$this->markTestSkipped('Not repeatable on Travis CI.');
|
||||
$this -> requireGraphicsLibrary();
|
||||
$outp = $this -> runExample("bit-image.php");
|
||||
$this -> outpTest($outp, "bit-image.bin");
|
||||
}
|
||||
|
||||
/**
|
||||
* @medium
|
||||
*/
|
||||
public function testCharacterEncodings()
|
||||
{
|
||||
$outp = $this -> runExample("character-encodings.php");
|
||||
$this -> outpTest($outp, "character-encodings.bin");
|
||||
}
|
||||
|
||||
/**
|
||||
* @medium
|
||||
*/
|
||||
public function testCharacterTables()
|
||||
{
|
||||
$outp = $this -> runExample("character-tables.php");
|
||||
$this -> outpTest($outp, "character-tables.bin");
|
||||
}
|
||||
|
||||
private function outpTest($outp, $fn)
|
||||
{
|
||||
$file = dirname(__FILE__) . "/resources/output/".$fn;
|
||||
if (!file_exists($file)) {
|
||||
file_put_contents($file, $outp);
|
||||
}
|
||||
$this -> assertEquals($outp, file_get_contents($file));
|
||||
}
|
||||
|
||||
/**
|
||||
* @medium
|
||||
*/
|
||||
public function testDemo()
|
||||
{
|
||||
$this->markTestSkipped('Not repeatable on Travis CI.');
|
||||
$this -> requireGraphicsLibrary();
|
||||
$outp = $this -> runExample("demo.php");
|
||||
$this -> outpTest($outp, "demo.bin");
|
||||
}
|
||||
|
||||
/**
|
||||
* @medium
|
||||
*/
|
||||
public function testGraphics()
|
||||
{
|
||||
$this->markTestSkipped('Not repeatable on Travis CI.');
|
||||
$this -> requireGraphicsLibrary();
|
||||
$outp = $this -> runExample("graphics.php");
|
||||
$this -> outpTest($outp, "graphics.bin");
|
||||
}
|
||||
|
||||
/**
|
||||
* @medium
|
||||
*/
|
||||
public function testReceiptWithLogo()
|
||||
{
|
||||
$this->markTestSkipped('Not repeatable on Travis CI.');
|
||||
$this -> requireGraphicsLibrary();
|
||||
$outp = $this -> runExample("receipt-with-logo.php");
|
||||
$this -> outpTest($outp, "receipt-with-logo.bin");
|
||||
}
|
||||
|
||||
/**
|
||||
* @medium
|
||||
*/
|
||||
public function testQrCode()
|
||||
{
|
||||
$outp = $this -> runExample("qr-code.php");
|
||||
$this -> outpTest($outp, "qr-code.bin");
|
||||
}
|
||||
|
||||
/**
|
||||
* @medium
|
||||
*/
|
||||
public function testBarcode()
|
||||
{
|
||||
$outp = $this -> runExample("barcode.php");
|
||||
$this -> outpTest($outp, "barcode.bin");
|
||||
}
|
||||
|
||||
/**
|
||||
* @medium
|
||||
*/
|
||||
public function testTextSize()
|
||||
{
|
||||
$outp = $this -> runExample("text-size.php");
|
||||
$this -> outpTest($outp, "text-size.bin");
|
||||
}
|
||||
|
||||
/**
|
||||
* @medium
|
||||
*/
|
||||
public function testMarginsAndSpacing()
|
||||
{
|
||||
$outp = $this -> runExample("margins-and-spacing.php");
|
||||
$this -> outpTest($outp, "margins-and-spacing.bin");
|
||||
}
|
||||
|
||||
/**
|
||||
* @medium
|
||||
*/
|
||||
public function testPdf417Code()
|
||||
{
|
||||
$outp = $this -> runExample("pdf417-code.php");
|
||||
$this -> outpTest($outp, "pdf417-code.bin");
|
||||
}
|
||||
|
||||
/**
|
||||
* @medium
|
||||
*/
|
||||
public function testUnifontPrintBuffer()
|
||||
{
|
||||
$this->markTestSkipped('Not repeatable on Travis CI.');
|
||||
if(!file_exists("/usr/share/unifont/unifont.hex")) {
|
||||
$this -> markTestSkipped("Test only repeatable w/ unifont installed");
|
||||
}
|
||||
$outp = $this -> runExample("unifont-print-buffer.php");
|
||||
$this -> outpTest($outp, "unifont-print-buffer.bin");
|
||||
}
|
||||
|
||||
public function testInterfaceCups()
|
||||
{
|
||||
$outp = $this -> runSyntaxCheck("interface/cups.php");
|
||||
}
|
||||
|
||||
public function testInterfaceEthernet()
|
||||
{
|
||||
$outp = $this -> runSyntaxCheck("interface/ethernet.php");
|
||||
}
|
||||
|
||||
public function testInterfaceLinuxUSB()
|
||||
{
|
||||
$outp = $this -> runSyntaxCheck("interface/linux-usb.php");
|
||||
}
|
||||
|
||||
public function testInterfaceWindowsUSB()
|
||||
{
|
||||
$outp = $this -> runSyntaxCheck("interface/windows-usb.php");
|
||||
}
|
||||
|
||||
public function testInterfaceSMB()
|
||||
{
|
||||
$outp = $this -> runSyntaxCheck("interface/smb.php");
|
||||
}
|
||||
|
||||
public function testInterfaceWindowsLPT()
|
||||
{
|
||||
$outp = $this -> runSyntaxCheck("interface/windows-lpt.php");
|
||||
}
|
||||
|
||||
private function runSyntaxCheck($fn)
|
||||
{
|
||||
$this -> runExample($fn, true);
|
||||
}
|
||||
|
||||
private function runExample($fn, $syntaxCheck = false)
|
||||
{
|
||||
// Change directory and check script
|
||||
chdir($this -> exampleDir);
|
||||
$this -> assertTrue(file_exists($fn), "Script $fn not found.");
|
||||
// Run command and save output
|
||||
$php = "php" . ($syntaxCheck ? " -l" : "");
|
||||
ob_start();
|
||||
passthru($php . " " . escapeshellarg($fn), $retval);
|
||||
$outp = ob_get_contents();
|
||||
ob_end_clean();
|
||||
// Check return value
|
||||
$this -> assertEquals(0, $retval, "Example $fn exited with status $retval");
|
||||
return $outp;
|
||||
}
|
||||
|
||||
protected function requireGraphicsLibrary()
|
||||
{
|
||||
if (!EscposImage::isGdLoaded() && !EscposImage::isImagickLoaded()) {
|
||||
$this -> markTestSkipped("gd or imagick plugin is required for this test");
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user