Link with downloadable pdf file in Django - django

I have a pdf file in static folder {% static 'pdf/files.pdf' %}. I need to make this file downloadable by a normal link.. Anyone can give me the easiest way to do it? thanks very much

Create a view action and call it on link(your download link) click then return your file.
For ex:
def generate_PDF(request):
file = open('test.pdf', "w+b")
file.seek(0)
pdf = file.read()
file.close()
return HttpResponse(pdf, 'application/pdf')

Related

django: how to correctly specify output-download file-type (in this case mp3)?

I have a simple django platform where I can upload text files. Ultimately I want to return a downloadable mp3 audio file made from the text in the uploaded file. My problem currently is that I cannot seem to correctly specify the type of file that the website outputs for download.
I then tried to make the downloadable output of the website an mp3 file:
views.py (code adapted from https://github.com/sibtc/simple-file-upload)
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
print(str(request.FILES['myfile']))
x=str(myfile.read())
tts = gTTS(text=x, lang='en')
response=HttpResponse(tts.save("result.mp3"),content_type='mp3')
response['Content-Disposition'] = 'attachment;filename=result.mp3'
return response
return render(request, 'core/simple_upload.html')
Upon pressing the upload button, the text-to-speech conversion is successful but the content_type of the response is not definable as 'mp3'. The file that results from the download is result.mp3.txt and it contains 'None'.
Can you try to prepare your response using the sample code below?
I've managed to return CSV files correctly this way so it might help you too.
Here it is:
HttpResponse(content_type='text/plain') # Plain text file type
response['Content-Disposition'] = 'attachment; filename="attachment.txt"' # Plain text file extension
response.write("Hello, this is the file contents.")
return response
There are two problems I can see here. The first is that tts.save() returns None, and that is getting passed directly to the HttpResponse. Secondly, the content_type is set to mp3 and ought to be set to audio/mp3.
After calling tts.save(), open the mp3 and pass the file handle to the HttpResponse, and then also set the content_type correctly - for example:
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
...
tts.save("result.mp3")
response=HttpResponse(open("result.mp3", "rb"), content_type='audio/mp3')

How to use Xhtml2PDF convertor in linux system?

I am trying to convert html to pdf in django using xhtml2pdf, and successfully converted html to pdf in windows but in linux it is giving me file permission error though i give all type of permission to that file.Here i am posting taht function that convert html to pdf please suggest any solution thanks in advance.
def CreatePDF(request):
ser_type=request.POST.get("service_type")
if ser_type is not None:
data=WalletTransaction.objects.get(order_id=request.POST.get("order_id"),user=request.user)
c={'data':data,'ser_type':int(ser_type)}
template = get_template('TransHistoryPdf.html')
html = template.render(c)
file = open('test.pdf', "w+b")
pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file,
encoding='utf-8')
file.seek(0)
pdf = file.read()
file.close()
return HttpResponse(pdf, 'application/pdf')

Upload image to png

How to change extension of uploaded file to "png" in django?
in views:
def pictures_2png(file):
return Image.open(file).save('img.png')
Pictures.objects.create_pictures(car, pictures_2png(request.FILES["picture"]))
Without pictures_2png file saves on hard disk with it old extension (jpg, gif, etc). Something wrong in that function, but if I use it (function) in ipython with my local images - it works. Whats wrong? How to fix it?
Thanks.
via link
def pictures_2png(file):
buffer = StringIO()
Image.open(file).save(buffer, "PNG")
return InMemoryUploadedFile(buffer, None, 'test.png', 'image/png', buffer.len, None)

Exporting html to pdf using django

I am trying to export my html pages into pdf using Pisa library in django, and here is the code that I use to do that:
def fetch_resources(uri, rel):
path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, ""))
return path
def write_pdf(template_src, context_dict):
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")),dest = result, encoding='UTF-8', link_callback=fetch_resources)
if not pdf.err:
return http.HttpResponse(result.getvalue(), mimetype='application/pdf')
return http.HttpResponse('Sorry, no pdf! %s' % cgi.escape(html))
def article(request):
return write_pdf('Storehouse/ReceiptPrint-v2.html',{'pagesize':'A4'})
But I have two problems when I get the pdf output: first, it does not render my css files and all of my styles are missed in the pdf (my css files are very large, so please don't suggest to have the style in the html file) and second it does not understand the specified unicode (UTF-8), my html pages are in Farsi, but when it turns into pdf, it changes into some meaningless squares.
Any help would be appreciated a lot!
Pisa's converter uses the ReportLab Toolkit, which has a difficult time rendering Farsi and other Arabic characters straight out of the box. I found that using the DejaVuSansMono.ttf font allows you to render the characters properly.

Django + ExtJS FileUpload (direct from PC and from link)

Firstly - sorry for my English..
I've inherited a rather big project which uses ExtJS and is based on Django.. So I have an upload form and it works ok. The path to the file is given in a fileuploadfield (this is the xtype of ExtJS field) then it is taken by the Django and saved to the DB (it's being transformed to a needed view to be stored in the base, but that's not the problem..)
So I have smth like this:
class image(entity):
...
def create(self,request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
try:
parent_id = int(request.POST["parent_id"])
except:
return ErrorResponse()
if form.is_valid():
fl = request.FILES['file'];
file = fl.read()
Obj = self.data.obj
New = Obj()
setattr(New,'is_main',False)
and so on..
So I need to make a file upload from a direct link. Of course by another field. Having the file from a link is not a problem (urllib2 helps great), saving the file to the media folder isn't a problem too. But I can't insert it in the code above. As I understand - my problem is that the file object differs from the request.FILES thing.. But I don't know how to convert a normal file (in my case all the files are images) to the type of request.FILES so it would be readable for the next functions.. What I mean:
I catch the link to the file from another field(textfield):
url = request.POST['link'] #It get's the user posted link
name = urllib2.urlopen(url).read()
f = open('media/images/picture.gif', 'wb') #I overwrite it on a dummy, couse it must be than transfered to the db
f.write(name)
f.close #the file can be seen in the media path
Ok. The file is now in the /media/ folder, but if I simply try to replace the
file = fl.read() with file=f.read() it doesn't work. As I understand - the request.FILES and just a file are different.. Can anybody help me to convert my file to the needed type? Or tell me how can this idea be done.. The project is really big and if I try changing the submitting mechanism it may cause a lot of problems..
Again sorry for my English)
I really don't understand why it didn't work, but I found out that this works for me..
url = request.POST['file_link']
name = urllib2.urlopen(url).read()
file = name
..
the urllib2.urlopen("link to a file") returns a normal File and that is it..