
本文将详细指导如何在 Symfony 3.4 应用中,将由 Snappy PDF 生成器返回的 PDF 字符串保存为服务器上的文件,并利用 qpdf 命令行 工具 对其进行密码保护,最终将受保护的 PDF 再次作为字符串返回。核心方法是利用 Symfony 的 Process 组件来执行系统命令,以克服 Snappy PDF 本身不提供密码保护功能的限制。
导言
在许多 Web 应用中,生成 PDF 文档是一项常见需求。Symfony 框架下的 Snappy Bundle(基于 wkhtmltopdf)是一个流行的选择,因为它能够将 HTML 内容转换为高质量的 PDF。然而,wkhtmltopdf 及其 Snappy 封装本身并不直接提供 PDF 密码保护功能。当业务需求要求对生成的 PDF 进行加密保护时,我们需要一种服务器端的方法来后处理这些 PDF。
本教程将展示如何通过以下步骤实现这一目标:
- 接收 Snappy PDF 生成的原始 PDF 字符串。
- 将该字符串写入服务器上的临时 PDF 文件。
- 利用 qpdf 命令行工具对临时文件进行密码保护。
- 读取受保护的 PDF 文件内容,并将其作为字符串返回。
- 清理临时文件。
前提条件
在开始之前,请确保您的服务器环境满足以下条件:
- PHP 环境: 您的 Symfony 应用运行的 PHP 环境。
- Symfony 3.4: 本教程基于 Symfony 3.4 版本。
- Snappy Bundle: 您的应用已集成并配置了 Snappy Bundle,能够生成 PDF 字符串。
- qpdf 工具: qpdf 是一个强大的命令行工具,用于 PDF 转换和操作。您需要在 Linux 服务器上安装它。
- 在基于 Debian/Ubuntu 的系统上,可以使用 sudo apt-get install qpdf 安装。
- 在基于 RedHat/CentOS 的系统上,可以使用 sudo yum install qpdf 安装。
- Symfony Process 组件: 确保您的 composer.json 中包含 symfony/process。如果未安装,请运行 composer require symfony/process。
实现步骤
我们将通过一个具体的代码示例来演示整个流程。
1. 接收 PDF 字符串
假设您已经通过 Snappy 服务生成了一个 PDF 字符串。这通常在您的控制器或服务中完成。
use KnpBundleSnappyBundleSnappyResponsePdfResponse; // …… 在您的控制器或服务中 /** @var KnpSnappyPdf $snappyPdfService */ $snappyPdfService = $this->get('knp_snappy.pdf'); // 获取 Snappy PDF 服务 // 假设 $htmlContent 是您要转换为 PDF 的 HTML 内容 $pdfString = $snappyPdfService->getOutputFromHtml($htmlContent); // $pdfString 现在包含了原始的 PDF 二进制数据
2. 将 PDF 字符串写入临时文件
为了让 qpdf 工具能够处理,我们需要将这个 PDF 字符串保存为一个实际的文件。使用临时文件是一个好的实践,因为它允许我们在处理完成后轻松删除。
use SymfonyComponentFilesystemFilesystem; // …… $fs = new Filesystem(); $tempDir = sys_get_temp_dir(); // 获取系统临时目录 $unprotectedPdfPath = $tempDir . '/' . uniqid('unprotected_', true) . '.pdf'; try {$fs->dumpFile($unprotectedPdfPath, $pdfString); } catch (Exception $e) {// 处理文件写入失败的情况 throw new RuntimeException('Failed to write unprotected PDF to temporary file:' . $e->getMessage()); }
3. 使用 qpdf 进行密码保护
这是核心步骤,我们将使用 Symfony 的 Process 组件来执行 qpdf 命令。qpdf 命令的基本语法如下:
qpdf –encrypt [user_password] [owner_password] [key_length] –print=full –modify=full — [input_file] [output_file]
- [user_password]:用户打开 PDF 时所需的密码。
- [owner_password]:所有者密码,用于更改 PDF 权限。
- [key_length]:加密强度,通常为 256。
- –print=full:允许完全打印。
- –modify=full:允许完全修改。
- –:分隔符,指示后续参数是文件路径。
- [input_file]:未受保护的 PDF 文件路径。
- [output_file]:受保护的 PDF 文件将保存的路径。
use SymfonyComponentProcessProcess; use SymfonyComponentProcessExceptionProcessFailedException; // …… $protectedPdfPath = $tempDir . '/' . uniqid('protected_', true) . '.pdf'; $password = 'YourSecurePassword123'; // 设置您的密码 // 构建 qpdf 命令 // 注意:为了安全,密码应避免直接硬编码,可以从配置或环境变量中获取 $command = ['qpdf', '--encrypt', $password, // 用户密码 $password, // 所有者密码 (通常可以设置为相同) '256', // 256 位加密 '--print=full', // 允许打印 '--modify=full', // 允许修改 '--', $unprotectedPdfPath, // 输入文件 $protectedPdfPath // 输出文件 ]; $process = new Process($command); try {$process->run(); // 检查命令是否成功执行 if (!$process->isSuccessful()) {throw new ProcessFailedException($process); } } catch (ProcessFailedException $e) {// 处理 qpdf 命令执行失败的情况 throw new RuntimeException('Failed to password protect PDF with qpdf:' . $e->getMessage() . 'Error output:' . $process->getErrorOutput()); }
4. 读取受保护的 PDF 并返回
qpdf 成功执行后,$protectedPdfPath 将指向受密码保护的 PDF 文件。我们可以读取其内容并作为字符串返回。
// …… $protectedPdfString = null; if ($fs->exists($protectedPdfPath)) {$protectedPdfString = file_get_contents($protectedPdfPath); } else {throw new RuntimeException('Protected PDF file not found after qpdf execution.'); } // $protectedPdfString 现在包含了受密码保护的 PDF 的二进制数据 // 您可以将其作为 HTTP 响应返回,或进行其他处理
5. 清理临时文件
为了避免磁盘空间浪费和文件泄露,务必在处理完成后删除所有临时文件。
// …… try {if ($fs->exists($unprotectedPdfPath)) {$fs->remove($unprotectedPdfPath); } if ($fs->exists($protectedPdfPath)) {$fs->remove($protectedPdfPath); } } catch (Exception $e) {// 记录清理失败的日志,但不中断主流程 error_log('Failed to clean up temporary PDF files:' . $e->getMessage()); }
完整代码示例(服务或控制器方法)
将以上所有步骤整合到一个方法中,例如在一个服务或控制器动作中:
<?php namespace AppBundleService; // 或您的控制器命名空间 use KnpBundleSnappyBundleSnappyResponsePdfResponse; use SymfonyComponentFilesystemFilesystem; use SymfonyComponentProcessProcess; use SymfonyComponentProcessExceptionProcessFailedException; use KnpSnappyPdf; // 假设您注入了 Snappy PDF 服务 class PdfProtectionService {private $snappyPdfService; private $filesystem; public function __construct(Pdf $snappyPdfService, Filesystem $filesystem) {$this->snappyPdfService = $snappyPdfService; $this->filesystem = $filesystem;} /** * 从 HTML 生成 PDF 并进行密码保护 * * @param string $htmlContent 要转换为 PDF 的 HTML 内容 * @param string $password PDF 的密码 * @return string 受密码保护的 PDF 二进制字符串 * @throws RuntimeException 如果在处理过程中发生错误 */ public function generateProtectedPdf(string $htmlContent, string $password): string {$unprotectedPdfPath = null; $protectedPdfPath = null; try { // 1. 从 HTML 生成原始 PDF 字符串 $pdfString = $this->snappyPdfService->getOutputFromHtml($htmlContent); // 2. 将原始 PDF 字符串写入临时文件 $tempDir = sys_get_temp_dir(); $unprotectedPdfPath = $tempDir . '/' . uniqid('unprotected_', true) . '.pdf'; $this->filesystem->dumpFile($unprotectedPdfPath, $pdfString); // 3. 使用 qpdf 进行密码保护 $protectedPdfPath = $tempDir . '/' . uniqid('protected_', true) . '.pdf'; $command = ['qpdf', '--encrypt', $password, // 用户密码 $password, // 所有者密码 '256', // 256 位加密 '--print=full', // 允许打印 '--modify=full', // 允许修改 '--', $unprotectedPdfPath, $protectedPdfPath]; $process = new Process($command); $process->run(); if (!$process->isSuccessful()) {throw new ProcessFailedException($process); } // 4. 读取受保护的 PDF 内容 if (!$this->filesystem->exists($protectedPdfPath)) {throw new RuntimeException('Protected PDF file not found after qpdf execution.'); } $protectedPdfString = file_get_contents($protectedPdfPath); return $protectedPdfString; } catch (ProcessFailedException $e) {throw new RuntimeException('Failed to password protect PDF with qpdf:' . $e->getMessage() . 'Error output:' . $process->getErrorOutput()); } catch (Exception $e) {throw new RuntimeException('Error during PDF protection process:' . $e->getMessage()); } finally {// 5. 清理临时文件 if ($unprotectedPdfPath && $this->filesystem->exists($unprotectedPdfPath)) {$this->filesystem->remove($unprotectedPdfPath); } if ($protectedPdfPath && $this->filesystem->exists($protectedPdfPath)) {$this->filesystem->remove($protectedPdfPath); } } } }
在您的控制器中,您可以这样使用这个服务:
<?php namespace AppBundleController; use SymfonyBundleFrameworkBundleControllerController; use SymfonyComponentHttpFoundationResponse; use AppBundleServicePdfProtectionService; // 引入您的服务 class DocumentController extends Controller {public function generateSecurePdfAction() {// 假设您有一些 HTML 内容 $htmlContent = $this->renderView('default/pdf_template.html.twig', [ 'data' => 'Some dynamic data for the PDF']); $password = 'MySecretDocPassword'; // 从配置或用户输入获取 /** @var PdfProtectionService $pdfProtectionService */ $pdfProtectionService = $this->get('app.pdf_protection_service'); // 假设您已将服务注册到容器中 try {$protectedPdfString = $pdfProtectionService->generateProtectedPdf($htmlContent, $password); // 返回受保护的 PDF 作为 HTTP 响应 $response = new Response($protectedPdfString); $response->headers->set('Content-Type', 'application/pdf'); $response->headers->set('Content-Disposition', 'attachment; filename="protected_document.pdf"'); return $response; } catch (RuntimeException $e) {// 处理错误,例如显示错误页面或返回 JSON 错误信息 return new Response('Error generating protected PDF:' . $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR); } } }
请确保在 app/config/services.yml 中注册您的服务:
# app/config/services.yml services: app.pdf_protection_service: class: AppBundleServicePdfProtectionService arguments: - '@knp_snappy.pdf' # 注入 Snappy PDF 服务 - '@filesystem' # 注入 Filesystem 服务
注意事项与总结
- 安全性: 在实际应用中,PDF 密码不应硬 编码。它们应该来自安全的配置、环境变量或用户输入,并且在传输和存储时应妥善处理。
- 错误处理: 务必对文件操作和 Process 组件的执行进行健壮的错误处理。捕获异常并提供有意义的错误信息对于调试和用户体验至关重要。
- 临时文件管理: finally 块确保了即使在发生错误的情况下,临时文件也能被清理,防止资源泄露。
- qpdf 路径: 如果 qpdf 不在系统 PATH 中,您可能需要在 $command 数组中指定其完整路径,例如 ‘/usr/local/bin/qpdf’。
- 并发性: 在高并发环境下,uniqid()生成的文件名碰撞概率极低,但仍需注意。如果担心,可以结合进程 ID 或其他唯一标识符。
- 性能: 将 PDF 写入磁盘并再次读取会引入一些 I / O 开销。对于极高性能要求的场景,可能需要评估这种方法的适用性。然而,对于大多数 Web 应用来说,这种开销通常是可接受的。
通过利用 Symfony 的 Process 组件,我们能够无缝地将外部命令行工具(如 qpdf)集成到 PHP 应用中,从而扩展了 Snappy PDF 生成器的功能,实现了服务器端的 PDF 密码保护。这种方法灵活且强大,适用于需要对 PDF 进行各种高级操作的场景。
以上就是在 Symfony 中处理 Snappy PDF 字符串并实现服务器端密码保护的详细内容,更多请关注 php 中文网其它相关文章!