Git Product home page Git Product logo

django-weasyprint's Introduction

Django-WeasyPrint

Build Coverage PyPI Download PyPI Python Versions PyPI License

A Django class-based view generating PDF responses using WeasyPrint.

Installation

Install and update using pip:

pip install -U django-weasyprint

WeasyPrint is automatically installed as a dependency of this package. If you run into any problems be sure to check their install instructions for help!

Tip

In version 53 WeasyPrint switched to pydyf as PDF generator instead of Cairo. With that change PNG output was dropped and you might encounter other changes in the generated PDF.

You can continue using WeasyPrint/Cairo by installing django-weasyprint 1.x!

Usage

Use WeasyTemplateView as class based view base class or the mixin WeasyTemplateResponseMixin on a TemplateView (or subclass thereof).

Example

# views.py
import functools

from django.conf import settings
from django.views.generic import DetailView

from django_weasyprint import WeasyTemplateResponseMixin
from django_weasyprint.views import WeasyTemplateResponse
from django_weasyprint.utils import django_url_fetcher


class MyDetailView(DetailView):
    # vanilla Django DetailView
    template_name = 'mymodel.html'

def custom_url_fetcher(url, *args, **kwargs):
    # rewrite requests for CDN URLs to file path in STATIC_ROOT to use local file
    cloud_storage_url = 'https://s3.amazonaws.com/django-weasyprint/static/'
    if url.startswith(cloud_storage_url):
        url = 'file://' + url.replace(cloud_storage_url, settings.STATIC_URL)
    return django_url_fetcher(url, *args, **kwargs)

class CustomWeasyTemplateResponse(WeasyTemplateResponse):
    # customized response class to pass a kwarg to URL fetcher
    def get_url_fetcher(self):
        # disable host and certificate check
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        return functools.partial(custom_url_fetcher, ssl_context=context)

class PrintView(WeasyTemplateResponseMixin, MyDetailView):
    # output of MyDetailView rendered as PDF with hardcoded CSS
    pdf_stylesheets = [
        settings.STATIC_ROOT + 'css/app.css',
    ]
    # show pdf in-line (default: True, show download dialog)
    pdf_attachment = False
    # custom response class to configure url-fetcher
    response_class = CustomWeasyTemplateResponse

class DownloadView(WeasyTemplateResponseMixin, MyDetailView):
    # suggested filename (is required for attachment/download!)
    pdf_filename = 'foo.pdf'
    # set PDF variant to 'pdf/ua-1' (see weasyprint.DEFAULT_OPTIONS)
    pdf_options = {'pdf_variant': 'pdf/ua-1'}

class DynamicNameView(WeasyTemplateResponseMixin, MyDetailView):
    # dynamically generate filename
    def get_pdf_filename(self):
        return 'foo-{at}.pdf'.format(
            at=timezone.now().strftime('%Y%m%d-%H%M'),
        )
# tasks.py
from celery import shared_task
from django.template.loader import render_to_string

from django_weasyprint.utils import django_url_fetcher

@shared_task
def generate_pdf(filename='mymodel.pdf'):
    weasy_html = weasyprint.HTML(
        string=render_to_string('mymodel.html'),
        url_fetcher=django_url_fetcher,
        base_url='file://',
    )
    weasy_html.write_pdf(filename)
<!-- mymodel.html -->
<!doctype html>
<html>
    <head>
        <!-- Use "static" template tag and configure STATIC_URL as usual. -->
        <link rel="stylesheet" href="{% static 'css/app.css' %}" />
    </head>
    <body>
        Hello PDF-world!
    </body>
</html>

Settings

By default WeasyTemplateResponse determines the base_url for weasyprint.HTML and weasyprint.CSS automatically using Django's request.build_absolute_uri().

To disable that set WEASYPRINT_BASEURL to a fixed value, e.g.:

# Disable prefixing relative URLs with request.build_absolute_uri().
# Instead, handle them as absolute file paths.
WEASYPRINT_BASEURL = '/'

Changelog

See CHANGELOG.md

Links

django-weasyprint's People

Contributors

arthru avatar dekkers avatar dependabot[bot] avatar fdemmer avatar foarsitter avatar graingert avatar hellysmile avatar jayennis22 avatar lize avatar niccolomineo avatar sblondon avatar schnouki avatar scottbarkman avatar tdesveaux avatar timb07 avatar ziima avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-weasyprint's Issues

Accessing PDF FIle

Hello,
I currently have a PDF generator where a user can generate a unique PDF based on certain data they input. I am trying to save the PDF to the server file system but I'm not too sure on how to access the file and where would be the best place access it method wise. I was thinking about not using an attachment but each PDF is unique and the values not stored anywhere. Here is my pseudo code:

class MyDownloadAttachmentView(WeasyTemplateResponseMixin, DetailView):
    pdf_attachment = True

    # what I am trying to do
    def render_to_reponse(self):
        pdf = self.file  # basically the unique PDF that is being rendered from the view
        artifact.objects.create(    
           name='pdf_artifact',
           file=pdf
        )  # create an artifact with the PDF

Basically I am looking for a way to access the PDF file object and save it to my local file system. Thanks in advance

how to configure nginx to deal with django_weasyprint requests

thats the error i get
Failed to load image at "http://localhost/static/images/Logo.svg" (URLError: <urlopen error [Errno 99] Cannot assign requested address>)

cause nginx doesn't GET the images instead it redirects to the url

nginx configurations:

upstream hello_django {
    server web:8000;
}

server {
    listen   80;

    location /static/ {
        autoindex on;
        alias   /code/static/;
    }

    location /media/ {
        autoindex on;
        alias   /code/media/;
    }

    location / {
        proxy_pass http://hello_django;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }
    #For favicon
    location  /favicon.ico {
        alias /code/assets/favicon.ico;
    }

    # Error pages
    error_page 404 /404.html;
    location = /404.html {
        root /code/templates/;
    }
}


cannot display script output from javascript

I'm doing a "Total" sum on multiple tables using javascript. But when I export, the script cannot be read in the PDF file. Whereas previously the script was read on a Web page.

Is there a solution?

HTML.render() got multiple values for argument 'font_config' with Weasyprint 59

Hi,
it seems weasyprint changed its API with v59 and the signature of HTML.render() hast changed.
See: https://github.com/Kozea/WeasyPrint/releases/tag/v59.0b1

As a result, django-weasyprint throws an exception with Weasyprint v59:

  File ".../venv/lib/python3.11/site-packages/django_weasyprint/views.py", line 91, in rendered_content
    document = self.get_document()
               ^^^^^^^^^^^^^^^^^^^
  File ".../venv/lib/python3.11/site-packages/django_weasyprint/views.py", line 81, in get_document
    return html.render(
           ^^^^^^^^^^^^
TypeError: HTML.render() got multiple values for argument 'font_config'

Maybe you could adapt to the changed API. Thank you!

Best,
Floek

OSError: no library called "cairo" was found

no library called "libcairo-2" was found
cannot load library 'libcairo.so': Error loading shared library libcairo.so: No such file or directory
cannot load library 'libcairo.2.dylib': Error loading shared library libcairo.2.dylib: No such file or directory
cannot load library 'libcairo-2.dll': Error loading shared library libcairo-2.dll: No such file or directory
I have only installed django-weasyprint and it is showing this error when i try to use it.

How to return a generated pdf file response using APIView

Hello folks!
I have this scenario where I send request to generate pdf report from React Application where everything seems well on creating a pdf file from html template on Django Server, but when returning a response to frontend a generated pdf seems to be BLANK means it doesn't contains anything, just white pdf file.

Below are my codes so far.

On Django Server

from weasyprint import HTML
from weasyprint.fonts import FontConfiguration
from django.template.loader import render_to_string
from .models import Donation

from datetime import datetime

class ExportDonationReport(APIView):
    def get(request, *args, **kwargs):
        donations = Donation.objects.all()
        response = HttpResponse(content_type=application/pdf”)
        response[‘Content-Disposition’] =inline; filename={date}-donation-receipt.pdf”.format(
            date=datetime.today()        
        )
        html = render_to_string(“donations/donations_reports_pdf.html”, {
            ‘donations’: donations
        })
        font_config = FontConfiguration()
        HTML(string=html).write_pdf(response, font_config=font_config)
        return response

On React Application

import {saveAs} from 'file-saver';
import axios from "axios";

axios
        .get("http://locahost:8000/reports/donations/export/", {}, header)
        .then((response) => {
            const blob = new Blob([response.data], {type: 'application/pdf'})
            saveAs(blob, "donations-report.pdf")
        })
        .catch((error) => {
            console.log(error.response);
        });

I am getting a pdf file but it doesn't contain anything, just a blank white pdf file as I stated above.

I tried using xhtml2pdf and successfully get a file with data but I would like to use WeasyPrint because it is very dyanamic and easy to style than xhtml2pdf

So anyone with idea on how to solve my issue please help me.

Thanks in advance.

Support for CDN statics

  1. Thanks for this awesome software
  2. I am only using the custom URL fetcher outside any django views to imperatively render a pdf in a background process, that will later be emailed etc. So maybe I am missing something, please tell me so.

As explained in https://docs.djangoproject.com/en/3.0/howto/static-files/deployment/#serving-static-files-from-a-cloud-service-or-cdn statics might be served from an external domain. In this situation, URLs produced in templates due to blocks like

<img src="{% static 'logo.png' %}" />

will already start with a schema and will not be prefixed by file:// even if that is the explicit base_url, thus skipping the whole advantatge of your URL fetcher. URLs can neither be hardcoded like file:///static/example.png because their path won't fulfill the condition of matching settings.STATIC_URL.

Right now I am working around this with a custom URL fetcher like

def custom_url_fetcher(url, *args, **kwargs):
    if url.startswith(settings.STATIC_URL):
        file_path = url.replace(settings.STATIC_URL, '', 1)
        file_obj = open(find(file_path), 'rb')
        data = {
            'file_obj': file_obj
        }
        return data

    return django_weasyprint.utils.django_url_fetcher(
        url, *args, **kwargs)

but was wondering if you feel like this could belong to this package. I think it is safe to assume that any reference to a file starting with the full STATIC_URL is something that has actually been collected by django and thus can still be found by the configured STATICFILES_FINDERS with no network calls.

This would also help avoiding some issues with static file versioning (static files bundled with the running django installation not yet collected and published to an accessible CDN) and picky network configurations (e.g. statics being collected in a CI pipeline but webservers being constrained to whitelisted services that exclude the very CDN 🤷‍♀️ ).

Install fails due to "cannot load library 'pango-1.0'"

I'm using a Mac running v10.15.5 (Catalina). On attempting to install this via $pipenv install django-weasyprint I get the following:

Installing django-weasyprint…
Adding django-weasyprint to Pipfile's [packages]…
✔ Installation Succeeded 
Pipfile.lock (4b2068) out of date, updating to (e65fa0)…
Locking [dev-packages] dependencies…
Building requirements...
Resolving dependencies...
✘ Locking Failed! 
Traceback (most recent call last):
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/resolver.py", line 807, in <module>
    main()
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/resolver.py", line 802, in main
    _main(parsed.pre, parsed.clear, parsed.verbose, parsed.system, parsed.write,
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/resolver.py", line 785, in _main
    resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages)
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/resolver.py", line 758, in resolve_packages
    results = clean_results(results, resolver, project)
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/resolver.py", line 640, in clean_results
    entry_dict = translate_markers(entry.get_cleaned_dict(keep_outdated=False))
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/resolver.py", line 239, in get_cleaned_dict
    self.validate_constraints()
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/resolver.py", line 565, in validate_constraints
    constraints = self.get_constraints()
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/resolver.py", line 493, in get_constraints
    pipfile_constraint = self.get_pipfile_constraint()
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/resolver.py", line 507, in get_pipfile_constraint
    return self.constraint_from_parent_conflicts()
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/resolver.py", line 527, in constraint_from_parent_conflicts
    if not p.requirements:
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/resolver.py", line 625, in __getattribute__
    return super(Entry, self).__getattribute__(key)
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/resolver.py", line 370, in requirements
    self.project.environment.get_package_requirements(self.name)
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/environment.py", line 698, in get_package_requirements
    return [self._get_requirements_for_package(p, key_tree) for p in nodes]
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/environment.py", line 698, in <listcomp>
    return [self._get_requirements_for_package(p, key_tree) for p in nodes]
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/environment.py", line 675, in _get_requirements_for_package
    d['dependencies'] = [
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/environment.py", line 676, in <listcomp>
    cls._get_requirements_for_package(c, key_tree, parent=node,
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/environment.py", line 667, in _get_requirements_for_package
    d = node.as_dict()
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/vendor/pipdeptree.py", line 284, in as_dict
    'installed_version': self.installed_version,
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/vendor/pipdeptree.py", line 251, in installed_version
    return guess_version(self.key, self.UNKNOWN_VERSION)
  File "/usr/local/Cellar/pipenv/2020.6.2/libexec/lib/python3.8/site-packages/pipenv/vendor/pipdeptree.py", line 123, in guess_version
    m = import_module(pkg_key)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "$MYPROJECT/.venv/lib/python3.8/site-packages/weasyprint/__init__.py", line 440, in <module>
    from .css import preprocess_stylesheet  # noqa isort:skip
  File "$MYPROJECT/.venv/lib/python3.8/site-packages/weasyprint/css/__init__.py", line 30, in <module>
    from . import computed_values, media_queries
  File "$MYPROJECT/.venv/lib/python3.8/site-packages/weasyprint/css/computed_values.py", line 18, in <module>
    from .. import text
  File "$MYPROJECT/.venv/lib/python3.8/site-packages/weasyprint/text.py", line 259, in <module>
    pango = dlopen(ffi, 'pango-1.0', 'libpango-1.0-0', 'libpango-1.0.so',
  File "$MYPROJECT/.venv/lib/python3.8/site-packages/weasyprint/text.py", line 254, in dlopen
    return ffi.dlopen(names[0])  # pragma: no cover
  File "$MYPROJECT/.venv/lib/python3.8/site-packages/cffi/api.py", line 150, in dlopen
    lib, function_cache = _make_ffi_library(self, name, flags)
  File "$MYPROJECT/.venv/lib/python3.8/site-packages/cffi/api.py", line 832, in _make_ffi_library
    backendlib = _load_backend_lib(backend, libname, flags)
  File "$MYPROJECT/.venv/lib/python3.8/site-packages/cffi/api.py", line 827, in _load_backend_lib
    raise OSError(msg)
OSError: cannot load library 'pango-1.0': dlopen(pango-1.0, 2): image not found.  Additionally, ctypes.util.find_library() did not manage to locate a library called 'pango-1.0'

speed problems

Hello, how are you, sorry for the inconvenience.

I am generating a PDF of approximately 26 pages, it is a render of a table with many rows, for the aesthetics of the table and the report I use Boottrap 3, it does it very well but it is very very slow, is there something I am doing wrong or is it normal , I tried several ways to use weasyprint and none of them achieved more speed. It takes a few more or 46 seconds less, and if there are more pages it will take up to several minutes.

Thank you

Status of this project?

With the xhtml2pdf project being recently abandoned, they suggest using Weasyprint instead, so I started digging for a wrapper for Django and found this project.

Seeing that it looks quite inactive as well, I looked at the forks, and found @fdemmer fork which has continued the project, and looks much more active. Then I searched on on PyPi, but the package owner seems to be someone else, is that you @graingert maybe?

Which one is still maintained? Am I right in assuming that the Pypi package is not the same code as @fdemmer's fork? If so, is there any plan in consolidating ownership of the repository and Pypi package?

If none of you is maintaining them anymore, no worries, I'll do my own, just wanted to check before jumping to something abandoned.

Collaborating with django-renderpdf

Hi! I maintain django-renderpdf, which I wrote back in 2017 to, well, render PDFs. It also uses weasyprint under the hood.

I've come across django-weasyprint a few times during the years. It seems that around 80% of what both projects do is the same. There's some duplicate effort going on between both projects. I'd like to contribute to django-weasyprint by merging any functionality that's missing, and then have a migration plan to transition projects from django-renderpdf into django-weasyprint.

I wanted to hear your thoughts on this and see if this sounds good to you too before actually doing anything.

From what I can tell, these are the biggest differences with django-renderpdf:

Manifest-suffixed image not showing up

Hi, apparently a static image cannot be displayed with the standard static template tag when using a manifest-appending storage.

The issue seems to be in utils.django_url_fetcher:34, where find() is invoked: file finders are not able to find the manifest file, because STATIC_ROOT does not and cannot appear in STATICFILES_FINDERS at the same time.

A temporary workaround is to hardcode the file path with the prepended static root inside the template file.

I would like to propose a couple of alternative solutions:

#49 does not remove the current finding behaviour, but simply checks whether the collected file exists.

#50 Only performs said check ('cause is it really needed to trigger the finders in the first place?)

Multi-process support?

Hey folks,

I'm currently struggling with Kozea/WeasyPrint#167 which is a bug in upstream weasyprint -- it segfaults when run in a forked child process. This precludes using forked WSGI servrs like gunicorn or uwsgi.

Have y'all found a workaround for that to make this work under Django regardless of the WSGI server process model, by chance?

Thanks,
Tom

Recommend defaulting content_type to PDF

This issue is somewhat selfish in nature. I prefer to use Function-Based Views, and would like to use WeasyTemplateResponse in these views with minimal boilerplate. Specifying content_type in the returned response should no longer be necessary.

As noted in the README, support for PNG output in Weasyprint has been removed, so we can default to using 'application/pdf' as the content_type for WeasyTemplateResponse.

Additionally, this can be done in an entirely backwards-compatible manner by setting the content_type in the init method of WeasyTemplateResponse, defaulting to a pdf if not otherwise set: self.content_type = kwargs.get("content_type", "application/pdf")

Then all we need for a view is:

from django_weasyprint.views import WeasyTemplateResponse

def pdf_view(request, id):
    template = "detail_view.html"
    pdf_filename = "my_report.pdf"

    context = {}
    context["data"] = MyModel.objects.get(id=id)

    return WeasyTemplateResponse(pdf_filename, request=request, template=template, context=context)

Would a PR with this small change and an example for the docs be helpful?

Imagefield not showing due to LoginRequiredMiddleware

Hello. New to django-weasyprint. My problem resided with weasyprint initially because it couldn't render a model.imagefield after I implemented a middleware that required login to view all the content.

After that django-weasyprint came to my attention. I hastily implemented a solution but the image still doesn't show. Any help?

pango_context_set_round_glyph_positions' not found in library 'libpango-1.0.so.0'

Starting from yesterday (or more days ago. not sure) django-weasyprint==1.0.1 is broken when trying to generate pdf.

Dockerfile. This shows how prerequirements are installed:

# Development Dockerfile for Django app
FROM python:3.7-slim

ENV PYTHONUNBUFFERED 0

# Install system requirements
RUN apt-get update && \
    apt-get upgrade -y && \
    apt-get install -y --no-install-recommends gcc gettext libpq-dev git python3-cffi \
     libcairo2 libpango-1.0-0 libpangocairo-1.0-0 \
    libgdk-pixbuf2.0-0 libffi-dev shared-mime-info && \
    rm -rf /var/lib/apt/lists/*

Half of the traceback.

 File "/opt/project/myproject/oscar_forks/order/views.py", line 59, in get_pdf
   pdf = HTML(string=pdf_data['html']).write_pdf()
 File "/usr/local/lib/python3.7/site-packages/weasyprint/__init__.py", line 183, in write_pdf
   counter_style=counter_style, image_cache=image_cache)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/__init__.py", line 136, in render
   optimize_size, font_config, counter_style, image_cache)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/document.py", line 887, in _render
   [Page(page_box) for page_box in page_boxes],
 File "/usr/local/lib/python3.7/site-packages/weasyprint/document.py", line 887, in <listcomp>
   [Page(page_box) for page_box in page_boxes],
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/__init__.py", line 124, in layout_document
   pages = list(make_all_pages(context, root_box, html, pages))
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/pages.py", line 802, in make_all_pages
   page, resume_at = remake_page(i, context, root_box, html)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/pages.py", line 741, in remake_page
   page_number, page_state)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/pages.py", line 552, in make_page
   positioned_boxes, adjoining_margins, discard=False)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/blocks.py", line 60, in block_level_layout
   page_is_empty, absolute_boxes, fixed_boxes, adjoining_margins, discard)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/blocks.py", line 75, in block_level_layout_switch
   discard)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/blocks.py", line 128, in block_box_layout
   absolute_boxes, fixed_boxes, adjoining_margins, discard)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/blocks.py", line 520, in block_container_layout
   absolute_boxes, fixed_boxes, adjoining_margins, discard)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/blocks.py", line 60, in block_level_layout
   page_is_empty, absolute_boxes, fixed_boxes, adjoining_margins, discard)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/blocks.py", line 75, in block_level_layout_switch
   discard)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/blocks.py", line 128, in block_box_layout
   absolute_boxes, fixed_boxes, adjoining_margins, discard)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/blocks.py", line 520, in block_container_layout
   absolute_boxes, fixed_boxes, adjoining_margins, discard)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/blocks.py", line 60, in block_level_layout
   page_is_empty, absolute_boxes, fixed_boxes, adjoining_margins, discard)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/blocks.py", line 75, in block_level_layout_switch
   discard)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/blocks.py", line 122, in block_box_layout
   context, box, (containing_block.width, containing_block.height))
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/tables.py", line 738, in table_wrapper_width
   auto_table_layout(context, wrapper, containing_block)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/tables.py", line 631, in auto_table_layout
   table_and_columns_preferred_widths(context, box, outer=False)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/preferred.py", line 467, in table_and_columns_preferred_widths
   min_content_width(context, cell))
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/preferred.py", line 45, in min_content_width
   return table_cell_min_content_width(context, box, outer)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/preferred.py", line 234, in table_cell_min_content_width
   for child in box.children
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/preferred.py", line 235, in <listcomp>
   if not child.is_absolutely_positioned()]
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/preferred.py", line 48, in min_content_width
   return block_min_content_width(context, box, outer)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/preferred.py", line 181, in block_min_content_width
   context, box, min_content_width, outer)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/preferred.py", line 98, in _block_content_width
   function(context, child, outer=True) for child in box.children
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/preferred.py", line 99, in <listcomp>
   if not child.is_absolutely_positioned()]
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/preferred.py", line 53, in min_content_width
   context, box, outer, is_line_start=True)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/preferred.py", line 205, in inline_min_content_width
   widths = list(widths)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/layout/preferred.py", line 312, in inline_line_widths
   minimum=True))
 File "/usr/local/lib/python3.7/site-packages/weasyprint/text/line_break.py", line 334, in split_first_line
   justification_spacing)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/text/line_break.py", line 278, in create_layout
   context, style['font_size'], style, justification_spacing, max_width)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/text/line_break.py", line 84, in __init__
   self.setup(context, font_size, style)
 File "/usr/local/lib/python3.7/site-packages/weasyprint/text/line_break.py", line 100, in setup
   pango.pango_context_set_round_glyph_positions(pango_context, False)
 File "/usr/local/lib/python3.7/site-packages/cffi/api.py", line 912, in __getattr__
   make_accessor(name)
 File "/usr/local/lib/python3.7/site-packages/cffi/api.py", line 908, in make_accessor
   accessors[name](name)
 File "/usr/local/lib/python3.7/site-packages/cffi/api.py", line 838, in accessor_function
   value = backendlib.load_function(BType, name)
AttributeError: function/symbol 'pango_context_set_round_glyph_positions' not found in library 'libpango-1.0.so.0': /usr/lib/x86_64-linux-gnu/libpango-1.0.so.0: undefined symbol: pango_context_set_round_glyph_positions

no library called "libcairo-2" was found

I'm using cookiecutter-django and I already added django-weasyprint on my requirements.txt andd followed the installation instruction from WeasyPrint but still nothing. When I do docker-compose -f local.yml up --build nothing happens. I also updated the Dockerfile to include the dependencies

# Install apt packages
RUN apt-get update && apt-get install --no-install-recommends -y \
  # dependencies for building Python packages
  build-essential \
  # psycopg2 dependencies
  libpq-dev \
  # WeasyPrint dependencies
  libcairo2 \
  libpango-1.0-0 \
  libpangocairo-1.0-0 \
  libgdk-pixbuf2.0-0

Media can't load

Hello, I have a problem when generating my pdf report with media.

So, my html template looks like this :

{% for image in defect.images_list.all %} <img src="{{ image.image.url }}" width="80" alt="alt" /> {% endfor %}

When I'm generating pdf, every static files, are loaded well.

[30/May/2022 10:59:26] "GET /static/css/icons.min.css HTTP/1.1" 200 357566
[30/May/2022 10:59:26] "GET /static/fontsunicons.eot?34404611 HTTP/1.1" 404 1816
[30/May/2022 10:59:26] "GET /static/fonts/unicons.woff2?34404611 HTTP/1.1" 200 147808
[30/May/2022 10:59:27] "GET /static/fonts/dripicons-v2.eot HTTP/1.1" 200 40522
[30/May/2022 10:59:27] "GET /static/fonts/dripicons-v2.woff HTTP/1.1" 200 26004
[30/May/2022 10:59:27] "GET /static/fonts/materialdesignicons-webfont.eot HTTP/1.1" 200 1148064
[30/May/2022 10:59:27] "GET /static/fonts/materialdesignicons-webfont.woff2?v=6.5.95 HTTP/1.1" 200 361384
[30/May/2022 10:59:28] "GET /static/css/app.min.css HTTP/1.1" 200 535463
[30/May/2022 10:59:28] "GET /static/fonts/Nunito-Light.eot HTTP/1.1" 200 127225
[30/May/2022 10:59:28] "GET /static/fonts/Nunito-Regular.eot HTTP/1.1" 200 114012
[30/May/2022 10:59:28] "GET /static/fonts/Nunito-Regular.woff HTTP/1.1" 200 50968
[30/May/2022 10:59:28] "GET /static/fonts/Nunito-SemiBold.eot HTTP/1.1" 200 116168
[30/May/2022 10:59:28] "GET /static/fonts/Nunito-SemiBold.woff HTTP/1.1" 200 51528
[30/May/2022 10:59:28] "GET /static/fonts/Nunito-Bold.eot HTTP/1.1" 200 116020
[30/May/2022 10:59:28] "GET /static/fonts/Nunito-Bold.woff HTTP/1.1" 200 51940

But when it's the turn of the picture, the GET request is limitless ...
[30/May/2022 10:59:28] "GET /media/2022/05/27/89f7d446-defc-4d6d-b59c-458466b2faaa.jpg HTTP/1.1" 200 300305

I don't understand why the pdf generation is blocked, in my weasyprint logs, nothing, because the program is block.

What I tried :

I replace my media dynamic url with a random image url on the net "https://img-4.linternaute.com/hvfZsuh4tqr8u45GLflQPQaSCZ4=/660x366/smart/327335b117374791b523f9f879d1f559/ccmcms-linternaute/10839618.jpg"

{% for image in defect.images_list.all %} <img src="https://img-4.linternaute.com/hvfZsuh4tqr8u45GLflQPQaSCZ4=/660x366/smart/327335b117374791b523f9f879d1f559/ccmcms-linternaute/10839618.jpg" width="80" alt="alt" /> {% endfor %}

Everything working fine.

I have tried with another random url : "https://cdn.generationvoyage.fr/2021/02/croatie-en-photos-6.jpg"

Not working !

Any ideas ?

function based way to print the pdf and how to debug if the styles are not working

Hi there, I am using weasyprint directly and i cannot get the styles to work.

I googled then found this and django-renderpdf.

I prefer to use django-weasyprint. my questions are:

  1. can django-weasyprint have a function-based way to work? the reason is because i intend to have a backend job using celery to create the pdf
  2. if the styles don't work, how to debug this issue?

btw, i am willing to pay for consultation to speed things up as well. dm me on discord kimsia#3035. I can do sponsorship as well through github if that works too.

Passing Images in Templates

I am attempting to include a logo image for my PDF. The img tag that displays the logo in my HTML is as follows:

<img class="logo" src="/static/images/logo.png" alt="Nordic Naturals">

Is there a way we can pass the image file to the PDF similar to identifying the CSS rules to be followed?

Recursion error with large file.

Traceback

https://pastebin.com/eAHZKiY1

I have a file with ~3.5k lines that keeps giving me a maximum recursion error.

It seems to concern this line in particular

/lib/python3.6/site-packages/weasyprint/formatting_structure/build.py" in element_to_box 155. child_element, style_for, get_image_from_uri, base_url, state))

This is my first time reporting a bug - forgive me for possibly not doing it properly.

P.S. I really like this package - thank you!

Install Instruction unclear

Note: This issue strongly relates to issue #32

I had issues following the installation instructions in the README until coming across the linked issue. There should be some clear docs in the README explaining that the system requirements for weasyprint must be satisfied in order for django-weasyprint to run. I can add if need be.

module 'weasyprint' has no attribute 'fonts'

Hi there,

Weasyprint released a version 53 of their library yesterday (release notes here: https://github.com/Kozea/WeasyPrint/releases/tag/v53.0) and it changed an import:

FontConfiguration is now in the weasyprint.text.fonts module.

Because setup.py uses a >= instead of a ==, when we rebuilt our app yesterday everything stopped working because of the import.

Example in your make test:

======================================================================
ERROR: test_get_pdf (django_weasyprint.tests.test_views.WeasyTemplateViewTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/pierre/Dev/django-weasyprint/django_weasyprint/tests/test_views.py", line 17, in test_get_pdf
    response = self.client.get('/pdf/')
  File "/home/pierre/Dev/django-weasyprint/.tox/py38-dj22/lib/python3.8/site-packages/django/test/client.py", line 535, in get
    response = super().get(path, data=data, secure=secure, **extra)
  File "/home/pierre/Dev/django-weasyprint/.tox/py38-dj22/lib/python3.8/site-packages/django/test/client.py", line 345, in get
    return self.generic('GET', path, secure=secure, **{
  File "/home/pierre/Dev/django-weasyprint/.tox/py38-dj22/lib/python3.8/site-packages/django/test/client.py", line 422, in generic
    return self.request(**r)
  File "/home/pierre/Dev/django-weasyprint/.tox/py38-dj22/lib/python3.8/site-packages/django/test/client.py", line 503, in request
    raise exc_value
  File "/home/pierre/Dev/django-weasyprint/.tox/py38-dj22/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/pierre/Dev/django-weasyprint/.tox/py38-dj22/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/pierre/Dev/django-weasyprint/.tox/py38-dj22/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response
    response = response.render()
  File "/home/pierre/Dev/django-weasyprint/.tox/py38-dj22/lib/python3.8/site-packages/django/template/response.py", line 106, in render
    self.content = self.rendered_content
  File "/home/pierre/Dev/django-weasyprint/django_weasyprint/views.py", line 94, in rendered_content
    document = self.get_document()
  File "/home/pierre/Dev/django-weasyprint/django_weasyprint/views.py", line 77, in get_document
    font_config = self.get_font_config()
  File "/home/pierre/Dev/django-weasyprint/django_weasyprint/views.py", line 52, in get_font_config
    return weasyprint.fonts.FontConfiguration()
AttributeError: module 'weasyprint' has no attribute 'fonts'

I created a PR which fixes this problem here: #52

Thank you

statics files lost

I just tried to install the new django-weasyprint with pip. Before, I was using the 0.1 version. Now i have the 0.5 version.

So I changed PDFTemplateResponseMixin to the new WeasyTemplateResponseMixin.

My view (just an inherit view of a classic TemplateView) was working perfectly fine before, but
now all the statics files inserted in my templates with static tag don't work (css and images).

Any ideas?

Python 3.6 support

I am wondering if you guys are going to support python 3.6 soon, could you give me some insight on this subject?

__init__() takes 1 positional argument but 2 were given

Hi guys

I'm trying use this package for my project but it doesn't works, i have the next code:
views.py

# PDF file view
class RecipePDFPrintView(WeasyTemplateView):
    model = Recipe
    template_name = 'recipe_detail_pdf.html'  # TODO
    pdf_stylesheets = [
        settings.STATIC_ROOT + 'dist/css/pdf.css',
    ]

urls.py

 url(r'^export/(?P<slug>[-\w]+)/pdf/$', views.RecipePDFPrintView, name='recipe_export'),  

template.html

                                    <span class="wprm-recipe-print wprm-color-accent"> 
                                        <a href="{% url 'recipe_export' slug=recipe.slug %}"> 
                                            <i class="fa fa-file-pdf-o"></i> {% trans 'PDF' %}</a> 
                                    </span> 

But i'm getting this error.

i can not find a more complex example for use this package, so, i need your help.

Thank you.

Signature of inherited functions

I was extending your code a bit and I noticed a minor issue. I am not sure if this really is an issue, but I thought I'd bring it to your attention and let you decide.

In
https://github.com/dekkers/django-weasyprint/blob/master/django_weasyprint/views.py#L35 the signature of render_to_response does not match that of its super class implementation TemplateResponseMixin.render_to_response https://github.com/django/django/blob/stable/1.6.x/django/views/generic/base.py#L119

Similarly for PDFTemplateResponse.init.

Thank you for your work.

Static images not fetched on production server

Something seems to be going wrong when fetching urls from a static, maybe because my static_url is on a subdomain?

I have my pdf rendering perfectly fine locally with static_url:
STATIC_URL = '/static/'

However on my production server the images seem not to load with this static url:

STATIC_URL = 'https://static.domain.com/'

I'm using django-weasyprint 0.5.4

I'm using a simple TemplateView with WeasyTemplateResponseMixin:

class GenerateSTPContractPDF(WeasyTemplateResponseMixin, TemplateView):
    template_name = 'contract.html'

And in my template I'm loading the images from static:

{% load staticfiles %}
<img src="{% static 'myimage.jpg' %}">

Is this a bug or am I doing something wrong?

image issues on next page

Hi,

My current issue: the first image of the next page is not being rendered in a PDF. A simple html page doesn't have the issue.
I am trying to use a simple templating loop to render the objects from my database. The PDF is about print labels with fixed width and height.
django v5
tailwindcss v 3.8
Any ideas?

<body class="font-lato bg-gray-900 flex justify-center">
    <div class="bg-white" style="width:210mm; height:297mm;">
        <div class="flex flex-wrap">
            <!--flex flex-wrap-->
            {% for work in works %}
                <div class="flex items-center justify-center" style="width:{{dimensions.0}}mm; height:{{dimensions.1}}mm; border-left-width: 0px;
                border-right-width: 0px;">
                    <img class="p-2 m-auto" id="image" src="{{ work.image.url }}" alt="image" style="width: 100px; object-fit: contain;">
                    
                    <div id="metadata" class="text-center my-auto p-5 w-full" style="color: rgb(75,85,99); width: 190px; object-fit: contain; font-size: 10px;">
                        <!--INVENTORY NUMBER-->
                        <p class="text-xl mb-1">INV-{{work.inventory_number}}</p>
                        <!--NAME-->
                        {% if work.artist %}
                            <p class="uppercase">{{work.artist.name}}</p>
                        {% else %}
                        <p class="uppercase">{{request.user.first_name}} {{request.user.last_name}}</p>
                        {% endif %}
                        <!--ARTWORK TITLE-->
                        <p class="italic">{{work.title}}</p>
                        <!--DIMENSIONS-->
                        {% if work.width and work.height %}
                            <p class="italic">{{work.width|floatformat}} x {{work.height|floatformat}} {% if work.depth %}x {{work.depth|floatformat}} {% endif %}</p>
                        {% endif %}
                        <!--MATERIALS-->
                        {% if work.materials %}
                            <p>{{work.materials}}</p>
                        {% endif %}

                    </div>
                </div>
            {% endfor %} 
        </div>
    </div> 
</body>
class LabelCreationView(WeasyTemplateResponseMixin, TemplateView):
    label_options = {
        1: (70, 42.3),
        2: (105, 42.3)
    }
    model = Work.objects.all()
    template_name = 'dashboard/pdf_templates/label_template.html'
    pdf_attachment = False
    pdf_stylesheets = [
        '/theme/static/css/dist/styles.css',
    ]

    def post(self, request, *args, **kwargs):
        selected_work_values_json = request.POST.get('selected_work_values')
        selected_label_dimensions = request.POST.get('selected_label_dimensions')
        
        selected_work_values = json.loads(selected_work_values_json)
        self.label_dimensions = self.label_options.get(int(selected_label_dimensions), (0, 0))
        self.works = Work.objects.filter(pk__in=selected_work_values)
        
        return super().get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['works'] = self.works
        context['dimensions'] = self.label_dimensions
        return context

New release

Can you do a new release with the python 3 urllib changes?

text overlaps when using intcoma template filter

if i try to print invoice without filter its working fine like
Screenshot 2021-01-11 131256

but when i try to add comas with intcoma filter whole text starts overlap eachother like this
Screenshot 2021-01-11 131349

i think it may be because of text over flow any idea on how to solve it

Usage of library

Can anyone explain how to correctly use this module?
When I do something like this:

class TestView(WeasyTemplateView):
    template_name = 'account/visit.html'

My html code is:

<html>
    <head>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Fondamento" />
        <link href="https://db.onlinewebfonts.com/c/0f106940a384f214837a8df504786e1a?family=Formular" rel="stylesheet" type="text/css"/>
    </head>
    <body>
        <div class="card">
            <div class="title-text">
                Чаевые картой
                просто и удобно
            </div>
            <div class="list-text">
                <ul>
                    <li>Не облагаются налогом</li>
                    <li>Удобный вывод на карту</li>
                </ul>
            </div>
            <div class="qr-code">
                <img src="{{ user.qr_code.qrcode.url }}" style="width: 400px; height: 400px;">
            </div>
        </div>
        <style>
            .card {
                position: relative;
                width: 1200px;
                height: 628px;
                background: #D8CDE6;
            }
            .title-text {
                position: absolute;
                width: 346px;
                height: 88px;
                left: 142px;
                top: 220px;

                font-family: Formular;
                font-style: normal;
                font-weight: normal;
                font-size: 36px;
                line-height: 44px;

                color: #000000;
            }
            .list-text {
                position: absolute;
                width: 490px;
                height: 100px;
                left: 155px;
                top: 351px;
                font-family: Formular;

                font-style: normal;
                font-weight: normal;
                font-size: 36px;
                line-height: 50px;

                color: #000000;
            }
            .qr-code {
                position: absolute;
                width: 490px;
                height: 200px;
                left: 750px;
                top: 50px;
            }
        </style>
    </body>
</html>

I get this. This is correct size and background, but there is no text and image. I don't know how to insert image and add text.

pdf_attachment is not work

Like this:

class EngineeringQuantityCertificationPdfPreviewView(
    WeasyTemplateResponseMixin, DetailView
):
    def get_pdf_filename(self):
        object = self.get_object()
        title = clean_filename(object.get_human_title())
        return f"{title}.pdf"

It does not show any dialog.
It seems like this line didn't work or got overridden. So, in the browser's reception, Content-Disposition isn't actually set as it was configured.
Is this a bug?

with Django 4.2.4

Images not showing

I'm trying to render an html template with some images.
It works fine as a normal template view. Then I see the images.
But when I try to make the PDF they are not showing. I'm using the basic code from the example

class MyModelView(DetailView):
     # vanilla Django DetailView
     model = Factuur
     template_name = 'facturatie/pdf.html'

   
class MyModelPrintView(WeasyTemplateResponseMixin, MyModelView):
    # show pdf in-line (default: True, show download dialog)
    pdf_attachment = False
    # custom response class to configure url-fetcher
    response_class = WeasyTemplateResponse

In my template

  {% load static%}
  ...
  <img src="{%static '/facturatie/logo.png' %}" alt="logo" />

Did anyone experience this before?

Very verbose logs

Hi !

Thanks a lot for you work. It's amazing and very usefull for us.
I try to install it within my stack, and with the last update ( from django-weasyprint 1 to 2.1.0 ), the ouput logger.info is become very very verbose on each pdf creation :)

Did you know how to calm down the log ?
Thanks !

@font-face declared fonts not embedded in pdf

Hello, I recently started using django-weasyprint in a project to produce nice pdf-reports. However, the fonts I declared in my css using @font-face rules were not embedded in the final pdf.
This is probably due to a missing font_config attribute when django-weasyprint instanciates css objects. According to weasyprint docs, you should declare the font-config attribute also on css instance when using font-face rules. I tested it by writing a function view that directly uses weasyprint.
So I downloaded the latest stable version of django-weasyprint and fixed it locally. I'll create a pull request.

The output of pdffonts command before the fix:

name                                 type              encoding         emb sub uni object ID
------------------------------------ ----------------- ---------------- --- --- --- ---------
QHAAMN+DejaVuSans-Bold               TrueType          WinAnsi          yes yes yes      6  0
AYDOZU+DejaVuSans-ExtraLight         TrueType          WinAnsi          yes yes yes      7  0
UJBTBB+DejaVuSans                    TrueType          WinAnsi          yes yes yes      8  0

and after the fix:

name                                 type              encoding         emb sub uni object ID
------------------------------------ ----------------- ---------------- --- --- --- ---------
BQMJZP+FiraSans-Bold                 Type 1C           WinAnsi          yes yes yes      6  0
FTQEDP+FiraSans-Light                Type 1C           WinAnsi          yes yes yes      7  0
KUVOMO+FiraSans-Regular              Type 1C           WinAnsi          yes yes yes      8  0

Regards Oliver

Potential regression with use of WEASYPRINT_BASEURL and images

I have a small project that uses django-weasyprint for generating PDFs from Django templates.

It works just fine but after the latest upgrade to v2.2.1 and Weasyprint v59.0 it noticed that my tests stopped working while running in both development and production works just fine.

The issue seems to be that WEASYPRINT_BASEURL is no longer used as the base path for images the way it could previously be used. In my tests I use that for referring to a local path on the filesystem as can be seen here although it doesn't seem like this is related to overriding settings in tests.

So it seems to me like this might be a regression as the WEASYPRINT_BASEURL is ignored for image paths which I assume shouldn't be the case.

I haven't done a lot of time digging into this, but it seems to me like it might be related to this change in Weasyprint.

Not sure if this could be an issue in Weasyprint or django-weasyprint. It is of course also very likely that I've misunderstood something or been using the WEASYPRINT_BASEURL incorrectly.

I'll be happy to look more into this and perhaps extends the tests to reproduce this but it would be nice to know if this is indeed an issue before I look any further.

Thanks a lot.

Problem getting images from `sorl-thumbnail`

Hi boys,

I have a model with images handled by sorl-thumbnail but i am no getting their respective thumbnail images:
documento generado.pdf

This is the main view:
mainview

I am getting the video thumbnail whit this:

                {% video recipe.video '950x500' as my_video %}
                    <img class="video-image" src="{{ my_video.thumbnail }}">
                {% endvideo %}

And i'm using this fot other images:

{% thumbnail recipe.author.profile.photo "100x100" crop="center" as im %}
                                <img alt="{{ recipe.author.get_full_name }}"
                                     src="{{ im.url }}"
                                     srcset="{{ im.url|resolution:"2x" }}"
                                     class="avatar avatar-60 photo"
                                     height="60" width="60">
                            {% endthumbnail %}

And as you can see in the file, i'm getting only the alt text instead the images.

Why?

Custom font not loaded/working using WeasyTemplateResponseMixin for PDF creation

Hi there,

I am using the WeasyTemplateResponseMixin and trying to get a custom font to load. The font files are located in my django statics dir.

Here's my code:

SCSS:

$karla-font: MyFont, Arial, Helvetica, sans-serif;

@font-face {
  font-family: "MyFont";
  src: url('/static/fonts/MyFont-Regular.ttf') format("truetype"),
  url('/static/fonts/MyFont-Regular.otf') format("opentype");
}


body {
  font-family: $karla-font;
}

View:

class GeneratePdfView(WeasyTemplateResponseMixin, TemplateView):
    template_name = "my_template.html"
    pdf_filename = "my-export.pdf"
    valid_form = None

    def post(self, request, form, *args, **kwargs):
        self.valid_form = form
        return super().get(request, form, *args, **kwargs)

    def get_pdf_stylesheets(self):
        return [Path(Path(settings.APPS_DIR).as_posix() + '/static/scss/pdf/my-styles.css').as_posix()]

    ...

Hints:

  • The rest of the styles are being loaded correctly.
  • The url resolver does not try to load the fonts, only the images within the template
  • I tried prefixing the url to the fonts with file:
  • I tried a relative path

Any ideas what I might be doing wrong? Unfortunately this feature is not covered in the docs AFAIK 😕

Thx!
Ronny

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.