使用DocuSign API PHP下载已签署PDF返回损坏文件怎么办?
问题原因
你的代码错误地将临时文件的路径字符串写入PDF文件,而非文件的二进制内容,导致文件损坏。$response->getPathName()返回的是SDK保存下载内容的临时文件路径,不是文件本身的内容。
修复方案
有两种可靠的修复方式:
方式1:读取临时文件内容写入目标文件
直接读取临时文件的二进制内容,再写入目标文件:
try { $envelopesApi = new EnvelopesApi($apiClient); $response = $envelopesApi->getDocument('ACCOUNT_ID', $documentId, $envelopeId); // 读取临时文件的二进制内容 $fileContents = file_get_contents($response->getPathName()); // 写入目标文件,二进制模式更安全 file_put_contents('path/filename.pdf', $fileContents, FILE_BINARY); echo 'Signed document downloaded successfully.'; } catch (ApiException $e) { echo 'Error while downloading the signed document: ' . $e->getMessage(); } die;
方式2:直接复制流内容(适合大文件)
利用文件流复制内容,避免占用过多内存:
try { $envelopesApi = new EnvelopesApi($apiClient); $response = $envelopesApi->getDocument('ACCOUNT_ID', $documentId, $envelopeId); // 打开源文件流和目标文件流 $sourceStream = fopen($response->getPathName(), 'rb'); $targetStream = fopen('path/filename.pdf', 'wb'); // 复制流内容 stream_copy_to_stream($sourceStream, $targetStream); // 关闭流资源 fclose($sourceStream); fclose($targetStream); echo 'Signed document downloaded successfully.'; } catch (ApiException $e) { echo 'Error while downloading the signed document: ' . $e->getMessage(); } die;
额外提示
- 确保目标路径
path/filename.pdf具备写入权限,必要时可添加权限检查。 - 若需下载信封内所有签署文档的合并PDF,可将
$documentId设为'combined'。
内容的提问来源于stack exchange,提问作者DavidG
相关产品推荐
相关产品推荐

