diff options
author | James Turnbull <james@jamesturnbull.org> | 2013-01-16 07:41:28 -0800 |
---|---|---|
committer | James Turnbull <james@jamesturnbull.org> | 2013-01-16 07:41:28 -0800 |
commit | a03c1e14b0da1999590442719c42293a88ab9e3b (patch) | |
tree | 45a1966ab8da505e62490c5a8651075c4ed157a1 /wkhtmltopdf/utils.py | |
parent | 887d3c6600750dd573e768c6fdf370a6a607d39b (diff) | |
parent | cda678a3ea9b01a684c6e2d3ed636834f41c96f8 (diff) | |
download | django-wkhtmltopdf-a03c1e14b0da1999590442719c42293a88ab9e3b.tar.gz django-wkhtmltopdf-a03c1e14b0da1999590442719c42293a88ab9e3b.tar.bz2 django-wkhtmltopdf-a03c1e14b0da1999590442719c42293a88ab9e3b.zip |
Merge pull request #28 from incuna/downloading-option
Make PDF downloading an option
Diffstat (limited to 'wkhtmltopdf/utils.py')
-rw-r--r-- | wkhtmltopdf/utils.py | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/wkhtmltopdf/utils.py b/wkhtmltopdf/utils.py index 63310c3..e5bd102 100644 --- a/wkhtmltopdf/utils.py +++ b/wkhtmltopdf/utils.py @@ -4,6 +4,7 @@ from copy import copy from functools import wraps from itertools import chain import os +import re import sys import urllib from urlparse import urljoin @@ -121,3 +122,37 @@ def http_quote(string): def pathname2fileurl(pathname): """Returns a file:// URL for pathname. Handles OS-specific conversions.""" return urljoin('file:', urllib.pathname2url(pathname)) + + +def make_absolute_paths(content): + """Convert all MEDIA files into a file://URL paths in order to + correctly get it displayed in PDFs.""" + + overrides = [ + { + 'root': settings.MEDIA_ROOT, + 'url': settings.MEDIA_URL, + }, + { + 'root': settings.STATIC_ROOT, + 'url': settings.STATIC_URL, + } + ] + has_scheme = re.compile(r'^[^:/]+://') + + for x in overrides: + if has_scheme.match(x['url']): + continue + + if not x['root'].endswith('/'): + x['root'] += '/' + + occur_pattern = '''["|']({0}.*?)["|']''' + occurences = re.findall(occur_pattern.format(x['url']), content) + occurences = list(set(occurences)) # Remove dups + for occur in occurences: + content = content.replace(occur, + pathname2fileurl(x['root']) + + occur[len(x['url']):]) + + return content |