Rendering PDF template in django in arabic language - python

I have a problem with rendering pdf template in arabic words that i made table contains rows of classes (goods) in store here is the code of Generate pdf
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("iso-8859-6")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
in encode i put iso-8859-6 i searched for arabic encode and try this and it dos not work plaese any help thanks

Ok the problem is likely that your terminal is not able to render the result, so try in your terminal:
pip install win_unicode_console
Then, in python:
import win_unicode_console
win_unicode_console.enable()
Then, substitute the below line as before:
pdf = pisa.pisaDocument(BytesIO(html.encode("cp1252")), result)

Related

How to export Django Template to pdf

I'm trying to convert django template to pdf using pdfkit, wkhtmltopdf was installed but I'm getting error like
OSError: wkhtmltopdf exited with non-zero code 1.
error:QXcbConnection: Could not connect to display
How to solve this issue or suggest me any other better way to export django template to pdf?
from django.http import HttpResponse
from django.template.loader import get_template
import pdfkit
def generatepdf(request):
data={}
template = get_template('template_name.html')
html = template.render(data)
pdf = pdfkit.from_string(html, False)
filename = "sample_pdf.pdf"
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-Disposition'] = 'inline; filename="' + filename + '"'
return response
You can try https://pypi.org/project/django-wkhtmltopdf/. It works without issue and the pdf has no issue in terms of layout. It is very easy to implement.

issue about convert html to pdf use html2pdf in python2.7

when i render a html, it`s normal, however when i convert it to pdf use pisaļ¼š
def render_html2pdf_stream_pisa(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
try:
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),
dest=result,
encoding="UTF-8",
)
if not pdf.err:
return result.getvalue()
except Exception,e:
print Exception(e)
return None
as the result, the pdf is half-baked, not full pdf file like html`s style;
i don`t know where the issue

How to convert HTML file into PDF and save it in projects media folder using django

I have to create a dynamic pdf from html file in this pdf i am passing some keywords as well as barcode is also generated, basically this pdf is a ticket of an event.
So i have to save this pdf in project's media foleder so that user can download it from his/her account
I have successfully created pdf from html file, i have used code on stackoverflow and its working fine but the problem is that it's opening in tab, i have to save it in directory.
Here is my code
def testing_pdf(request):
image = treepoem.generate_barcode(
barcode_type='azteccode',
data='00100111001000000101001101111000010100111100101000000110',
options={'layers':5}
)
image.save(settings.MEDIA_ROOT+'/barcodes/barcode.png')
template = get_template('home/pdf-template/index.html')
context_dict = { 'name':'Testing','event': 'testing', 'barcode':image}
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("utf-8")), result)
if not pdf.err:
response = HttpResponse(result.getvalue(), content_type='application/pdf')
return response
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
What should i do in my this code so that it can be saved into my project's media directory.

Convert html to pdf using Python/Flask

I want to generate pdf file from html using Python + Flask. To do this, I use xhtml2pdf. Here is my code:
def main():
pdf = StringIO()
pdf = create_pdf(render_template('cvTemplate.html', user=user))
pdf_out = pdf.getvalue()
response = make_response(pdf_out)
return response
def create_pdf(pdf_data):
pdf = StringIO()
pisa.CreatePDF(StringIO(pdf_data.encode('utf-8')), pdf)
return pdf
In this code file is generating on the fly. BUT! xhtml2pdf doesn't support many styles in CSS, because of this big problem to mark page correctly. I found another instrument(wkhtmltopdf). But when I wrote something like:
pdf = StringIO()
data = render_template('cvTemplate1.html', user=user)
WKhtmlToPdf(data.encode('utf-8'), pdf)
return pdf
Was raised error:
AttributeError: 'cStringIO.StringO' object has no attribute 'rfind'
And my question is how to convert html to pdf using wkhtmltopdf (with generating file on the fly) in Flask?
Thanks in advance for your answers.
The page need render, You can use pdfkit:
https://pypi.python.org/pypi/pdfkit
https://github.com/JazzCore/python-pdfkit
Example in document.
import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf') # Is your requirement?
Have you tried with Flask-WeasyPrint, which uses WeasyPrint? There are good examples in their web sites so I don't replicate them here.
Not sure if this would assist anyone but my issue was capturing Bootstrap5 elements as a pdf. pdfkit did not do so and heres a work around on windows using html2image and PIL. This is limited and does not take a full page screenshot.
from html2image import Html2Image
from PIL import Image
try:
hti.screenshot(html_file=C:\yourfilepath\file.html, save_as="test.png")
finally:
image1 = Image.open(r'C:\yourfilepath\test.png')
im1 = image1.convert('RGB')
im1.save(r'C:\yourfilepath\newpdf.pdf')

Unable to load images/files pisa pdf Django python

I had a problem before where it wouldn't show Chinese characters even when I specified #font-face to use a UTF-8 font. It turns out I cannot display images as well... so I seems like I am unable to get any of the files embeded into my pdf.
This is the code I use:
def render_to_pdf(template_src, context_dict):
"""Function to render html template into a pdf file"""
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:
response = http.HttpResponse(result.getvalue(), mimetype='application/pdf')
return response
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
def fetch_resources(uri, rel):
import os.path
from django.conf import settings
path = os.path.join(
settings.STATIC_ROOT,
uri.replace(settings.STATIC_URL, ""))
return path
html
<img src="/static/images/bc_logo_bw_pdf.png" />
and
#font-face {
font-family: "Wingdings";
src: url("/static/fonts/wingdings.ttf");
}
I looked at the other quests on SO but it was no help. There are also no exceptions happening in the two functions. Also in fetch_resources function the path returned was the correct full path to the file i.e. /home/<user>/project/static/images/bc_logo_bw_pdf.png and /home/<user>/project/static/fonts/wingdings.ttf and I am at a loss as to what is wrong.
UPDATE
Everytime I create a pdf, I get this message on the console
No handlers could be found for logger "ho.pisa"
could this be related?
UPDATE #2
The font works now I made a dumb mistake... The font I was using did not have the Chinese unicode. But I still cannot embed any images onto the pdf, be it jpeg, gif or png.
I have finally solved the problem I was having... it turns out it doesn't work if I set the body's height with css... once I removed that line the image was loading perfectly...
For me (django 1.4, python 2.7 pisa==3.0.33), If I put the full path of image instead of relative, it works for me.
Try doing the same.
Everything looks better . Try once with JPG image file. In my case PNG file was also not working.
<img src="/static/images/<name>.jpg" />
without width and height attribute image will not work. add width and height attribute.
<img src="{% static 'images/logo.png' %}" alt="image" width="200" height="150" />
this fix works for me.
I have the same problem here. Don't give up with XHTML2PDF Pisa.
Pisa use PIL for generate PDF and use lib zip decoder to inserting images.
You should check if your PIL already installed properly with zip decoder, fonts and several components
I have solve this problem by installing PIL with zip decoder.
http://obroll.com/install-python-pil-python-image-library-on-ubuntu-11-10-oneiric/
If you need more detail information, you can read my article here :
http://obroll.com/how-to-load-images-files-style-css-in-pdf-using-pisa-xhtml2pdf-on-django/

Categories