You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP调用PowerShell打印PDF失败,寻求解决方案

解决方案

1. 修复Apache服务权限问题

WAMP的Apache默认以Network Service账户运行,该账户无打印机访问权限和桌面交互权限,导致PHP调用PowerShell时无法触发打印:

  • 打开服务管理器(运行services.msc),找到Apache服务(如wampapache64)
  • 右键→属性→登录标签页,选择本地系统账户,勾选允许服务与桌面交互
  • 重启Apache服务

2. 替换错误的PDF打印命令

Get-Content会把PDF二进制文件当作文本读取,导致打印大量乱码内容,改用以下稳定方案:

方案A:调用系统默认PDF阅读器的打印功能

PowerShell脚本内容:

$pdfPath = "C:\wamp64\www\Intranet\bin\ean.pdf"
$printerName = "你的打印机名称" # 可通过`Get-Printer`命令查看打印机全名

# 调用系统打印功能,等待打印完成后删除文件
Start-Process -FilePath $pdfPath -ArgumentList "/p /h $printerName" -Wait -NoNewWindow
Remove-Item -Path $pdfPath -Force

方案B:使用SumatraPDF(推荐服务器环境)

SumatraPDF是轻量无界面的PDF工具,适合服务器批量打印:

  1. 下载SumatraPDF并解压到服务器(如C:\Tools\SumatraPDF\SumatraPDF.exe)
  2. PowerShell脚本内容:
$pdfPath = "C:\wamp64\www\Intranet\bin\ean.pdf"
$printerName = "你的打印机名称"
$sumatraPath = "C:\Tools\SumatraPDF\SumatraPDF.exe"

Start-Process -FilePath $sumatraPath -ArgumentList "-print-to `"$printerName`" `"$pdfPath`"" -Wait -NoNewWindow
Remove-Item -Path $pdfPath -Force

3. 优化PHP调用逻辑

确保PHP的Process组件正确传递参数,并捕获错误日志排查问题:

use Symfony\Component\Process\Process;

$scriptPath = "C:\wamp64\www\Intranet\bin\print_pdf.ps1";
// 明确指定执行策略,避免服务账户的策略限制
$process = new Process(["powershell.exe", "-ExecutionPolicy", "Unrestricted", "-File", $scriptPath]);
$process->run();

// 记录错误日志用于排查
if (!$process->isSuccessful()) {
    file_put_contents("print_error.log", date('Y-m-d H:i:s') . ": " . $process->getErrorOutput() . PHP_EOL, FILE_APPEND);
}

4. 补充权限验证

  • 给C:\wamp64\www\Intranet\bin目录添加SYSTEM账户的读写权限
  • 打开打印机属性→安全标签页,添加SYSTEM账户并赋予打印权限

内容的提问来源于stack exchange,提问作者Jerome Pochet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 10:55:14