在centos中将docx变为pdf需要libreoffice包来支撑,有了libreoffice,则方便了多
- 下载libreoffice,可以去官网下载最新版本,然后在centos中安装,libreoffice官方网址:
libreoffice官方网址 - 安装libreoffice:
- 解压:tar -zxvf LibreOffice_7.0.4_Linux_x86-64_rpm.tar.g(我这里下载的最新的)
- cd LibreOffice_7.0.4.2_Linux_x86-64_rpm
- cd RPMS
- yum localinstall *.rpm
- 安装其他依赖:
yum install cairo cups-libs libSM
yum install ibus
yum install libreoffice-headless - 检查是否安装成功
libreoffice -help - 将window环境字体拷贝至linux中,windows文件夹 C:\windows\Fonts文件夹中所有内容拷贝至 linux中/usr/share/fonts/chinese文件夹下,没有就新建(注意,拷贝完成之后要看下有没有真正拷贝过去)
- 修改字体缓存、权限
chmod -R 755 /usr/share/fonts/chinese
fc-cache -fv(安装字体)
fc-list | grep chinese //查看安装的新字体 - 生成pdf命令:
libreoffice7.0 --headless --convert-to pdf /home/xxx.docx ------直接生成在了docx文件同目录下,有同名的文件会覆盖掉
libreoffice7.0 --headless --convert-to pdf /home/xxx.docx --outdir /home/jianli -------指定了输出路径 - 在django中代码的实现:
视图中:
from .utils import docxpdf_linux
class WordPdfAPIView(GenericAPIView):
"""将word变为pdf"""
permission_classes = [IsAuthenticated]
def get(self, request):
docxPath = "docx的路径"
pdfPath = "pdf的路径"
is_succeed = docxpdf_linux(docxPath, pdfPath)
if is_succeed:
return APIResponse.fail(data=[], message="保存失败,请重试!")
return APIResponse.success(data=[], message="保存成功")
util中:
import subprocess
import os
import sys
def docxpdf_linux(docxPath, pdfPath):
"""
将word转化为pdf
"""
cmd = 'libreoffice7.0 --headless --convert-to pdf /home/sundries/简历demo.docx --outdir /home/sundries/简历'
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait(timeout=10)
stdout, stderr = p.communicate()
if stderr:
return 1
return 0
urls中:
path('user/word', views.WordPdfAPIView.as_view()),
结果:
9. 如何自定义生成pdf:
链接地址