centos7下使用python将docx变为pdf

56 篇文章 1 订阅
35 篇文章 1 订阅

在centos中将docx变为pdf需要libreoffice包来支撑,有了libreoffice,则方便了多

  1. 下载libreoffice,可以去官网下载最新版本,然后在centos中安装,libreoffice官方网址:
    libreoffice官方网址
  2. 安装libreoffice:
    1. 解压:tar -zxvf LibreOffice_7.0.4_Linux_x86-64_rpm.tar.g(我这里下载的最新的)
    2. cd LibreOffice_7.0.4.2_Linux_x86-64_rpm
    3. cd RPMS
    4. yum localinstall *.rpm
  3. 安装其他依赖:
    yum install cairo cups-libs libSM
    yum install ibus
    yum install libreoffice-headless
  4. 检查是否安装成功
    libreoffice -help
  5. 将window环境字体拷贝至linux中,windows文件夹 C:\windows\Fonts文件夹中所有内容拷贝至 linux中/usr/share/fonts/chinese文件夹下,没有就新建(注意,拷贝完成之后要看下有没有真正拷贝过去)
  6. 修改字体缓存、权限
    chmod -R 755 /usr/share/fonts/chinese
    fc-cache -fv(安装字体)
    fc-list | grep chinese //查看安装的新字体
  7. 生成pdf命令:
    libreoffice7.0 --headless --convert-to pdf /home/xxx.docx ------直接生成在了docx文件同目录下,有同名的文件会覆盖掉
    libreoffice7.0 --headless --convert-to pdf /home/xxx.docx --outdir /home/jianli -------指定了输出路径
  8. 在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:
链接地址

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值