웹 (http://www.20seven.org/journal/2008/11/pdf-generation-with-pisa-in-django.html)의 표준 예제를 사용하여 장고보기/템플릿을 PDF로 변환합니다.django - pisa : PDF 출력에 이미지 추가
템플릿에 이미지 (URL 또는 서버의 참조)를 포함 시켜서 PDF에 표시하는 쉬운 방법이 있습니까?
웹 (http://www.20seven.org/journal/2008/11/pdf-generation-with-pisa-in-django.html)의 표준 예제를 사용하여 장고보기/템플릿을 PDF로 변환합니다.django - pisa : PDF 출력에 이미지 추가
템플릿에 이미지 (URL 또는 서버의 참조)를 포함 시켜서 PDF에 표시하는 쉬운 방법이 있습니까?
이미지가 작동합니다. 다음과 같이 코드는 다음과 같습니다
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.template import RequestContext
from django.conf import settings
import ho.pisa as pisa
import cStringIO as StringIO
import cgi
import os
def dm_monthly(request, year, month):
html = render_to_string('reports/dmmonthly.html', { 'pagesize' : 'A4', }, context_instance=RequestContext(request))
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources)
if not pdf.err:
return HttpResponse(result.getvalue(), mimetype='application/pdf')
return HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html))
def fetch_resources(uri, rel):
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
return path
이
당신은 항상이 iText/ISharp과 이후에 이미지를 추가 할 수 http://groups.google.com/group/xhtml2pdf/browse_thread/thread/4cf4e5e0f4c99f55장고 사용자가 아닌 경우 'MEDIA_ROOT'는 'MEDIA_URL'은 해당 위치의 * http-friendly * 버전입니다 (예 : 로컬 HTML 파일의 경우 :'MEDIA_URL = 'file : ///'+ MEDIA_ROOT'). . 그렇지 않으면 이것은 일반적인 해결책입니다! – ecoe
에서 자유롭게 촬영했다.
Google에서 찾을 수있는 모든 솔루션을 사용해도 이미지가 표시되지 않았습니다.
from tempfile import mkstemp
# write html to a temporary file
# can used NamedTemporaryFile if using python 2.6+
fid, fname = mkstemp(dir='/tmp')
f = open(fname, 'w+b')
f.write(html)
f.close()
# now create pdf from the html
cmd = 'xhtml2pdf "%s"' % fname
os.system(cmd)
os.unlink(fname)
# get the content of the pdf
filename = fname+'.pdf'
pdf = open(filename, 'r')
content = pdf.read()
pdf.close()
os.unlink(pdf.name)
# return content
response = HttpResponse(content, mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=draft.pdf'
이미지를 URL 또는 전체 경로 이름, 예를 들어 하나를 가지고있는 곳은 일 : 피사의 명령 행 버전 확인 이미지를 표시하지만이 퍼지 나를 위해 일했다.
<img src="/home/django/project/site_media/css/output/images/logo.jpg" />
<img src="http://www.mysite.com/css/output/images/logo.jpg" />
def render_to_pdf(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
if page has an image.something:
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources)
else no image.something :
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),result)
if not pdf.err:
return HttpResponse(result.getvalue(), mimetype='examination_report/pdf')
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
def fetch_resources(uri, rel):
if os.sep == '\\': # deal with windows and wrong slashes
uri2 = os.sep.join(uri.split('/'))
else:# else, just add the untouched path.
uri2 = uri
path = '%s%s' % (settings.SITE_ROOT, uri2)
return path
위의 모든 코드 은 나를 위해 일하지 않았다. 결국 그것은 get_full_path 프로 시저를 넣어서 작동 시켰습니다. 따라서 최종 코드는 다음과 같습니다.
def render_to_pdf(template_src, context_dict):
now = datetime.now()
filename = now.strftime('%Y-%m-%d') + '.pdf'
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),result, path=path)
if not pdf.err:
response = HttpResponse(result.getvalue(), mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename="'+filename+'"'
return response
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
def get_full_path_x(request):
full_path = ('http', ('', 's')[request.is_secure()], '://',
request.META['HTTP_HOST'], request.path)
return ''.join(full_path)
이미지를 base64로도 변환 할 수 있습니다. 당신은 이미지 링크에 문제가 없을 것 BASE64로 변환
http://www.motobit.com/util/base64-decoder-encoder.asp
.
예, 이미지를 base64로 변환 할 수 있습니다. pdf에 삽입하는 방법에 대한 예를 추가하십시오. – ebob
링크가 작동하지 않습니다 - 이것입니다 : http://20seven.org/journal/2008/11/11/pdf-generation-with-pisa-in-django/ – Gady