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
Related
Im trying to generate pdf from given html file but get_template function is not working i guess.
from io import BytesIO
from django.template.loader import get_template
from xhtml2pdf import pisa
def render_to_pdf(context_dict={}):
try:
template = get_template('invoice.html')
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return result.getvalue()
return None
except Exception as e:
print('ERROR', e)
The Except block returns None.
Change line to:
pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result)
It was my logical error issue. I didn't added 'templates' folder to DIRS in settings.py file.
I tried to generate Pdf file from html using xhtml2pdf, after that I want to upload to S3. I had no idea how to do it, after trying a few ways but still stuck. Thank you so much for your help in advance.
def upload_pdf_S3(pdf):
client = boto3.client(
's3',
aws_access_key_id,
aws_secret_access_key
)
try:
client.upload_fileobj(pdf, 'test', 'test111.pdf')
return True
except ClientError as e:
print(e)
return False
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-1")), result)
upload_pdf_S3(pdf)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
I found a way to upload the file directly to the S3 bucket without having to write it locally. I use a different upload function but the idea is the same:
def upload_pdf_S3(pdf):
s3 = boto3.resource('s3')
try:
s3.Bucket(AWS_STORAGE_BUCKET_NAME).put_object(
Key=f"myfolder/myfile.pdf",
Body=pdf)
return True
except:
return False
The trick was that the Body parameter in put_object has to be in bytes format.
pisa_status = pisa.CreatePDF(html, dest=response, link_callback=link_callback)
upload_success = upload_pdf_S3(result.getvalue())
if not upload_success:
return HttpResponse('File upload to S3 has failed.')
It didn't work for me using pisa.pisaDocument(), but it did with pisa.createPDF() and result.getvalue(), as the latter is the file in bytes.
In case you don't have a link_callback function, I used the same the documentation has.
In case someone is in the same issues, you can tried this, it will create a local file, then you can upload to S3 for example.
file = open('test.pdf', "w+b")
pdf = pisa.pisaDocument(BytesIO(html.encode('utf-8')), dest=file)
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)
I have a Django app that reads a document template (DOCX) and modifies it. The program is working well, but it is returning to download a DOCX document (as expected). So, I want to edit the download file format to PDF. I thought of converting the DOCX file to PDF but I couldn't find a working way to do that.
My actual code looks like this:
f = io.BytesIO()
document.write(f)
length = f.tell()
f.seek(0)
response = HttpResponse(
f.getvalue(),
content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
)
response['Content-Disposition'] = 'attachment; filename=' + formular.name + '.docx'
response['Content-Length'] = length
return response
I want to find a working method of converting the DOCX file f to a PDF file before returning that as response.
you need pywin32 library for that purpose. which you can use like so
def convert_to_pdf(doc):
try:
word = client.DispatchEx("Word.Application")
new_name = doc.replace(".docx", r".pdf")
worddoc = word.Documents.Open(doc)
worddoc.SaveAs(new_name, FileFormat = 17)
worddoc.Close()
except Exception, e:
return e
finally:
word.Quit()
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.