Laravel 5.5使用FpdiProtection设置PDF密码报错求助
解决Laravel 5.5中使用FpdiProtection给PDF加密时的类型错误
这个错误原因很清晰——setSourceFile()方法并不接受Laravel的Illuminate\Http\UploadedFile实例作为参数,它需要的是文件路径字符串或者setasign\Fpdi\PdfParser\StreamReader对象。咱们直接调整代码就能解决问题:
方案1:直接使用上传文件的临时路径
Laravel的UploadedFile提供了getPathname()方法,可以获取文件的临时存储路径,直接把这个路径传给setSourceFile即可:
use setasign\FpdiProtection\FpdiProtection; // 获取上传文件的临时路径 $uploadedFile = $request->file('file'); $filePath = $uploadedFile->getPathname(); $pdf = new FpdiProtection(); $pagecount = $pdf->setSourceFile($filePath); for ($i = 1; $i <= $pagecount; $i++) { $tplidx = $pdf->importPage($i); $specs = $pdf->getTemplateSize($tplidx); $pdf->addPage($specs['orientation'], [ $specs['width'], $specs['height'] ]); $pdf->useTemplate($tplidx); } $pdf->setProtection( FpdiProtection::PERM_PRINT | FpdiProtection::PERM_COPY, 'the user password', 'the owner password' ); $pdf->save($FilePathPdf);
方案2:使用StreamReader包装文件流
如果你更倾向于处理流对象,可以用StreamReader来包装上传文件的流,记得先导入这个类:
use setasign\FpdiProtection\FpdiProtection; use setasign\Fpdi\PdfParser\StreamReader; $uploadedFile = $request->file('file'); // 从文件路径创建StreamReader实例 $streamReader = StreamReader::createByFile($uploadedFile->getPathname()); $pdf = new FpdiProtection(); $pagecount = $pdf->setSourceFile($streamReader); // 后续的页面导入、加密逻辑和上面一致 for ($i = 1; $i <= $pagecount; $i++) { $tplidx = $pdf->importPage($i); $specs = $pdf->getTemplateSize($tplidx); $pdf->addPage($specs['orientation'], [ $specs['width'], $specs['height'] ]); $pdf->useTemplate($tplidx); } $pdf->setProtection( FpdiProtection::PERM_PRINT | FpdiProtection::PERM_COPY, 'the user password', 'the owner password' ); $pdf->save($FilePathPdf);
额外检查
确保你已经通过Composer正确安装了依赖包,如果还没安装的话,运行这条命令:
composer require setasign/fpdi-protection
内容的提问来源于stack exchange,提问作者Muhaamad Umar
相关产品推荐
相关产品推荐

