使用base64解码在PHP中打印PDF时问题

发布于 2025-02-14 00:05:27 字数 1472 浏览 1 评论 0 原文

我正在尝试创建一个PHP程序,该程序打印了PDF,该PDF在Base64中编码为任何形式的打印机。

我已经完成了解码,并且Base64 PDF正在转换为真正的PDF。但是,当我将解码的base64发送到打印机时,它会打印出解码的字符串而不是PDF。

我的代码:

打印机IP被禁用以进行开发

<?php
error_reporting(E_ALL);

$base64 = $_POST['fileBase64'];
$printer = $_POST['printer'];

printer('', 9100, $base64);

function printer($printerIp, $printerPort, $base64): void {
    $docname = md5(date("Y-m-d-H-i-s-Z")) . '.pdf';

    // Generate the pdf from the base64
    //Decode pdf content
    $pdf_decoded = base64_decode($base64);

    //Write data back to pdf file
    $pdf = fopen ($docname,'w');
    fwrite ($pdf, $pdf_decoded);

    //close output file
    fclose ($pdf);

    // echo file_get_contents($docname);

    try {
        $fp = pfsockopen($printerIp, $printerPort, $errno, $errstr);

        if ($fp === false) {
            echo 'Connection Failed! ' . $errno . ' ' . $errstr;
        } else {
            fputs($fp, file_get_contents($docname), filesize($docname));
            fclose($fp);

            echo "Successfully printed";

            // If done then delete pdf and clear text file
            exec("rm -rf '" . $docname . "'");
        }
    } catch (Exception $e) {
        echo $e->getMessage();
        exit;
    }
}

file_get_contents()的输出:

I'm trying to create a PHP program which prints a pdf which is encoded in Base64 to any kind of printer.

I already got the decoding done and the base64 pdf is being converted to a real PDF. However when I send the decoded Base64 to the printer it prints out the decoded string and not a PDF.

My code:

Printer ip is disabled for development

<?php
error_reporting(E_ALL);

$base64 = $_POST['fileBase64'];
$printer = $_POST['printer'];

printer('', 9100, $base64);

function printer($printerIp, $printerPort, $base64): void {
    $docname = md5(date("Y-m-d-H-i-s-Z")) . '.pdf';

    // Generate the pdf from the base64
    //Decode pdf content
    $pdf_decoded = base64_decode($base64);

    //Write data back to pdf file
    $pdf = fopen ($docname,'w');
    fwrite ($pdf, $pdf_decoded);

    //close output file
    fclose ($pdf);

    // echo file_get_contents($docname);

    try {
        $fp = pfsockopen($printerIp, $printerPort, $errno, $errstr);

        if ($fp === false) {
            echo 'Connection Failed! ' . $errno . ' ' . $errstr;
        } else {
            fputs($fp, file_get_contents($docname), filesize($docname));
            fclose($fp);

            echo "Successfully printed";

            // If done then delete pdf and clear text file
            exec("rm -rf '" . $docname . "'");
        }
    } catch (Exception $e) {
        echo $e->getMessage();
        exit;
    }
}

Output of file_get_contents():

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文