How to use the weasyprint.CSS function in weasyprint

To help you get started, we’ve selected a few weasyprint examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github BlackLight / platypush / platypush / backend / http / request / rss / __init__.py View on Github external
<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))
github uccser / cs-unplugged / csunplugged / resources / utils / BaseResourceGenerator.py View on Github external
if not isinstance(copy_data, list):
                copy_data = [copy_data]
            copy_data = resize_encode_resource_images(
                self.options["paper_size"].value,
                copy_data
            )
            context["all_data"].append(copy_data)

        filename = "{} ({})".format(resource_name, self.subtitle)
        context["filename"] = filename

        pdf_html = render_to_string("resources/base-resource-pdf.html", context)
        html = HTML(string=pdf_html, base_url=settings.BUILD_ROOT)
        css_file = finders.find("css/print-resource-pdf.css")
        css_string = open(css_file, encoding="UTF-8").read()
        base_css = CSS(string=css_string)
        return (html.write_pdf(stylesheets=[base_css]), filename)
github uccser / cs-unplugged / csunplugged / resources / content / sorting_network / generate.py View on Github external
base_image_settings['range_max'] = 1000
        base_image_settings['font_size'] = 90

    # Create resource image
    base_image_settings['base_image_path'] = 'resources/content/{}/sorting-network-colour.png'.format(resource.folder)
    base_image_settings['font_path'] = 'resources/content/fonts/PatrickHand-Regular.ttf'
    with Pool() as pool:
        context['resource_images'] = pool.map(PageCreator(base_image_settings), range(0, int(request.GET['copies'])))

    # Write to PDF
    context['paper_size'] = paper_size
    context['resource'] = resource
    html_string = render_to_string('resources/base-resource-pdf.html', context)

    html = HTML(string=html_string, base_url=request.build_absolute_uri())
    base_css = CSS(string=open('static/css/print-resource-pdf.css', encoding='UTF-8').read())
    pdf_file = html.write_pdf(stylesheets=[base_css]);

    response = HttpResponse(pdf_file, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="example.pdf"'
    return response
github dkmstr / openuds / server / src / uds / core / reports / report.py View on Github external
return default_url_fetcher(url)

        with open(stock.getStockCssPath('report.css'), 'r') as f:
            css = f.read()

        css = (
            css.replace("{header}", header or _('Report'))
            .replace('{page}', _('Page'))
            .replace('{of}', _('of'))
            .replace('{water}', water or 'UDS Report')
            .replace('{printed}', _('Printed in {now:%Y, %b %d} at {now:%H:%M}').format(now=datetime.now()))
        )

        h = HTML(string=html, url_fetcher=report_fetcher)
        c = CSS(string=css)

        return h.write_pdf(stylesheets=[c])
github fdemmer / django-weasyprint / django_weasyprint / views.py View on Github external
def get_css(self, base_url, url_fetcher):
        tmp = []
        for value in self._stylesheets:
            css = weasyprint.CSS(
                value,
                base_url=base_url,
                url_fetcher=url_fetcher,
            )
            if css:
                tmp.append(css)
        return tmp
github jmaupetit / md2pdf / md2pdf.py View on Github external
# Paths
    md_file_path = arguments.get('INPUT.MD')
    pdf_file_path = arguments.get('OUTPUT.PDF')
    css_file_path = arguments.get('--css', None)

    # Convert markdown to html
    raw_html = markdown_path(md_file_path)

    # Weasyprint HTML object
    html = HTML(string=raw_html)

    # Get styles
    css = []
    if css_file_path:
        css.append(CSS(filename=css_file_path))

    # Generate PDF
    html.write_pdf(pdf_file_path, stylesheets=css)

    return 1
github stoq / stoq / stoqlib / reporting / report.py View on Github external
def render(self, stylesheet=None):
        import weasyprint

        template_dir = environ.get_resource_filename('stoq', 'template')
        if platform.system() == 'Windows':
            # FIXME: Figure out why this is breaking
            # On windows, weasyprint is eating the last directory of the path
            template_dir = os.path.join(template_dir, 'foobar')
        html = weasyprint.HTML(string=self.get_html(),
                               base_url=template_dir)

        return html.render(stylesheets=[weasyprint.CSS(string=stylesheet)])