Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
<title>{title}</title>
<style>{style}</style>
{{content}}
'''.format(title=self.title, style=style, content=content)
with open(digest_filename, 'w', encoding='utf-8') as f:
f.write(content)
elif self.digest_format == 'pdf':
import weasyprint
from weasyprint.fonts import FontConfiguration
font_config = FontConfiguration()
css = [weasyprint.CSS('https://fonts.googleapis.com/css?family=Merriweather'),
weasyprint.CSS(string=style, font_config=font_config)]
weasyprint.HTML(string=content).write_pdf(digest_filename, stylesheets=css)
else:
raise RuntimeError('Unsupported format: {}. Supported formats: ' +
'html or pdf'.format(self.digest_format))
digest_entry = FeedDigest(source_id=source_record.id,
format=self.digest_format,
filename=digest_filename)
session.add(digest_entry)
self.logger.info('{} digest ready: {}'.format(self.digest_format, digest_filename))
session.commit()
self.logger.info('Parsing RSS feed {}: completed'.format(self.title))
yield specificity, check_style_attribute(
element, 'text-align:%s' % align)
elif element.tag == 'col':
if element.get('width'):
style_attribute = 'width:%s' % element.get('width')
if element.get('width').isdigit():
style_attribute += 'px'
yield specificity, check_style_attribute(
element, style_attribute)
elif element.tag == 'hr':
size = 0
if element.get('size'):
try:
size = int(element.get('size'))
except ValueError:
LOGGER.warning('Invalid value for size: %s', size)
if (element.get('color'), element.get('noshade')) != (None, None):
if size >= 1:
yield specificity, check_style_attribute(
element, 'border-width:%spx' % (size / 2))
elif size == 1:
yield specificity, check_style_attribute(
element, 'border-bottom-width:0')
elif size > 1:
yield specificity, check_style_attribute(
element, 'height:%spx' % (size - 2))
if element.get('width'):
style_attribute = 'width:%s' % element.get('width')
if element.get('width').isdigit():
style_attribute += 'px'
yield specificity, check_style_attribute(
element, style_attribute)
def expand_page_break_before_after(base_url, name, tokens):
"""Expand legacy ``page-break-before`` and ``page-break-after`` properties.
See https://www.w3.org/TR/css-break-3/#page-break-properties
"""
keyword = get_single_keyword(tokens)
new_name = name.split('-', 1)[1]
if keyword in ('auto', 'left', 'right', 'avoid'):
yield new_name, keyword
elif keyword == 'always':
yield new_name, 'page'
box_children = list(box.enumerate_skip(skip))
for i, (index, child) in enumerate(box_children):
child.position_y = box.position_y
if child.is_absolutely_positioned():
child.position_x = position_x
placeholder = AbsolutePlaceholder(child)
line_placeholders.append(placeholder)
waiting_children.append((index, placeholder))
if child.style.position == 'absolute':
absolute_boxes.append(placeholder)
else:
fixed_boxes.append(placeholder)
continue
elif child.is_floated():
child.position_x = position_x
float_width = shrink_to_fit(
context, child, containing_block.width)
# To retrieve the real available space for floats, we must remove
# the trailing whitespaces from the line
non_floating_children = [
child_ for _, child_ in (children + waiting_children)
if not child_.is_floated()]
if non_floating_children:
float_width -= trailing_whitespace_size(
context, non_floating_children[-1])
if float_width > max_x - position_x or waiting_floats:
# TODO: the absolute and fixed boxes in the floats must be
# added here, and not in iter_line_boxes
waiting_floats.append(child)
else:
@handle_min_max_width
def inline_block_width(box, context, containing_block):
if box.width == 'auto':
box.width = shrink_to_fit(context, box, containing_block.width)
for i, child in enumerate(box.children[skip:]):
index = i + skip
child.position_y = box.position_y
if child.is_absolutely_positioned():
child.position_x = position_x
placeholder = AbsolutePlaceholder(child)
line_placeholders.append(placeholder)
waiting_children.append((index, placeholder))
if child.style['position'] == 'absolute':
absolute_boxes.append(placeholder)
else:
fixed_boxes.append(placeholder)
continue
elif child.is_floated():
child.position_x = position_x
float_width = shrink_to_fit(context, child, containing_block.width)
# To retrieve the real available space for floats, we must remove
# the trailing whitespaces from the line
non_floating_children = [
child_ for _, child_ in (children + waiting_children)
if not child_.is_floated()]
if non_floating_children:
float_width -= trailing_whitespace_size(
context, non_floating_children[-1])
if float_width > max_x - position_x or waiting_floats:
# TODO: the absolute and fixed boxes in the floats must be
# added here, and not in iter_line_boxes
waiting_floats.append(child)
else:
child = float_layout(
cb_x, cb_y, cb_width, cb_height = containing_block
# TODO: handle bidi
padding_plus_borders_x = padding_l + padding_r + border_l + border_r
translate_x = 0
translate_box_width = False
default_translate_x = cb_x - box.position_x
if left == right == width == 'auto':
if margin_l == 'auto':
box.margin_left = 0
if margin_r == 'auto':
box.margin_right = 0
available_width = cb_width - (
padding_plus_borders_x + box.margin_left + box.margin_right)
box.width = shrink_to_fit(context, box, available_width)
elif left != 'auto' and right != 'auto' and width != 'auto':
width_for_margins = cb_width - (
right + left + padding_plus_borders_x)
if margin_l == margin_r == 'auto':
if width + padding_plus_borders_x + right + left <= cb_width:
box.margin_left = box.margin_right = width_for_margins / 2
else:
box.margin_left = 0
box.margin_right = width_for_margins
elif margin_l == 'auto':
box.margin_left = width_for_margins
elif margin_r == 'auto':
box.margin_right = width_for_margins
else:
box.margin_right = width_for_margins
translate_x = left + default_translate_x
def inline_block_width(box, context, containing_block):
if box.width == 'auto':
box.width = shrink_to_fit(context, box, containing_block.width)
def render_pdf(self):
# Only import weasyprint when required as production
# environment does not have it installed.
from weasyprint import HTML, CSS
# Create HTML
context = dict()
context["chapters"] = Chapter.objects.all()
filename = "CSFG PDF (test)"
context["filename"] = filename
pdf_html = render_to_string("pdf/base.html", context)
html = HTML(
string=pdf_html,
base_url=settings.BUILD_ROOT,
url_fetcher=self.django_url_fetcher,
)
# Get CSS
css_file = finders.find("css/website.css")
css_string = open(css_file, encoding="UTF-8").read()
base_css = CSS(string=css_string)
# Create PDF
return (html.write_pdf(stylesheets=[base_css]), filename)
def bind(self):
logger.debug('Binding %s.pdf', self.file_name)
pdf_path = os.path.join(self.app.output_path, 'pdf')
os.makedirs(pdf_path, exist_ok=True)
all_pages = []
bar = IncrementalBar('Adding chapters to PDF', max=len(self.chapters))
bar.start()
if os.getenv('debug_mode') == 'yes':
bar.next = lambda: None # Hide in debug mode
# end if
try:
html = HTML(string=self.create_intro())
all_pages += html.render().pages
logger.info('Added intro page')
for chapter in self.chapters:
html_string = chapter['body']
html = HTML(string=html_string)
all_pages += html.render().pages
logger.info('Added chapter %d', chapter['id'])
bar.next()
# end for
finally:
bar.clearln()
# bar.finish()
# end try
html = HTML(string=self.make_metadata())