
本文将详细指导如何在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字符串。这通常在您的控制器或服务中完成。
use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
// ... 在您的控制器或服务中
/** @var \Knp\Snappy\Pdf $snappyPdfService */
$snappyPdfService = $this->get('knp_snappy.pdf'); // 获取Snappy PDF服务
// 假设 $htmlContent 是您要转换为PDF的HTML内容
$pdfString = $snappyPdfService->getOutputFromHtml($htmlContent);
// $pdfString 现在包含了原始的PDF二进制数据为了让qpdf工具能够处理,我们需要将这个PDF字符串保存为一个实际的文件。使用临时文件是一个好的实践,因为它允许我们在处理完成后轻松删除。
use Symfony\Component\Filesystem\Filesystem;
// ...
$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());
}这是核心步骤,我们将使用Symfony的Process组件来执行qpdf命令。qpdf命令的基本语法如下:
qpdf --encrypt [user_password] [owner_password] [key_length] --print=full --modify=full -- [input_file] [output_file]
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
// ...
$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());
}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响应返回,或进行其他处理为了避免磁盘空间浪费和文件泄露,务必在处理完成后删除所有临时文件。
// ...
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 AppBundle\Service; // 或您的控制器命名空间
use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Knp\Snappy\Pdf; // 假设您注入了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 AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Service\PdfProtectionService; // 引入您的服务
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: AppBundle\Service\PdfProtectionService
arguments:
- '@knp_snappy.pdf' # 注入Snappy PDF服务
- '@filesystem' # 注入Filesystem服务通过利用Symfony的Process组件,我们能够无缝地将外部命令行工具(如qpdf)集成到PHP应用中,从而扩展了Snappy PDF生成器的功能,实现了服务器端的PDF密码保护。这种方法灵活且强大,适用于需要对PDF进行各种高级操作的场景。
以上就是在Symfony中处理Snappy PDF字符串并实现服务器端密码保护的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号