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

Node html-pdf包生成PDF时Ubuntu服务器编码图片URL无法显示问题

html-pdf Ubuntu环境远程图片加载失败解决方案
  • 首先排查基础依赖和网络问题
    html-pdf底层依赖phantomjs运行,Ubuntu环境默认缺少phantomjs运行所需的动态库,先执行命令安装依赖:
sudo apt install -y libfontconfig1 libfreetype6 libssl-dev libjpeg-dev libpng-dev

安装完成后在服务器终端执行curl命令测试目标图片URL是否可正常访问,排除服务器防火墙、出口代理、DNS解析等网络问题:

curl -I "你的图片完整URL"

如果返回状态码不是200,先解决网络层面的访问问题。

  • 调整html-pdf启动配置
    调用生成PDF的方法时,传入phantomjs运行参数,关闭web安全限制、允许远程资源访问、忽略SSL证书校验,避免证书或跨域限制导致资源加载失败:
const pdf = require('html-pdf')
const config = {
  phantomArgs: [
    '--web-security=no',
    '--local-to-remote-url-access=yes',
    '--ignore-ssl-errors=yes',
    '--ssl-protocol=any'
  ],
  timeout: 30000 // 延长超时时间,避免大图片加载超时
}
pdf.create(html内容, config).toFile('输出路径.pdf', (err, res) => {
  // 你的回调逻辑
})
  • 规避URL编码处理差异
    mac和Ubuntu对长编码URL的底层处理逻辑存在差异,最稳妥的解决方案是先将远程图片下载到本地临时目录,再替换img标签的src为本地文件绝对路径,完全避开phantomjs的远程资源加载逻辑:
const axios = require('axios')
const fs = require('fs')
const path = require('path')
const os = require('os')

// 下载远程图片到临时目录
async function downloadImage(url) {
  const tempPath = path.join(os.tmpdir(), `chart_${Date.now()}.png`)
  const response = await axios({
    url,
    method: 'GET',
    responseType: 'stream'
  })
  return new Promise((resolve, reject) => {
    response.data.pipe(fs.createWriteStream(tempPath))
      .on('finish', () => resolve(tempPath))
      .on('error', reject)
  })
}

// 使用示例
const imgUrl = '你的quickchart图片链接'
const localImgPath = await downloadImage(imgUrl)
// 替换html中img的src为`file://${localImgPath}`
const html = `<img src="file://${localImgPath}" alt="chart" style="width:100%" />`
// 生成pdf完成后删除临时文件
pdf.create(html, config).toFile('output.pdf', (err, res) => {
  fs.unlinkSync(localImgPath)
  // 其余逻辑
})
  • 统一phantomjs版本
    如果上述方案都无效,检查服务器和本地的phantomjs版本是否一致,优先使用html-pdf自带的phantomjs-prebuilt依赖,不要使用Ubuntu系统全局安装的phantomjs,避免版本兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:15:03