gpt4 book ai didi

python - 如何将.html文件输出到.doc文件django

转载 作者:行者123 更新时间:2023-12-05 07:58:41 25 4
gpt4 key购买 nike

我想将 .html 文件结果输出到 .doc 文件。我尝试使用 python-docx 但无法弄清楚。我是 django 的新手。

这是我的 api.py

from docx import Document
from xhtml2pdf import pisa
from cStringIO import StringIO
def export_pdf(request,id):
report = Report.objects.get(id=id)
document = Document()

options1 = ReportPropertyOption.objects.filter(report=report,is_active=True)
locations = []
out_string = ""
map = None



for option in options1:
option.property = get_property_name(option.property)
option.exterior_images = ReportExteriorImages.objects.filter(report = option)
option.interior_images = ReportInteriorImages.objects.filter(report = option)
option.floorplan_images = ReportFloorPlanImages.objects.filter(report = option)
option.fitouts = ReportFitOut.objects.filter(propertyoption = option)
if (option.gps_longitude):

locations.append("&markers=color:red|label:S|"+""+str(option.gps_longitude)+","+str(option.gps_latidtude)+"")
for loc in locations:
out_string+=loc

if locations:
map = "http://maps.google.com/maps/api/staticmap?center=Bangalore&zoom=12&size=512x512&maptype=roadmap"+out_string+"&sensor=true"
#map = "http://maps.google.com/maps/api/staticmap?zoom=12&size=400x400&maptype=roadmap&sensor=false&center=\\"
html = render_to_string('report/export.html', { 'pagesize' : 'A4', }, context_instance=RequestContext(request,{'options1':options1,'meta':report.meta,'map':map}))

#result = StringIO.StringIO()
result = StringIO()
result1=document.save(result)
length = result.tell()
result.seek(0)

#doc = document(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources )
return result

这是我的 views.py 文件

def export(request,id):
result = export_pdf(request,id)
report = Report.objects.get(id=id)
report.finalised = True
report.transaction.state= TransactionState.objects.get(state="Finalized")
report.transaction.save()
report.save()
email = report.transaction.manager.email
message=""
if result:
report_mail(request,result,email,message)
response = HttpResponse(result.getvalue(), content_type='vnd.openxmlformats-officedocument.wordprocessingml.document')
response['Content-Disposition'] = 'attachment; filename="my_file.docx"'
response['Content-Length'] = result.tell()
return response

return HttpResponse('Some error occured here! %s')

正在创建空白 docx。如何将 .html 文件添加到文档?所以请帮助我在 .docx 文件中获取结果输出。

最佳答案

您没有向您的 document 对象添加任何内容,因此您得到一个空的 docx 返回。

根据python-docx您需要像这样使用 document 对象的文档:

from docx import Document
[...]

document = Document()

document.add_heading('Document Title', 0)
[...]
document.save('demo.docx')

关于python - 如何将.html文件输出到.doc文件django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23871519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com