本文介绍如何在wordpress插件中修改现有pdf生成逻辑,实现在用户下载快递标签pdf的同时,将同一份pdf文件自动保存至服务器指定目录,避免重复请求第三方api。
要在生成DPD快递标签PDF时同时保存到服务器(而不仅限于响应客户端下载),关键是在get_labels_output()函数中,在输出PDF内容给浏览器之前,先将其写入服务器磁盘。当前代码通过echo $pdf直接将二进制PDF流发送至HTTP响应,随后调用die终止脚本——我们只需在echo前插入文件写入逻辑即可。
private function get_labels_output( $pdf, $file_name = 'dpdLabels' ) {
$name = $file_name . '-' . date( 'Y-m-d-His' ) . '.pdf'; // 增加秒级时间戳,避免同日重名
$upload_dir = wp_upload_dir(); // 推荐使用WordPress标准上传目录
$save_path = $upload_dir['path'] . '/' . $name; // 如:/wp-content/uploads/2025/06/dpdLabels-2025-06-15-143022.pdf
// ✅ 安全写入:确保目录可写且路径合法
if ( ! is_writable( $upload_dir['path'] ) ) {
error_log( "PDF save failed: upload directory not writable — {$upload_dir['path']}" );
// 可选:降级处理或抛出用户提示(需配合前端)
} else {
$bytes_written = file_put_contents( $save_path, $pdf );
if ( $bytes_written === false ) {
error_log( "PDF save failed: unable to write file — {$save_path}" );
}
}
// ? 保持原有下载行为不变
header( 'Content-Description: File Transfer' );
header( 'Content-Type: application/pdf' );
header( 'Content-Disposition: attachment; filename="' . $name . '"' );
header( 'Content-Transfer-Encoding: binary' );
header( 'Connection: Keep-Alive' );
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
header( 'Pragma: public' );
echo $pdf;
die;
}
通过以上改造,每次调用 print_order_parcel_label() 生成标签时,PDF既会触发浏览器下载,也会静默持久化至服务器,为后续审计、重发或批量导出提供可靠数据源。