Skip to content

Commit

Permalink
Merge pull request #79 from dekkers/weasyprint-options
Browse files Browse the repository at this point in the history
Make it possible to set WeasyPrint options
  • Loading branch information
fdemmer authored Feb 23, 2024
2 parents 2d1b717 + cfeb259 commit 053b0b2
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 3 deletions.
2 changes: 2 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ Example
class DownloadView(WeasyTemplateResponseMixin, MyDetailView):
# suggested filename (is required for attachment/download!)
pdf_filename = 'foo.pdf'
# set PDF variant to pdf/ua-1
pdf_options = {'pdf_variant': 'pdf/ua-1'}
class DynamicNameView(WeasyTemplateResponseMixin, MyDetailView):
# dynamically generate filename
Expand Down
7 changes: 7 additions & 0 deletions django_weasyprint/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,15 @@ class PDFView(WeasyTemplateView):
template_name = 'example.html'


class PDFOptionsView(WeasyTemplateView):
template_name = 'example.html'
pdf_stylesheets = [static('css/print.css')]
pdf_options = {'pdf_version': '1.6'}


urlpatterns = [
path('html/', BaseView.as_view()),
path('pdf/', PDFView.as_view()),
path('pdf/download/', PDFDownloadView.as_view()),
path('pdf/options/', PDFOptionsView.as_view()),
]
13 changes: 13 additions & 0 deletions django_weasyprint/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,16 @@ def test_get_pdf(self):
self.assertEqual(response['content-type'], 'application/pdf')
self.assertFalse(response.has_header('content-disposition'))
self.assertEqual(response.content[:4], b'%PDF')

@mock.patch('weasyprint.open', new_callable=lambda: mock.mock_open(read_data=b''))
def test_get_pdf_options(self, mock_open):
response = self.client.get('/pdf/options/')
self.assertEqual(response.status_code, 200)

# additional css from pdf_stylesheets attribute
mock_open.assert_called_once_with('/static/css/print.css', 'rb')

self.assertTrue(response.has_header('content-type'))
self.assertEqual(response['content-type'], 'application/pdf')
self.assertFalse(response.has_header('content-disposition'))
self.assertEqual(response.content[:8], b'%PDF-1.6')
22 changes: 19 additions & 3 deletions django_weasyprint/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,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 @@ -17,8 +17,10 @@ def __init__(self, filename=None, stylesheets=None, attachment=True,
:param attachment: set `Content-Disposition` 'attachment', a `filename`
must be given if `True` (default: `True`)
:param stylesheets: list of additional stylesheets
:param options: dictionary of options passed to WeasyPrint
"""
self._stylesheets = stylesheets or []
self._options = options.copy() if options else {}
super().__init__(*args, **kwargs)
if filename:
display = 'attachment' if attachment else 'inline'
Expand Down Expand Up @@ -80,9 +82,15 @@ def get_document(self):
base_url=base_url,
url_fetcher=url_fetcher,
)

self._options.setdefault(
'stylesheets',
self.get_css(base_url, url_fetcher, font_config),
)

return html.render(
stylesheets=self.get_css(base_url, url_fetcher, font_config),
font_config=font_config,
**self._options,
)

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


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

def get_pdf_filename(self):
"""
Expand All @@ -123,6 +132,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 @@ -135,6 +150,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 053b0b2

Please sign in to comment.