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?
Related
I have some md files in an 'entries' folder in my django app folder and i wanna get them, covert them to HTML then render them.
This is my util.py
def get_entry(title):
"""
Retrieves an encyclopedia entry by its title. If no such
entry exists, the function returns None.
"""
try:
f = default_storage.open(f"entries/{title}.md")
return f.read().decode("utf-8")
except FileNotFoundError:
return None
def convert_md(filename):
"""
Converts given md file to html
"""
#file= f"{filename}.md"
file= default_storage.open(f"{filename}.md")
md= file.read()
html= md.markdown(md)
return html
This is my views.py
def wiki(request, topic):
if util.get_entry(topic) != None:
html= util.convert_md(topic)
return render(request, "encyclopedia/pages.html", {
"title": topic, "body": html
})
else:
return render(request, "encyclopedia/pages.html", {
"title": "ERROR", "body": "THIS PAGE IS NOT AVALIABLE."
})
I also have...
path("wiki/<str:topic>", views.wiki)
in my urls.py but I'm still getting a FileNotFoundError at /wiki/Python error
Note: I have pip installed markdown
pip install markdown on your console/terminal.
Then try the following:
import markdown
f = open("MDFile.md","r")
f = f.read()
html = markdown.markdown(f)
where MDFile.md are your markdown files. html will have the HTML version of your markdown file.
I was facing same FileNotFound exception, but i have found the answer finally.
Md files are located in entries folder, so you have to specify that in convert_md function in utils.py just like in get_entry function.
file = default_storage.open(f"entries/{filename}.md", "r")
I hope this will fix your issue as it did mine. :)
I want to make a webpage with Flask which enables me to search images according to some keywords and return two relevant images in the webpage.
And, assume the keyword is 'Steve jobs' and these images that are related to 'Steve jobs' will be scraped by Google Search and stored in a file called 'Steve jobs'.
But I still cannot display images from my file and return a blank page.
hello.py
#app.route("/about",methods=['GET', 'POST'])
def about():
...
DIR = os.path.join(os.getcwd())
DIR = os.path.join(DIR, query.split()[0])
...
def show_index():
for i,(img,Type) in enumerate(ActualImages[:2]):
try:
req = urllib.request.Request(img, headers=header)
raw_img = urllib.request.urlopen(req).read()
cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1
print(cntr)
if len(Type)==0:
f = open(os.path.join(DIR,image_type + "_"+ str(cntr)+".jpg"),'wb')
else:
f = open(os.path.join(DIR,image_type + "_"+ str(cntr)+"."+Type),'wb')
f.write(raw_img)
f.close()
except Exception as e:
print('>>> Could not load: '+img)
print(e)
return f
return render_template('about.html', f = f)
about.html
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<img src="{{f}}" alt="f">
</body>
</html>
A typical HTML image tag looks like so:
<img src="/path/image.gif" alt="My Image"/>
As you can see, the src attribute contains a URL telling the browser where to find the image. It will go off and download the image from there. It doesn't contain the image itself. Your code appears to be trying to load the image file's content into the HTML, and that won't work.
(Note - it is possible to directly embed images into HTML, but it's pretty unusual, so I won't talk about that.)
Given that, what you need to is to put the images somewhere, and serve and refer to them as per the answer to How do i link to images not in Static folder in flask.
I'm new to django and I have developed a django website which allows people to download epub file by typing the book's name. I have checked the django api about download and the code seems to work fine (no error reported), but there is no download window pops up by my browser. I'm testing on 127.0.0.1:8000 and here is part of my code
view.py
def download(request, file_path, book_name):
if os.path.exists(file_path):
response = HttpResponse(content_type="application/epub+zip")
response['X-Sendfile'] = file_path
response['Content-Disposition'] = 'attachment; filename=abc.epub'
print (response)
return response
raise False
According to my console it could find the file path, and by printing the message it shows
<HttpResponse status_code=200, "application/epub+zip">
[26/Mar/2018 18:31:03] "POST / HTTP/1.1" 200 509
Everything seems to work fine, just the download window does not pop up. Does anyone have any idea where is goes wrong? Thanks!
==========
Supplementary:
To give you a full sight of the view file, download is called by index and thats all:
def index(request):
template = loader.get_template('index.html')
book_name = ''
result = ''
if request.method == "POST": # check if user actually type a book name
book_name = request.POST.get("book_name")
cwd = os.getcwd()
if book_name != '': # search and create are functions from other file which would create an epub file and put it in current directory
result = search.search_ask(book_name)
create.create(book_name)
file_path = os.path.join(cwd, book_name) + '.epub'
download(request, file_path, book_name)
context = {'return_value': book_name,
'result_1': result,
'cwd': cwd}
return HttpResponse(template.render(context, request))
you don't return the response object returned by the download method. most be:
return donwload(request, file_path, book_name)
or
download_response = donwload(request, file_path, book_name)
if download_response:
return download_response
else:
# not found or other return.
in your code always return
return HttpResponse(template.render(context, request))
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')
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!