WeasyPrint HTML to PDF not rendered Images in TEST VM Environment - Django - django

I am using Django + WeasyPrint for HTML to PDF generation.
In HTML template I am having around 2 SVG files. While running in Development (local) server, it rendered SVG Images when converting HTML to PDF. Whereas in TEST Server(Which runs by using NGINX and Docker Container), it fail to render SVG files. In WeasePrint, I have mentioned my TEST URL (http//test.sampleproject.com:8000) in the base_url. I don't know why it is working in my dev server and not working in TEST Server
My Code.
html_string = render_to_string('sample.html', {'data': data})
result = HTML(string=html_string, base_url='http//test.sampleproject.com:8000').write_pdf(presentational_hints=True)
response = HttpResponse(result, content_type='application/pdf')
response['Content-Disposition'] = 'inline; filename={}'.format('sample.pdf')
return response
In my Template file I have loaded around 10 images. Ex: 'sample.html' template file:
{% load staticfiles %}
<img src="{% static 'svg/Logo1.svg' %}" alt="" />
<img src="{% static 'svg/Logo2.svg' %}" alt="" />
Please help me to render the SVG files in the output PDF.

I've done some work in the past with Django + Weasyprint and the only time I had issue rendering images was due to the fact that Weasyprint accesses the image in a different way.
I found that I had to add a static endpoint for it to access the files from, as it is requesting the static images externally to Django. Here's how you can enable your static resources to be accessed externally;
https://docs.djangoproject.com/en/3.0/howto/static-files/#s-serving-static-files-during-development
Also as FlipperPA mentions, ensure you have all the OS level libraries installed on your server;
https://weasyprint.readthedocs.io/en/latest/install.html
Hope this helps :)

Related

image not showing in browser using easy thumbnail with Amazon S3 in Django Project

I am working on Django project and using easy thumbnails for cropping the images. Previously I used the in local enviornment and its working fine. but when I move media to Amazon S3 then the images not showing ( could not load the image) in the browser.
easy-thumbnail library link
image tag in the template:-
<img class="img-fluid" src="{% thumbnail destination.destination_image 1200x800 quality=95 crop %}" alt="">
image tag in browser:-
<img class="img-fluid" src="https://mybucket.s3.amazonaws.com/media/destination/myimage.jpg.1200x800_q95_crop.jpg" alt="">
But when I remove the (.1200x800_q95_crop.jpg) this part through web developer tools in img tag. then it's working. but the image size and crop options are not working.
I want to crop and resize images when it's showing in the browser.

Static images are not rendering in production on pdf using wkhtmltopd in django application

I am using pdfkit to convert html into pdf. Everything seems to be working perfectly in development, but after building a docker image and running it locally, the pdf is generated but images are not loaded.
Here is my how I am rendering image, which seems to be working fine locally:
<img src="{{ host_url }}/static/tcs.jpg" style="width:100px;display:block;" />
Here's my code in django view function:
template = get_template("tcs_invoice.html")
data = {
"host_url": settings.HOST
}
html = template.render(data) # Renders the template with the context data.
pdf = pdfkit.from_string(html, False)
return HttpResponse(pdf, content_type='application/pdf')
I have installed wkhtmltopdf on my docker container. When I hit the url in the browser the image is shown. why does it not render in production mode.
I had the same issue this answer did the trick: wkhtmltopdf, 0.12.6, Warning: Blocked access to file
It ended up being a change of behavior after wkhtmltopdf 0.12.6 where local file access is disabled by default, so you need to wether specify the files you want to allow using the --allow <file> option or set --enable-local-file-access to allow any files.
So after trying almost everything, even aws s3(privet bucket) none of them work !
The only way to pass the image with URL ; but we can't always do that in the case of confidential(in my case ) static images like signatures. solution?
If you are hosting it I mean env is Linux add this to settings.py:
STATIC_URL = '/static/'
STATIC_ROOT=(
os.path.join(BASE_DIR,'static')
)
STATICFILES_DIRS =[
os.path.join(BASE_DIR, 'staticfiles'),
]
1.Then your static files will be here ,0.0.0.0/static/img/....
2.You need to pass the image in html page through url only to be converted to PDF
3.From the backend get the domain and pass the url to page
from django.contrib.sites.shortcuts import get_current_site
current_domain = get_current_site(request).domain
template=get_template('template location like template/some.html')
template_render=template.render({'value':yourquery,"current_domain":current_domain})
options={
'page-size': 'Letter',
"enable-local-file-access": None,
"disable-smart-shrinking": None,
"zoom": "0.7",}
pdf=pdfkit.from_string(template_render,False,options)
response = HttpResponse(pdf,content_type='application/pdf')
response['Content-Disposition'] = 'attachment;
filename="ourcodeworld.pdf" '
return HttpResponse(pdf, content_type='application/pdf')
4.In this way you will be able to pass the domain cause it might change.
5.
change the static :
<img src="{% static 'img/someimage.png' %}>
to
<img src="http://{{current_domain}}/static/img/someimage.png">
It works everywhere! even in EC2.
Upvotes are appreciated, Thank you!

Serving static images on django application?

I am have been having troubles figuring out how to serve static images with my django application. However, I have figured out a sort of "hack" to get it working but it doesn't allow for much flexibility.
In the html files I have tried the following...
<img src="{{ STATIC_URL }}textchange/nextarrow.png" class="foobar" id="foobar">
Above: The pages will load when I use this but the images will not work.
<img src="{% static "textchange/nextarrow.png" %}" class="foobar" id="foobar">
Above: The pages will not load, I get a server error
<img src="thefullurltoS3bucket/nextarrow.png" class="foobar" id="foobar">
Above: The images will load fine
I have been trying all these different formats when going to production with Heroku and S3. The question I have is is the way I'm serving my static images correct? I use the last example in which I make the src the full url to the bucket at s3. Is that fine?
It should be noted that when I use the static tag serving css files works fine. Images is the only problem.
Your first and second solutions ( that you got server error and not loading ) is the correct way of using static files which is:
<img src="{% static "textchange/nextarrow.png" %}" class="foobar" id="foobar">
review your settings.py file and set STATIC_URL and STATIC_DIRS and also STATIC_ROOT, if you got server error maybe you set the STATIC_URL or STATIC_DIRS wrong. you can find plenty of posts about these settings.
Also check your image url in browser ( sth like 127.0.0.1:8000/static/files/etc.jpg )see if you can access the image.
Serving static files in Django can be a pain.
First, make sure you use the static template tag correctly in your template:
{% load static from staticfiles %}
<img src="{% static 'path/to/image.jpg' %}">
In your settings, have your STATIC_URL point to something like '/static/', your STATIC_ROOT point to the directory where you'll actually serve your files post-collectstatic, and your STATIC_DIRS to where you'll place your static files within your project (i.e. 'static' directory).
If you're serving from S3, you'll probably follow a tutorial like this one.

Custom image in Django template via static

I am programming a website powered by Django 1.6.3. Under news you always see a big story and on the side recent articles. Therefore, I used Bootstrap 3 and wrote a static html page serving my requirements.
Now I would like to program the logic behind this. I save all my files under static that consists of the folders css, fonts (from Bootstrap), img and js. The image folder has some subfolder e.g. news. To create a new entry on the news page I would like to open the admin page, add a news_entry and select one image that should be under the titel. How is it possible to include the image in the page? My approach was:
<img src="{% static {{ news.image_name }} %}" class="img-title">
Unfortunately I get an parsing error. Image_name is a property of my news model.
You need to access the url attribute of your image_name.
Try:
<img src="{{ news.image_name.url }}" class="img-title">
Similar question here.

Using Django urls in javascript files

I am trying to use url-names in my javascript/jquery files for AJAX requests and I have found several solutions that can solve this problem. The one that I am currently using is the following.
I define a url to serve javascript files:
urls.py
url(r'^js/([\w\.\-]+)/([\w\.\-]+)/$', 'views.get_javascript_file', name='get_javascript_file')
url(r'^getmoredicus/$', 'load_discussions', name="load-discus"),
Then I define the view that renders the javascript files.
views.py:
def get_javascript_file(request, app_name, js_file):
'''
Used to request and serve rendered javascript/jquery files.
'''
return render_to_response("%s/%s.js" % (app_name, js_file),
context_instance=RequestContext(request))
Now in the html files, we can use the get_javascript_file url to get the rendered javascript files.
html files:
<script type="text/javascript" src="{% url get_javascript_file 'myapp' 'jsfile' %}"></script>
Now in any javascript file, I can access the url-names through {% url url-name %}.
Questions:
1) Is there a better/faster way to use url-names in javascript files? I know that there are some apps already created to accomplish this but I want to get everyone's(django experts) opinion on the best way to accomplish this.
2) Can we cache the rendered javascript files after they have been rendered the first time so that in each subsequent request, we don't have to render them again? If yes, then how can we go about doing that.
3) In this method, we are rendering the script files from their apps folders. Is there a way to access the static files located in STATIC_ROOT from the get_javascript_file view? I am just thinking about how this would work in a production environment. Is it a good practice to access static files from their apps folders rather than putting them in STATIC_URL and accessing them from there?
NOTE
I know that there are already some questions on SO that answer some parts of this question, but I just wanted to get to the bottom of this once and for all for future django learners. What is the best way to use url-names in javascript or any script for that matter?
I'm not a fan of running external js through the view rendering. Especially if you're using something like django-compressor to compress and cache your js files.
I prefer to just include the variables in a script tag prior to including the external files.
<script>
my_var = "{{ MY_PROPERTY }}"
</script>
<script type="text/javascript" src="{{ STATIC_URL }}js/external_script.js"></script>
That solution is also not always ideal, but I'm open to other solutions.