使用Wkhtmltopdf与pdfkit生成PDF后Ubuntu无法复制文本问题
问题解决:Ubuntu下Wkhtmltopdf生成PDF无法复制文本
核心原因及解决办法
1. 字体缺失导致文本位图化
Ubuntu默认没有Windows常用字体(如宋体、微软雅黑),如果HTML模板依赖这类字体,wkhtmltopdf会 fallback 到系统替代字体,甚至直接把文本渲染成位图,导致无法复制。
解决步骤:
- 安装开源中文字体(适配中文场景):
sudo apt install fonts-wqy-microhei fonts-wqy-zenhei sudo fc-cache -fv - 若需Windows字体,可安装微软字体包:
sudo apt install ttf-mscorefonts-installer sudo fc-cache -fv - 在HTML模板的CSS中明确指定已安装字体:
body { font-family: "WenQuanYi Micro Hei", Arial, sans-serif; }
2. Wkhtmltopdf版本兼容性问题
Windows与Ubuntu上的wkhtmltopdf版本差异可能导致渲染逻辑不同,旧版本易出现文本转位图的bug。
解决步骤:
- 检查当前版本:
wkhtmltopdf --version - 更新到最新稳定版:
sudo apt remove wkhtmltopdf sudo apt install -y software-properties-common sudo add-apt-repository ppa:linuxuprising/libwkhtmltox sudo apt update sudo apt install wkhtmltopdf
3. 配置参数缺失
现有配置缺少确保文本可复制的关键参数,需补充调整:
options={ 'no-outline': None, 'page-size': 'A4', 'margin-top': '0.2in', 'margin-bottom': '0.55in', 'margin-right': '0.1in', 'margin-left': '0.1in', 'encoding': "utf-8", 'footer-font-size': "7", 'footer-spacing':5, 'header-font-size':"8", 'footer-right': "Page [page] of [topage]", 'footer-center':"Madoverbuildings AI Private Ltd.", 'custom-header': [ ('Accept-Encoding', 'gzip') ], # 新增关键参数 'enable-local-file-access': None, # 确保本地字体/资源可加载 'disable-smart-shrinking': None, # 阻止文本被压缩为位图 'dpi': '96', # 设定标准DPI,保证文本渲染精度 }
4. HTML模板样式问题
过度使用复杂CSS(如transform、绝对定位嵌套)可能触发wkhtmltopdf的位图渲染逻辑。
- 简化模板布局,避免非必要的CSS变换
- 确认文本内容未被设置为背景图片或其他非文本元素
验证测试
修改完成后,可用命令行直接测试HTML模板,排查渲染问题:
wkhtmltopdf --enable-local-file-access --disable-smart-shrinking your_template.html test_output.pdf
内容的提问来源于stack exchange,提问作者Abhijeet Gupta
相关产品推荐
相关产品推荐

