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

如何将FPDI生成的PDF通过PHP上传至Cloudinary?

解决FPDI生成PDF上传Cloudinary的问题

问题原因

Cloudinary的uploadFile方法默认仅支持传入文件路径或符合PHP上传规范的文件对象(如$_FILES中的结构),直接传入FPDI通过Output('', 'S')生成的PDF二进制字符串,会被识别为无效路径,导致上传空内容;而直接调用$pdf->Output()不带参数时,会直接向浏览器输出PDF内容,无法返回给Cloudinary用于上传。

解决方案

以下两种方法均可解决问题:

方法1:通过临时文件上传(兼容性好)

把PDF内容写入临时文件,再让Cloudinary读取该文件完成上传:

$pdf = new FPDI();
$pdf->setSourceFile("https://testwebsite.com/test.pdf");
$page= $pdf->importPage(1);
$pdf->addPage();
$pdf->useTemplate($page);

// 获取PDF二进制内容
$pdfContent = $pdf->Output('', 'S');

// 创建临时存储文件
$tempFilePath = tempnam(sys_get_temp_dir(), 'temp_pdf_');
file_put_contents($tempFilePath, $pdfContent);

// 上传到Cloudinary,指定资源类型为raw(PDF属于原始文件)
$uploadResult = Cloudinary::uploadFile($tempFilePath, [
    'resource_type' => 'raw'
]);
$uploadedFileUrl = $uploadResult->getSecurePath();

// 上传完成后删除临时文件
unlink($tempFilePath);

方法2:直接上传二进制内容(更高效)

使用Cloudinary的upload方法直接传入PDF二进制字符串,无需创建临时文件:

$pdf = new FPDI();
$pdf->setSourceFile("https://testwebsite.com/test.pdf");
$page= $pdf->importPage(1);
$pdf->addPage();
$pdf->useTemplate($page);

// 获取PDF二进制内容
$pdfContent = $pdf->Output('', 'S');

// 直接上传二进制内容,指定资源类型为raw
$uploadResult = Cloudinary::upload($pdfContent, [
    'resource_type' => 'raw',
    'public_id' => 'custom_pdf_name' // 可选,自定义Cloudinary上的文件名
]);
$uploadedFileUrl = $uploadResult->getSecurePath();

关键注意点

  • 必须指定resource_type为raw:Cloudinary默认会把上传内容当作图片处理,PDF属于原始文档类型,明确指定后才能正确存储和返回访问链接。
  • 调用Output时要传入第二个参数'S':该参数让FPDI返回PDF的二进制字符串,而不是直接输出到浏览器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:06:14