How to use Xhtml2PDF convertor in linux system? - django

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')

Related

Django output csv file, filename is not setting as the value of Content-Disposition

I want to download a csv file with custom filename in a django project, but somehow the downloaded filename just display as "download.csv" instead of using the value of filename in Content-Disposition. I also tried to print csv_response['Content-Disposition'] out, but I'm getting a very strange string =?utf-8?b?YXR0YWNobWVudDsgZmlsZW5hbWU9Iuivvueoi+aKpeWQjeaDheWGtV8yMDE5MTEyODA3NDI0Ny5jc3Yi?=
the code snippet is :
#action(detail=False, methods=['GET'])
def download(self, request):
registrations = self.filter_queryset(self.get_queryset())
csv_response = HttpResponse(content_type='text/csv')
csv_response['Content-Disposition'] = 'attachment; filename="some_custom_name_{time}.csv"'.format(
time=time.strftime("%Y%m%d%H%M%S", time.localtime())
)
writer = csv.writer(csv_response)
writer.writerow([
some content,
])
for registration in registrations:
term_title = '{order} th'.format(order=registration.term.order)
course_title = registration.course.title
writer.writerow([
registration.user.email,
course_title,
term_title,
str(registration.confirmation_code),
str(registration.payment_due),
str(registration.payment_paid),
str(registration.source),
str(registration.created_at),
str(registration.updated_at),
str(registration.payment_source),
])
return csv_response
the django I am using is 2.2
any ideas why this is happening? I am a newb.
Thx in advance
The response header in chrome Dev tools:
I resolved the problem, by following the answer in the below post:
HttpResponse Django does not change file name
I guess that it is that because the string of Content-Disposition needs to be encoded, and if no, then somehow cannot operate on that, by using urlquote, it is solved.
Explanation about urlquote is here
UPDATE:
Also, a simpler way to resolve this without importing urlquote is to add encode(), like below:
csv_response['Content-Disposition'] = 'attachment; filename="some_custom_name_{time}.csv"'.format(
time=time.strftime("%Y%m%d%H%M%S", time.localtime())
).encode()
Change to this:
csv_response['Content-Disposition'] = 'attachment; filename="some_custom_name_{}.csv"'.format(
time.strftime("%Y%m%d%H%M%S", time.localtime())
)

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')

Append .png image to a pdf using reportlab in Django framework

I'm using Django and reportlab to generate a PDF report
I already can generate the pdf, but I Wanted to append a logo.png to it.
these were the lines I added in
views.py:
from reportlab.platypus import Image
logo = Image("/cdss/static/cdss/img/logo.png")
exam.append(logo)
But it isn't working, Am I exporting the Image() method wrong? Or is Path to the file wrong?
Hope you can help me, thanks ;)
This Worked For me....
def PrintImage(request,std_id):
response = HttpResponse(content_type='application/pdf')
doc = SimpleDocTemplate(response,topMargin=2)
doc.pagesize = landscape(A6)
elements = []
I = Image('http://demoschoolzen.educationzen.com/images/tia.png')
I.drawHeight = 0.7*inch
I.drawWidth = 0.7*inch
elements.append(I)
doc.build(elements)
return response
and Call it from your URLs

Link with downloadable pdf file in 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')

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.