rafaelcecchin/cups-printer

本包最新版本(v1.0.0)没有提供许可证信息。

简单的CUPS打印机

v1.0.0 2024-07-29 14:20 UTC

This package is auto-updated.

Last update: 2024-09-29 14:47:43 UTC


README

在花费大量时间寻找一个简单的方法直接从PHP打印文件后,我决定创建自己的Composer库。🚀

composer require rafaelcecchin/cups-printer

最初,我以为找到适用于不同环境的解决方案会更容易,但我错了。许多现有的CUPS + PHP打印解决方案都过时了,涉及大量代码,并且忽视了许多开发者使用Windows进行开发而Linux用于生产环境的事实。🖥️➡️🐧

本项目利用了CUPS命令

lp -h [printerServer] -d [printerName] [fileLocation]

“但是,对于我提到的那些情况,比如我在Windows开发环境和Linux生产环境工作,怎么办?” 🌐

它也可以工作,而且解决方案比你想象的简单。下面我会解释更多。 👇

如何使用

这里是一个代码片段,展示了库的功能。 📜

use RafaelCecchin\CupsPrinter\CupsPrinter;

$printerServer = '192.168.0.100';
$printerName = 'L8360CDW-Rafael';

$printer = new CupsPrinter($printerServer, $printerName);

/* Print an existing file */
$fileLocation = '/var/docs/test.pdf';
$printer->printFile($fileLocation);

/* Save the content to a temporary file before printing */
$output = $pdf->output();
$printer->printData($output);

/* Save the buffer content to a temporary file before printing */
$print = $printer->obPrint(function () use ($pdf) {
    $pdf->stream("dompdf_out.pdf", array("Attachment" => false));
});

唯一的要求是主机必须已安装cups-client。 🛠️

在Linux上,您可以运行

sudo apt-get update
sudo apt-get install cups-client

在Windows上,一种解决方案是从Windows Store下载Linux。是的,现在可以通过WSL技术实现这一点。只需访问Windows Store,搜索您想要的Linux发行版,并在其中安装cups-client

在您的项目中,您应该创建一个扩展CupsPrinter的类,并使用多态原则重写cmdPrintCommand函数。以下是我如何做到这一点的示例。 🧩

use RafaelCecchin\CupsPrinter\CupsPrinter;

class Printer extends CupsPrinter
{
    function __construct(String $printerServer, String $printerName)
    {
        parent::__construct($printerServer, $printerName);
    }

    public function cmdPrintCommand(String $fileLocation)
    {
        $env = getenv('APP_ENV');
        $cmd = '';

        if ($env == 'DEV') {
            $cmd .= "ubuntu run ";
            $fileLocation = $this->convertWindowsPathToUnix($fileLocation);
        }

        $cmd .= "lp -h $this->printerServer -d $this->printerName $fileLocation";
        
        return $cmd;
    }

    private function convertWindowsPathToUnix(String $fileLocation)
    {
        $fileLocation = str_replace('\\', '/', $fileLocation);
        $fileLocation = preg_replace_callback(
            '/^([a-zA-Z]):/',
            function ($matches) {
                return '/mnt/' . strtolower($matches[1]);
            },
            $fileLocation
        );

        return $fileLocation;
    }
}

在这种情况下,我从Windows Store下载了Ubuntu。要在其中运行命令,我在lp命令前加上ubuntu run ,并且还将文件路径调整为Unix格式,在驱动器字母前添加/mnt/

很简单,对吧? 😎

希望这个解决方案对您有意义! 😊