PHP Classes

How Can PHP Print to Network Printer, a Document Using the Package D3 Printer IPP: Manage printers and printing jobs using IPP

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2025-08-08 (2 days ago) RSS 2.0 feedNot yet rated by the usersTotal: Not yet counted Not yet ranked
Version License PHP version Categories
d3printer-ipp 1.0Freeware7.4Networking, PHP 5, Printing, Documents
Description 

Author

This package can manage printers and printing jobs using IPP.

It provides classes that can access to network printers using the IPP protocol, either via Web pages or the terminal console.

Currently, it can:

- Configure the list of printers that can be used to print documents

- Send PDF documents to a configured printer with specific printing options like printing job name, page size, number of copies, page sides used to print the document and printing quality

- Monitor and display aspects of a printer like the online status, paper and ink level

- List of printing jobs

- Cancel active printing jobs

- Add a new printer to the current server machine, an available printer

Picture of Uldis Nelsons
Name: Uldis Nelsons <contact>
Classes: 20 packages by
Country: Latvia Latvia
Age: 56
All time rank: 19466 in Latvia Latvia
Week rank: 195 Up1 in Latvia Latvia Up
Innovation award
Innovation award
Nominee: 13x

Winner: 2x

Instructions

Please read this document to learn how can PHP configure and print documents using network printers.

Example

<?php

use d3system\yii2\web\D3SystemView;
use
d3yii2\d3printeripp\logic\read\ReadConfiguration;
use
eaBlankonThema\assetbundles\layout\LayoutAsset;
use
eaBlankonThema\components\FlashHelper;
use
eaBlankonThema\widget\ThAlertList;
use
eaBlankonThema\widget\ThButton;
use
eaBlankonThema\widget\ThReturnButton;
use
yii\helpers\Url;

LayoutAsset::register($this);

/**
 * @var D3SystemView $this
 * @var d3yii2\d3printeripp\models\AlertSettings $model
 * @var DeviceHealth $deviceHealth
 * @var ReadConfiguration $configHealth
 * @var bool $statusOk
 * @var string $status
 * @var bool $cartridgeOk
 * @var string $cartridge
 * @var bool $drumOk
 * @var string $drum
 * @var array $lastLoggedErrors;
 * @var string $printerCode;
 * @var string $component;
 */


$this->title = 'DeviceHealth info';

$this->setPageHeader($this->title);
$this->setPageIcon('');
$this->setSettingButton([
   
'alert-settings',
   
'addSectionKey' => $printerCode,
   
'component' => $component
]);

if (
$configHealth) {
   
$configAttributeLabels = $configHealth->device->attributeLabels();
}
?>
<div class="row">
    <?= ThAlertList::widget() ?>
<div class="col-md-9">
        <div class="panel rounded shadow">
            <div class="panel-body rounded-bottom">
                <h4><?= $deviceHealth->printerName ?? '' ?></h4>
                <?php if ($deviceHealth): ?>
Status: <?= $statusOk
                       
? '<span style="color:darkgreen">' . $status . '</span>'
                       
: '<span style="color:red">' . $status . '</span>'
                   
?><br>
                    Cartridge: <?= $cartridgeOk
                   
? '<span style="color:darkgreen">' . $cartridge . '</span>'
                   
: '<span style="color:red">' . $cartridge . '</span>'
                   
?><br>
                    Drum: <?= $drumOk
                       
? '<span style="color:darkgreen">' . $drum . '</span>'
                       
: '<span style="color:red">' . $drum . '</span>'
                   
?>
<?php endif; ?>
<hr>
                <?= ThButton::widget([
                   
'type' => ThButton::TYPE_PRIMARY,
                   
'label' => 'Set Printer defaults',
                   
'link' => Url::to(['set-default-settings', 'component' => Yii::$app->request->get('component')])
                ])
?>
</div>
        </div>
        <div class="panel rounded shadow">
            <div class="panel-body rounded-bottom">
                <h4>Print Settings</h4>
                <?php
               
if ($configHealth) {
                    foreach (
$configHealth->device->printSettings() as $key => $value) {
                        echo
$configAttributeLabels[$key] . ': ' . $value . '<br>';
                    }
                }
?>
</div>
        </div>
        <div class="panel rounded shadow">
            <div class="panel-body rounded-bottom">
                <h4>Paper Settings</h4>
                <?php
               
if ($configHealth) {
                    foreach (
$configHealth->device->paperSettings() as $key => $value) {
                        echo
$configAttributeLabels[$key] . ': ' . $value . '<br>';
                    }
                }
?>
</div>
        </div>
        <div class="panel rounded shadow">
            <div class="panel-body rounded-bottom">
                <h4>Energy Settings</h4>
                <?php
               
if ($configHealth) {
                    foreach (
$configHealth->device->energySettings() as $key => $value) {
                        echo
$configAttributeLabels[$key] . ': ' . $value . '<br>';
                    }
                }
?>
</div>
        </div>
        <div class="panel rounded shadow">
            <div class="panel-body rounded-bottom">
                <h4>Last Errors</h4>
                <?php
               
foreach ($lastLoggedErrors as $error) {
                    echo
str_replace(PHP_EOL, '<br>', $error) . '<hr>';
                }
?>
</div>
        </div>
    </div>
</div>


Details

IPP Printer Manager for Yii2

A PHP 7.4+ package for managing IPP printers in Yii2 applications using the nateobray/IPP library.

Installation

composer require yourcompany/yii2-ipp-printer-manager

Configuration

Add the component to your config/web.php:

'components' => [
    'printerManager' => [
        'class' => 'app\components\PrinterManagerComponent',
        'autoConnect' => false,
        'healthCheckInterval' => 300, // 5 minutes
        'printers' => [
            'office_hp_laser' => [
                'type' => 'hp',
                'host' => '192.168.1.100',
                'port' => 631,
                'username' => 'admin',
                'password' => 'secure_password',
                'timeout' => 30,
                'encryption' => false
            ],
            'warehouse_canon' => [
                'type' => 'canon',
                'host' => '192.168.1.101',
                'port' => 631,
                'pincode' => '1234',
                'encryption' => true,
                'timeout' => 45
            ],
            'reception_generic' => [
                'type' => 'generic',
                'host' => '192.168.1.102',
                'port' => 631,
                'timeout' => 20
            ]
        ]
    ]
],

Usage Examples

Basic Printing

// In your controller
public function actionPrint()
{
    $printerManager = \Yii::$app->printerManager;
    
    // Load document (PDF, PostScript, etc.)
    $document = file_get_contents('/path/to/document.pdf');
    
    // Print options
    $options = [
        'job-name' => 'Invoice #12345',
        'copies' => 1,
        'media' => 'iso_a4_210x297mm',
        'sides' => 'one-sided',
        'print-quality' => 'high'
    ];
    
    try {
        $result = $printerManager->print('office_hp_laser', $document, $options);
        
        if ($result['success']) {
            return $this->asJson([
                'status' => 'success',
                'job_id' => $result['job-id'],
                'message' => 'Document queued for printing'
            ]);
        }
    } catch (\Exception $e) {
        return $this->asJson([
            'status' => 'error',
            'message' => $e->getMessage()
        ]);
    }
}

Health Monitoring

// Check all printers health
public function actionHealthDashboard()
{
    $printerManager = \Yii::$app->printerManager;
    $health = $printerManager->getHealthStatus();
    
    $summary = [];
    foreach ($health as $name => $status) {
        $summary[$name] = [
            'online' => $status['online'],
            'supplies' => $this->formatSupplies($status['supplies'] ?? []),
            'last_check' => $status['last_check']
        ];
    }
    
    return $this->render('health', ['printers' => $summary]);
}

private function formatSupplies(array $supplies): array
{
    $formatted = [];
    foreach ($supplies as $supply) {
        $formatted[] = [
            'name' => $supply['name'],
            'level' => $supply['level'],
            'status' => $supply['status'],
            'color' => $supply['color'] ?? 'unknown'
        ];
    }
    return $formatted;
}

Job Management

// Get printer jobs
public function actionJobs($printerName)
{
    $printer = \Yii::$app->printerManager->getPrinter($printerName);
    
    if (!$printer) {
        throw new NotFoundHttpException('Printer not found');
    }
    
    $jobs = $printer->getJobs();
    
    return $this->asJson([
        'printer' => $printerName,
        'jobs' => $jobs
    ]);
}

// Cancel job
public function actionCancelJob($printerName, $jobId)
{
    $printer = \Yii::$app->printerManager->getPrinter($printerName);
    $success = $printer->cancelJob((int)$jobId);
    
    return $this->asJson([
        'success' => $success,
        'message' => $success ? 'Job cancelled' : 'Failed to cancel job'
    ]);
}

Dynamic Printer Management

// Add printer at runtime
public function actionAddPrinter()
{
    $config = [
        'type' => 'hp',
        'host' => '192.168.1.200',
        'port' => 631,
        'username' => 'printer_admin',
        'password' => 'printer_pass'
    ];
    
    $printerManager = \Yii::$app->printerManager;
    $printerManager->addPrinter('new_printer', $config);
    
    // Test connection
    $printer = $printerManager->getPrinter('new_printer');
    $connected = $printer->connect();
    
    return $this->asJson([
        'added' => true,
        'connected' => $connected
    ]);
}

Architecture Overview

The package follows these design patterns:

1. Strategy Pattern

Different printer types (HP, Canon, Generic) implement the same PrinterInterface but with specific behaviors.

2. Factory Pattern

PrinterFactory creates appropriate printer instances based on configuration.

3. Manager Pattern

PrinterManager orchestrates multiple printers and provides unified access.

4. Component Pattern

Yii2 integration through PrinterManagerComponent for dependency injection.

Extending the Package

Adding New Printer Types

use app\components\printer\BasePrinter;

class EpsonPrinter extends BasePrinter
{
    protected function initializeIPP(): void
    {
        parent::initializeIPP();
        
        // Epson-specific initialization
        // Set specific attributes or connection parameters
    }
    
    public function getSuppliesStatus(): array
    {
        $data = parent::getSuppliesStatus();
        
        // Epson-specific supply processing
        return $this->processEpsonSupplies($data);
    }
    
    private function processEpsonSupplies(array $supplies): array
    {
        // Custom Epson supply level interpretation
        foreach ($supplies as &$supply) {
            if ($supply['type'] === 'ink-cartridge') {
                // Epson ink cartridges might report differently
                $supply['epson_specific_data'] = $this->getEpsonInkData($supply);
            }
        }
        
        return $supplies;
    }
}

// Register the new printer type
PrinterFactory::registerPrinterType('epson', EpsonPrinter::class);

Custom Print Options

class CustomPrinter extends BasePrinter
{
    public function printJob(string $document, array $options = []): array
    {
        // Add custom pre-processing
        $document = $this->preprocessDocument($document, $options);
        
        // Add custom IPP attributes
        if (isset($options['custom_option'])) {
            $this->ipp->addAttribute('custom-attribute', $options['custom_option']);
        }
        
        return parent::printJob($document, $options);
    }
    
    private function preprocessDocument(string $document, array $options): string
    {
        // Custom document processing
        return $document;
    }
}

Console Commands

The package includes console commands for printer management:

# Check all printer health
php yii printer/health

# Test print to all printers
php yii printer/test-print

# Check specific printer status
php yii printer/status office_hp_laser

Error Handling

The package provides comprehensive error handling:

try {
    $result = $printerManager->print('printer_name', $document, $options);
} catch (\InvalidArgumentException $e) {
    // Configuration or parameter errors
    \Yii::error("Printer configuration error: " . $e->getMessage());
} catch (\Exception $e) {
    // Network, IPP, or printer errors
    \Yii::error("Printer communication error: " . $e->getMessage());
}

Testing

// Basic printer connectivity test
$printer = \Yii::$app->printerManager->getPrinter('test_printer');
$isOnline = $printer->isOnline();

// Health check test
$health = \Yii::$app->printerManager->getHealthStatus(true);
foreach ($health as $name => $status) {
    if (!$status['online']) {
        \Yii::warning("Printer {$name} is offline");
    }
}

Security Considerations

  1. Credentials Storage: Store printer credentials securely, consider using environment variables:
'printers' => [
    'secure_printer' => [
        'host' => getenv('PRINTER_HOST'),
        'username' => getenv('PRINTER_USERNAME'),
        'password' => getenv('PRINTER_PASSWORD'),
    ]
]

  1. Network Security: Use encryption when available:
'encryption' => true,
'timeout' => 30,

  1. Input Validation: Always validate print options and document content before sending to printers.

Performance Tips

  1. Connection Pooling: Set `autoConnect => false` and connect only when needed.
  2. Health Check Caching: Use the built-in caching with appropriate intervals.
  3. Async Processing: Consider using Yii2 queues for large print jobs.

Troubleshooting

Common Issues

  1. Connection Timeouts: Increase timeout values for slow networks
  2. Authentication Failures: Verify credentials and printer settings
  3. IPP Version Compatibility: Some older printers may need specific IPP versions

Debug Mode

Enable debug logging in your Yii2 configuration:

'log' => [
    'targets' => [
        [
            'class' => 'yii\log\FileTarget',
            'categories' => ['app\components\printer\*'],
            'logFile' => '@runtime/logs/printer.log',
        ],
    ],
],

  Files folder image Files (30)  
File Role Description
Files folder imageaccessRights (2 files)
Files folder imagecommands (1 file)
Files folder imagecomponents (1 file)
Files folder imagecontrollers (2 files)
Files folder imageinterfaces (1 file)
Files folder imagelogic (10 files, 2 directories)
Files folder imagemessages (1 directory)
Files folder imagemodels (2 files)
Files folder imageviews (2 directories)
Accessible without login Plain text file composer.json Data Auxiliary data
Plain text file Module.php Class Class source
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files (30)  /  accessRights  
File Role Description
  Plain text file D3PrinterFullUserRole.php Class Class source
  Plain text file D3PrinterViewPanelUserRole.php Class Class source

  Files folder image Files (30)  /  commands  
File Role Description
  Plain text file PrinterCommand.php Class Class source

  Files folder image Files (30)  /  components  
File Role Description
  Plain text file PrinterManagerComponent.php Class Class source

  Files folder image Files (30)  /  controllers  
File Role Description
  Plain text file DeviceInfoController.php Class Class source
  Plain text file InfoPanelController.php Class Class source

  Files folder image Files (30)  /  interfaces  
File Role Description
  Plain text file PrinterInterface.php Class Class source

  Files folder image Files (30)  /  logic  
File Role Description
Files folder imagepanel (1 file)
Files folder imageprinters (3 files)
  Plain text file AlertConfig.php Class Class source
  Plain text file BasePrinter.php Class Class source
  Plain text file PrinterAttributes.php Class Class source
  Plain text file PrinterConfig.php Class Class source
  Plain text file PrinterDaemon.php Class Class source
  Plain text file PrinterFactory.php Class Class source
  Plain text file PrinterHealth.php Class Class source
  Plain text file PrinterManager.php Class Class source
  Plain text file PrinterSpooler.php Class Class source
  Plain text file Request.php Class Class source

  Files folder image Files (30)  /  logic  /  panel  
File Role Description
  Plain text file DisplayDataLogic.php Class Class source

  Files folder image Files (30)  /  logic  /  printers  
File Role Description
  Plain text file CanonPrinter.php Class Class source
  Plain text file GenericIPPPrinter.php Class Class source
  Plain text file HPPrinter.php Class Class source

  Files folder image Files (30)  /  messages  
File Role Description
Files folder imagelv (1 file)

  Files folder image Files (30)  /  messages  /  lv  
File Role Description
  Accessible without login Plain text file d3printeripp.php Aux. Configuration script

  Files folder image Files (30)  /  models  
File Role Description
  Plain text file AlertSettings.php Class Class source
  Plain text file DeviceInfo.php Class Class source

  Files folder image Files (30)  /  views  
File Role Description
Files folder imagedevice-info (2 files)
Files folder imageinfo-panel (1 file)

  Files folder image Files (30)  /  views  /  device-info  
File Role Description
  Plain text file alert_settings.php Class Class source
  Accessible without login Plain text file index.php Example Example script

  Files folder image Files (30)  /  views  /  info-panel  
File Role Description
  Accessible without login Plain text file status.php Aux. Configuration script

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads  
 100%
Total:0
This week:0