我正在使用html2pdf生成pdf报告,如果有大量数据/记录则不会生成pdf。我有5000条记录和它将涵盖400多个pdf页面。如果数据/记录仅为1000(涵盖最多80-85个pdf页面),则会成功生成。但就上述而言,它完全失败了。有没有解决方案,或者我是否需要使用任何其他插件。
我使用 write_pdf 功能
html2pdf.py
from django import http
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.loader import get_template
from django.template import Context
import ho.pisa as pisa
import cStringIO as StringIO
import cgi, os
from django.conf import settings
from datetime import datetime
def fetch_resources(uri, rel):
path = os.path.join(settings.MEDIA_ROOT, uri.replace("//", ""))
return path
def write_pdf(template_src, context_dict, filename):
os.chdir(settings.MEDIA_ROOT+'/pathtofoldertosave/')
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = open(filename, 'wb')
pdf = pisa.pisaDocument(StringIO.StringIO(
html.encode("UTF-8")), result,link_callback=fetch_resources)
result.close()
return str(settings.MEDIA_URL)+'/pathtofoldertosave/'+str(filename)
def render_to_pdf(template_src, context_dict,file_name):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result, link_callback=fetch_resources)
if not pdf.err:
response = HttpResponse( result.getvalue() ) response['Content-Type'] = 'application/pdf'
response['Content-Disposition'] = 'attachment; filename='+file_name;
return response
return http.HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html))
生成报告的功能是: report.py
def reportFun(request):
mem = Member.objects.all()
FileName = "Report_"+datetime.now().strftime('%d-%m-%Y-%H:%M')+".pdf"
fname = "http://"+str(request.META['HTTP_HOST'])+"/"+write_pdf('report_pdf.html',{'pagesize':'A4','data':mem}, FileName)
return render_to_response("report.html",{'result':mem,'fname':fname}, context_instance=RequestContext(request))