Skip to content

Commit

Permalink
Make it possible to set WeasyPrint options
Browse files Browse the repository at this point in the history
  • Loading branch information
dekkers committed Jan 22, 2024
1 parent b7acb1c commit f6adcd7
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions django_weasyprint/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@


class WeasyTemplateResponse(TemplateResponse):
def __init__(self, filename=None, stylesheets=None, attachment=True,
def __init__(self, filename=None, stylesheets=None, attachment=True, options=None,
*args, **kwargs):
"""
An HTTP response class with PDF or PNG document as content.
Expand All @@ -18,6 +18,7 @@ def __init__(self, filename=None, stylesheets=None, attachment=True,
:param stylesheets: list of additional stylesheets
"""
self._stylesheets = stylesheets or []
self._options = options or {}
super().__init__(*args, **kwargs)
if filename:
display = 'attachment' if attachment else 'inline'
Expand Down Expand Up @@ -82,6 +83,7 @@ def get_document(self):
return html.render(
stylesheets=self.get_css(base_url, url_fetcher, font_config),
font_config=font_config,
option=self._options,
)

@property
Expand All @@ -90,7 +92,7 @@ def rendered_content(self):
Returns rendered PDF pages.
"""
document = self.get_document()
return document.write_pdf()
return document.write_pdf(options=self._options)


class WeasyTemplateResponseMixin(TemplateResponseMixin):
Expand All @@ -102,6 +104,7 @@ class WeasyTemplateResponseMixin(TemplateResponseMixin):
pdf_filename = None
pdf_attachment = True
pdf_stylesheets = []
pdf_options = {}

def get_pdf_filename(self):
"""
Expand All @@ -122,6 +125,12 @@ def get_pdf_stylesheets(self):
"""
return self.pdf_stylesheets

def get_pdf_options(self):
"""
Returns dictionary of WeasyPrint options.
"""
return self.pdf_options

def render_to_response(self, context, **response_kwargs):
"""
Renders PDF document and prepares response by calling on
Expand All @@ -134,6 +143,7 @@ def render_to_response(self, context, **response_kwargs):
'attachment': self.pdf_attachment,
'filename': self.get_pdf_filename(),
'stylesheets': self.get_pdf_stylesheets(),
'options': self.get_pdf_options(),
})
return super().render_to_response(
context, **response_kwargs
Expand Down

0 comments on commit f6adcd7

Please sign in to comment.