尝试使用 django 编辑 ms word 文档并另存为 pdf

Trying to edit a ms word document and save as a pdfusing django

我想从 ms excel 文件中读取数据,并使用 excel 中的数据编辑现有的 word 文档以填充书签,然后将其另存为 pdf。到目前为止,我已经能够使用 openpyxl 成功读取数据,但我正在努力处理编辑和保存部分。如果有人能提供帮助就太好了。

我的代码:

from django.shortcuts import render
from django.http import HttpResponse
import openpyxl
from reportlab.pdfgen import canvas
import io
from io import BytesIO


def index(request):
    if "GET" == request.method:
        return render(request, 'letters/index.html', {})
    else:
        excel_file = request.FILES["excel_file"]

        # you may put validations here to check extension or file size

        wb = openpyxl.load_workbook(excel_file)

        # getting a particular sheet by name out of many sheets
        worksheet = wb.sheetnames
        if 'sheet name' in wb.sheetnames:
            sheet = wb['sheet name']
        print(worksheet)

        excel_data = list()
        # iterating over the rows and
        # getting value from each cell in row
        for name in wb.sheetnames:
            sheet = wb[name]
            first = False
            for row in sheet.iter_rows():
                row_data = list()
                for cell in row:
                    row_data.append(str(cell.value))
                print (row_data)
                
                if first == False:
                    pass
                else:
                    buffer = io.BytesIO()
                    p = canvas.Canvas(buffer)
                    f = open("media/template.docx", "w+")
                    for x in range (5):
                        def BookMarkReplace():
                            f.Bookmark = name, 
                            string = row_data[0])
                        {
                        Admission = row_data[2]
                        p.drawString(doc)
                        p.showPage()
                        p.save()
                        response ['Content-Disposition'] = 'attachment;filename=Admission.docx'
                        return response
                first = True
                excel_data.append(row_data)
               
    return render(request, 'letters/index.html', {"excel_data":excel_data})

我对这种方法不满意。有谁知道如何做到这一点或以任何其他方式做到这一点。

解决了!!! 我使用 python-doxc 来编辑我的 word 文档。我仍然无法弄清楚如何使用书签,但我替换了我想要编辑的部分,如下所示:

for paragraph in document.paragraphs:
  if 'Name of the student   : ' in paragraph.text:
     paragraph.text = 'Name of the student  : ' + Name

然后我使用 pypandoc 将它们转换为 pdf。

pypandoc.convert_file('template.docx', 'pdf', outputfile='S' + ' ' + Name + '.pdf')