Output image to pdf with xhtml2pdf - python

I followed this post : django - pisa : adding images to PDF output and using fetch_resources.
The PDF file can be generated normally except the image is missing.
This is my code:
def fetch_resources(uri, rel):
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
return path
def render_to_pdf(template_src, context_dict, filename):
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")),
dest=result,
link_callback=fetch_resources )
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))
This is my template:
<p><img src="{{ copyright.digital_signature.url }}"></p>
I'm sure that "copyright.digital_signature.url" is correct because it can show an image on browser properly.
And that means PIL had been installed?
Can anybody help me what the problem is? Thank you very much!

Related

Return PNG image from Django views is damaged

I'm working on a Django(2) project in which I need to return a PNG image as HttpResponse when I return this image in the form of a zip archive it returns the image correctly, but when I return the PNG image directly it damaged the image.
Here's my code:
How it's writing the image:
img_resized = cv2.resize(seg_image, dsize)
cv2.imwrite(os.path.join(settings.BASE_DIR, 'img/MaskedImage.png'), img_resized)
How it's returning the Image:
response = HttpResponse(os.path.join(settings.BASE_DIR, 'img/MaskedImage.png'), content_type='image/png')
response['Content-Disposition'] = 'attachment; filename=MaskedImage.png'
return response
It returns an Image with the name MaskedImage.pn but the image is damaged, not able to open.
What can be wrong here?
Thanks in advance!
You will need to read the image data. You're currently returning a response with just the image path.
with open(os.path.join(settings.BASE_DIR, 'img/MaskedImage.png'), 'rb') as fp:
response = HttpResponse(fp.read(), content_type='image/png')
response['Content-Disposition'] = 'attachment; filename=MaskedImage.png'
return response

Django downloading a file that had been uploaded before

I'm using Django 1.10 and I have a button on my home page that you can click to download a file (PDF or MP4). I have a ajax call going to my views.py
`def downloadfile(request):
if request.POST:
fileviewing = get_object_or_404(FileViewing, pk=request.POST.get("id"))
file_name = fileviewing.file.file.name
file_path = fileviewing.file.file.path
file_wrapper = FileWrapper(file(file_path,'rb'))
file_mimetype = mimetypes.guess_type(file_path)
response = HttpResponse(file_wrapper, content_type=file_mimetype)
response['X-Sendfile'] = file_path
response['Content-Length'] = os.stat(file_path).st_size
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
return response`
This is my function to download a file but nothing happens when it goes through the fuction. There are no errors and the function runs completely but nothing is being downloaded.

Not able to see converted Excel to HTML through Django

I have converted on Excel(with 2 tabs) to HTML. Now I want to display this generated HTML on a webpage with Django code. But I am not able to get the entire data in my webpage.
Following is my Django code.
#api_view(['GET'])
def download_y9cfile1(request, file_name):
filePath = CommonUtils.get_absolute_file_path('app','static','generated','HTML', file_name)
logger.debug("File name is %s" % filePath )
try:
relevantFile = open(filePath,'rb')
response = HttpResponse((relevantFile), content_type='text/html')
response['Content-Disposition'] = 'inline; filename="%s"' %file_name
except IOError:
logger.exception("File doesn't exist")
return HttpResponse("File doesn't exist", status=500)
return response
I think the issue is that Django is not able to read the supporting CSS file for HTML.
Try passing the file contents to HttpResponse instead of the file handle:
response = HttpResponse(relevantFile.read(), content_type='text/html')

Downloading file from FileField in Django with a HTTP link in a HTML file

I create a link that when a user press it, it will download a pdf file from the media folder in Django to the users machine.
I tried different methods but all were wrong for me. It tells me that the file can not be found, or the code is running but the file is corrupted.
My Html link:
<td> Download</td>
My url pattern links into a view:
url(r'^download/$', views.DownloadPdf),
My FileField is like this:
upload_pdf = models.FileField()
Following snippet code is the view that downloads a corrupted pdf:
def DownloadPdf(request):
filename = '/home/USER/PycharmProjects/MyProject/media/Invoice_Template.pdf'
response = HttpResponse(content_type='application/pdf')
fileformat = "pdf"
response['Content-Disposition'] = 'attachment;
filename=thisismypdf'.format(fileformat)
return response
So, what I have to do to make it working ?
with open(os.path.join(settings.MEDIA_ROOT, 'Invoice_Template.pdf'), 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/pdf")
response['Content-Disposition'] = 'attachment; filename=invoice.pdf'
return response
#Sergey Gornostaev 's code just work perfect, but i post below my code because it is a aproach in a differect way.
I correct a little bit my code:
def DownloadPdf(request):
path_to_file = '/home/USER/PycharmProjects/MyProject/media /Invoice_Template.pdf'
f = open(path_to_file, 'r')
myfile = File(f)
response = HttpResponse(myfile, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=filename'
return response
But only in pdf file ( works with txt files ) gives me that error:
'utf-8' codec can't decode byte 0xe2 in position 10

Django pdf question with pisa

I want to generate a html template to a pdf file using pisa. I believe I have all the packages I need but I seem to be having problems doing so. Here is my view below so
far what I have done.
EDIT: Here is my latest url, views & template.
url.py
(r'^index/render_pdf/(?P<id>\d+)/$', render_pdf),
views.py
def fetch_resources(uri, rel):
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
return path
def render_pdf (html, id):
invoice_items_list = Invoice_Items.objects.filter(pk=id)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), dest=result, link_callback=fetch_resources)
return result
In a template, I have this tag.
<a href="{% url c2duo.views.render_pdf invoices.pk %}">
I dont know how much this will help, but this is the function i use to render the pdf:
def fetch_resources(uri, rel):
"""
Callback to allow pisa/reportlab to retrieve Images,Stylesheets, etc.
`uri` is the href attribute from the html link element.
`rel` gives a relative path, but it's not used here.
"""
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
return path
def render_pdf (html):
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), dest=result, link_callback=fetch_resources)
return result
Just for fun, try this instead:
def render_to_pdf(template_src, context_dict):
html = "<html><head><title>Title</title></head><body><h1>Hello</h1></body></html>"
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html), result)
if not pdf.err:
return http.HttpResponse("" % (repr(result.getvalue())))
else:
raise Exception("The error was %s" % pdf.err)
If you still encounter an error, I'm guessing the error might be in pisa. Are you sure it's up to date?

Categories

Resources