使用 libreoffice 将 docx 文件转换为 pdf 时显示错误

问题描述 投票:0回答:1

我以 html 形式上传 docx 文件,然后我想在 ubuntu 服务器中将此文件转换为 pdf,但它在 /add-document 处显示类似 CalledProcessError 的错误 命令 '['libreoffice', '--headless', '--convert-to', 'pdf', '/var/www/html/dev/media/documents/Lavender_Bay_Boatshed_Website_Testing_61gWm6r.docx', '--outdir', '/var/www/html/dev/media/documents/Lavender Bay Boatshed Website Test.pdf']' 返回非零退出状态 77。

@login_required
def add_document(request):
    title = "Add document"
    if request.method == 'POST':
        file = request.FILES.get('file')
        check = request.POST.get('check')
        
        subject = request.POST.get('subject')
        message = request.POST.get('message')
        print(request.POST)

        names = []
        emails = []
        for key in request.POST:
            
            if key.startswith('email_'):
                emails.append(request.POST[key])
            elif key.startswith('name_'):
                names.append(request.POST[key])
        print(emails)
        print(names)
        recipients = []
        list_of_dicts = [{'email': email, 'name': name} for email, name in zip(emails, names)]
        if file:
            if (file.name.endswith('.jpg')) or (file.name.endswith('.png')):
                obj = Documents(document=file,name=file.name,user=request.user)
                obj.save()
                image = Image.open(obj.document.path)
                iml = image.convert('RGB')
                folder = r'C:\Users\admin\Desktop\projects\Document-sign\media\documents'
                path = os.path.join(folder, file.name.split('.')[0] + '.pdf')
                os.remove(obj.document.path)
                iml.save(path)
                obj.document = f"documents/{file.name.split('.')[0]}.pdf"
                obj.save()
                os.remove(obj.document.path)
                if check:
                    request.session['check'] = False
                    return redirect('sign_document')
                else:
                    recipients.append({'emails':list_of_dicts,'subject':subject,'message':message})
                    request.session['recipients'] = recipients
                    request.session['check'] = True
                    return redirect('make_envelope')
                
            elif file.name.endswith('.docx'):
                obj = Documents(document=file, name=file.name, user=request.user)
                obj.save()

                # Define paths
                path = os.path.join(settings.MEDIA_ROOT, 'documents')
                input_path = obj.document.path
                

                # Run LibreOffice conversion
                try:
                    result = subprocess.run(
                        ['libreoffice', '--headless', '--convert-to', 'pdf', input_path, '--outdir', path],
                        check=True,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE
                    )
                    print(result.stdout)
                    print(result.stderr)
                except subprocess.CalledProcessError as e:
                    print("Error occurred:", e.stderr)
                    raise

                # Remove the original DOCX file
                os.remove(input_path)

                # Update the document path to the converted PDF
                obj.document = f"documents/{file.name.split('.')[0]}.pdf"
                obj.save()
                
                if check:
                    request.session['check'] = False
                    return redirect('sign_document')
                else:
                    recipients.append({'emails':list_of_dicts,'subject':subject,'message':message})
                    request.session['recipients'] = recipients
                    request.session['check'] = True
                    return redirect('make_envelope')
            else:
                obj = Documents(document=file,name=file.name,user=request.user)
                obj.save()
                if check:
                    
                    request.session['check'] = False
                    return redirect('sign_document')
                else:
                    recipients.append({'emails':list_of_dicts,'subject':subject,'message':message})
                    print(recipients)
                    request.session['recipients'] = recipients
                    request.session['check'] = True
                    return redirect('make_envelope')   
            
    context = {'title':title}
    return render(request, 'myapp/add_document.html',context=context)

python django pdf-generation docx libreoffice
1个回答
0
投票

我们可能需要一些额外的信息。尝试从以下几点开始:

1- 验证要转换的文件的路径 (

obj.document.path
) 是否正确。您只需在调用 libreoffice 之前添加
os.path.isfile(obj.document.path)
即可完成此操作。

2- 确保您的环境中安装了 libreoffice:

libreoffice --version

3-尝试使用

--convert-to pdf:writer_pdf_Export
而不仅仅是
--convert-to pdf

4-确保输出目录存在

5-确保没有打开 libreoffice 的 GUI 实例

© www.soinside.com 2019 - 2024. All rights reserved.