Python weasyprint.HTML Examples

The following are 30 code examples for showing how to use weasyprint.HTML(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module weasyprint , or try the search function .

Example 1
Project: insightconnect-plugins   Author: rapid7   File: action.py    License: MIT License 6 votes vote down vote up
def run(self, params={}):
        text = params.get('text')

        html_template = """
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title></title></head>
<body><pre>{}</pre></body>
</html>"""
        # Wrap text preserving existing newlines
        text = '\n'.join(
            wrapped for line in text.splitlines() for wrapped in wrap(
                line, width=70, expand_tabs=False,
                replace_whitespace=False, drop_whitespace=False
            )
        )
        text = escape(text)
        html_content = html_template.format(text)
        pdf_content = HTML(string=html_content).write_pdf()

        b64_content = b64encode(pdf_content).decode()

        return {'pdf': b64_content} 
Example 2
Project: wagtailinvoices   Author: SableWalnut   File: models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def serve_pdf(self, request):
        # Render html content through html template with context
        template = get_template(settings.PDF_TEMPLATE)
        context = {
            'invoice': self,
        }

        html = template.render(context)

        # Write PDF to file
        document_html = HTML(string=html, base_url=request.build_absolute_uri())
        document = document_html.render()
        if len(document.pages) > 1:
            for page in document.pages[1:]:
                str(page)
            pdf = document.write_pdf()
        else:
            pdf = document.write_pdf()
        #response = HttpResponse(html)
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'filename="Invoice {0} | Invoice {0}.pdf"'.format(self.id)
        return response 
Example 3
Project: mkdocs-pdf-export-plugin   Author: zhaoterryy   File: renderer.py    License: MIT License 6 votes vote down vote up
def render_doc(self, content: str, base_url: str, rel_url: str = None):
        soup = BeautifulSoup(content, 'html.parser')

        self.inject_pgnum(soup)

        stylesheet = self.theme.get_stylesheet()
        if stylesheet:
            style_tag = soup.new_tag('style')
            style_tag.string = stylesheet

            soup.head.append(style_tag)

        
        if self.combined:
            soup = prep_combined(soup, base_url, rel_url)
        else:
            soup = prep_separate(soup, base_url)

        html = HTML(string=str(soup))
        return html.render() 
Example 4
Project: rpl-attacks   Author: dhondta   File: report.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def generate_report(path, theme=None, intype='md'):
    """
    This function generates a "report.pdf" from a "report.[md|html]" template using weasyprint.

    :param path: path of report.[md|html]
    :param theme: full or relative (to "[path]/themes/") path to the CSS theme
    :param intype: input format
    """
    assert intype in ['html', 'md']
    if intype == 'md':
        input_file = codecs.open(join(path, 'report.md'), mode="r", encoding="utf-8")
        text = input_file.read()
        html = markdown(text)
    else:
        html = open(join(path, 'report.html')).read()
    html = HTML(string=html, base_url='file://{}/'.format(abspath(path)))
    output = join(path, 'report.pdf')
    kwargs = {}
    if theme is not None:
        theme = join(path, "themes", theme)
        if exists(theme):
            kwargs['stylesheets'] = [theme]
    html.write_pdf(output, **kwargs) 
Example 5
Project: amir   Author: Jooyeshgar   File: weasyprintreport.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, url, landscape=False):
        self.operation = Gtk.PrintOperation()

        document = HTML(string=url).render()

        self.operation.connect('begin-print', self.begin_print, document)
        self.operation.connect('draw-page', self.draw_page, document)

        self.operation.set_use_full_page(False)
        self.operation.set_unit(Gtk.Unit.POINTS)
        self.operation.set_embed_page_setup(True)
        if landscape == True:
            pageSetup = Gtk.PageSetup()
            pageSetup.set_orientation(Gtk.PageOrientation.LANDSCAPE)
            self.operation.set_default_page_setup(pageSetup)

        settings = Gtk.PrintSettings()

        directory = GLib.get_user_special_dir(
            GLib.UserDirectory.DIRECTORY_DOCUMENTS) or GLib.get_home_dir()
        ext = settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) or 'pdf'
        uri = 'file://%s/weasyprint.%s' % (directory, ext)
        settings.set(Gtk.PRINT_SETTINGS_OUTPUT_URI, uri)
        self.operation.set_print_settings(settings) 
Example 6
Project: resilient-community-apps   Author: ibmresilient   File: html2pdf.py    License: MIT License 6 votes vote down vote up
def render_pdf(self, input_data, input_data_type, stylesheet):
        '''
        convert html data to pdf
        :param input_data: url to read html or html already
        :param input_data_type: artifact data type. most important when data type is url or uri
        :param stylesheet: used to apply stylesheets for the pdf document. Most useful when showing
            landscape data or font family changes
        :return: binary pdf data
        '''
        if input_data_type and (input_data_type.lower().startswith("url") or input_data_type.lower().startswith("uri")):
            html = weasyprint.HTML(url=input_data)
        else:
            html = weasyprint.HTML(string=input_data)

        if stylesheet:
            css = [weasyprint.CSS(string=stylesheet)]
        else:
            css = None

        return html.write_pdf(None, css) 
Example 7
Project: EagleEye   Author: ThoughtfulDev   File: report.py    License: Do What The F*ck You Want To Public License 5 votes vote down vote up
def makeReport(name, links, preds, instnames):
    #sort
    links = sorted(links)
    preds = sorted(preds)
    instnames = sorted(instnames)

    name = name.strip()
    name = name.replace('%20', '-')
    with open('./report/template.html', 'r') as f:
        template_data = f.read()
    template_data = template_data.replace('{{INPUT_NAME}}', name)
    links_str = ""
    for l in links:
        links_str += "<li>"
        links_str += '<a href="{0}">{0}</a>'.format(l)
        links_str += "</li>"
    template_data = template_data.replace('{{SOCIAL_URLS}}', links_str)
    preds_str = ""
    for p in preds:
        preds_str += "<li>"
        preds_str += p
        preds_str += "</li>"
    template_data = template_data.replace('{{GOOGLE_PREDS}}', preds_str)
    insta_str = ""
    for i in instnames:
        insta_str += "<li>"
        insta_str += '<a href="https://www.instagram.com/{0}">https://instagram.com/{0}</a>'.format(i)
        insta_str += "</li>"
    template_data = template_data.replace('{{INSTA_PROFILES}}', insta_str)
    with open('tmp.html', 'w') as t:
        t.write(template_data)
    doc = HTML('tmp.html')
    doc.write_pdf('{0}_Report.pdf'.format(name))
    os.remove('tmp.html') 
Example 8
Project: Django-3-by-Example   Author: PacktPublishing   File: tasks.py    License: MIT License 5 votes vote down vote up
def payment_completed(order_id):
    """
    Task to send an e-mail notification when an order is
    successfully created.
    """
    order = Order.objects.get(id=order_id)

    # create invoice e-mail
    subject = f'My Shop - EE Invoice no. {order.id}'
    message = 'Please, find attached the invoice for your recent purchase.'
    email = EmailMessage(subject,
                         message,
                         'admin@myshop.com',
                         [order.email])
    # generate PDF
    html = render_to_string('orders/order/pdf.html', {'order': order})
    out = BytesIO()
    stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]
    weasyprint.HTML(string=html).write_pdf(out,
                                           stylesheets=stylesheets)
    # attach PDF file
    email.attach(f'order_{order.id}.pdf',
                 out.getvalue(),
                 'application/pdf')
    # send e-mail
    email.send() 
Example 9
Project: Django-3-by-Example   Author: PacktPublishing   File: views.py    License: MIT License 5 votes vote down vote up
def admin_order_pdf(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    html = render_to_string('orders/order/pdf.html',
                            {'order': order})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = f'filename=order_{order.id}.pdf'
    weasyprint.HTML(string=html).write_pdf(response,
        stylesheets=[weasyprint.CSS(
            settings.STATIC_ROOT + 'css/pdf.css')])
    return response 
Example 10
Project: Django-3-by-Example   Author: PacktPublishing   File: tasks.py    License: MIT License 5 votes vote down vote up
def payment_completed(order_id):
    """
    Task to send an e-mail notification when an order is
    successfully created.
    """
    order = Order.objects.get(id=order_id)

    # create invoice e-mail
    subject = f'My Shop - EE Invoice no. {order.id}'
    message = 'Please, find attached the invoice for your recent purchase.'
    email = EmailMessage(subject,
                         message,
                         'admin@myshop.com',
                         [order.email])
    # generate PDF
    html = render_to_string('orders/order/pdf.html', {'order': order})
    out = BytesIO()
    stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]
    weasyprint.HTML(string=html).write_pdf(out,
                                           stylesheets=stylesheets)
    # attach PDF file
    email.attach(f'order_{order.id}.pdf',
                 out.getvalue(),
                 'application/pdf')
    # send e-mail
    email.send() 
Example 11
Project: Django-3-by-Example   Author: PacktPublishing   File: views.py    License: MIT License 5 votes vote down vote up
def admin_order_pdf(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    html = render_to_string('orders/order/pdf.html',
                            {'order': order})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = f'filename=order_{order.id}.pdf'
    weasyprint.HTML(string=html).write_pdf(response,
        stylesheets=[weasyprint.CSS(
            settings.STATIC_ROOT + 'css/pdf.css')])
    return response 
Example 12
Project: django-freeradius   Author: openwisp   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_pdf(prefix, data):
    template = get_template(BATCH_PDF_TEMPLATE)
    html = HTML(string=template.render(data))
    f = open("{}/{}.pdf".format(settings.MEDIA_ROOT, prefix), "w+b")
    html.write_pdf(target=f)
    f.seek(0)
    return File(f) 
Example 13
Project: lexpredict-contraxsuite   Author: LexPredict   File: utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def clean_html_tags(html):
    """
    Simple regex HTML tag cleaner.
    """
    return re.sub(r'<.+?>', '', html) 
Example 14
Project: lexpredict-contraxsuite   Author: LexPredict   File: utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def download_pdf(data: pd.DataFrame, file_name='output'):
    data_html = data.to_html(index=False)
    try:
        data_pdf = pdf.from_string(data_html, False)
    except OSError:
        env = Environment(loader=FileSystemLoader(settings.PROJECT_DIR('templates')))
        template = env.get_template('pdf_export.html')
        template_vars = {"title": file_name.capitalize(),
                         "table": data_html}
        data_pdf = HTML(string=template.render(template_vars)).write_pdf()
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="{}.{}"'.format(file_name, 'pdf')
    response.write(data_pdf)
    return response 
Example 15
Project: Django-2-by-Example   Author: PacktPublishing   File: views.py    License: MIT License 5 votes vote down vote up
def admin_order_pdf(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    html = render_to_string('orders/order/pdf.html',
                            {'order': order})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename=order_{}.pdf"'.format(order.id)
    weasyprint.HTML(string=html).write_pdf(response,
        stylesheets=[weasyprint.CSS(
            settings.STATIC_ROOT + 'css/pdf.css')])
    return response 
Example 16
Project: Django-2-by-Example   Author: PacktPublishing   File: views.py    License: MIT License 5 votes vote down vote up
def admin_order_pdf(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    html = render_to_string('orders/order/pdf.html',
                            {'order': order})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename=order_{}.pdf"'.format(order.id)
    weasyprint.HTML(string=html).write_pdf(response,
        stylesheets=[weasyprint.CSS(
            settings.STATIC_ROOT + 'css/pdf.css')])
    return response 
Example 17
Project: ross   Author: ross-rotordynamics   File: Report.py    License: MIT License 5 votes vote down vote up
def generate_PDF():
    rotor = ross.rotor_example()

    TEMPLATE = 'report.html'
    CSS = 'report.css'
    OUTPUT_FILENAME = 'my-report.pdf'

    ROOT = Path(os.path.dirname(ross.__file__))/'API_Report'
    ASSETS_DIR = ROOT/'assets'
    TEMPLAT_SRC = ROOT/'templates'
    CSS_SRC = ROOT/ 'static/css'
    OUTPUT_DIR = ROOT/'output'

    env = Environment(loader=FileSystemLoader(str(TEMPLAT_SRC)))
    template = env.get_template(TEMPLATE)
    css = str(CSS_SRC/ CSS)

    bokeh_fig = rotor.plot_rotor()
    bokeh_fig.plot_width=500
    bokeh_fig.plot_height=400
    bokeh_fig.output_backend = 'svg'
    bokeh.io.export_svgs(bokeh_fig,filename = Path(ASSETS_DIR)/'plot.svg')
    template_vars = {'ASSETS_DIR':ASSETS_DIR,'ROTOR_NAME':'CENTRIFUGAL COMPRESSOR','ROTOR_ID':'0123456789'}

    rendered_string = template.render(template_vars)
    html = weasyprint.HTML(string=rendered_string)
    report = os.path.join(OUTPUT_DIR, OUTPUT_FILENAME)
    html.write_pdf(report, stylesheets=[css])
    print(f'Report generated in {OUTPUT_DIR}') 
Example 18
Project: amir   Author: Jooyeshgar   File: weasyprintreport.py    License: GNU General Public License v3.0 5 votes vote down vote up
def showPreview(self, html, landscape=False):
        HTML(string=html, base_url=__file__).write_pdf('report.pdf')
        if sys.platform == 'linux':
            subprocess.call(["xdg-open", 'report.pdf'])
        else:
            os.startfile('report.pdf')
        time.sleep(3)
        os.remove('report.pdf') 
Example 19
Project: knowledge-repo   Author: airbnb   File: pdf.py    License: Apache License 2.0 5 votes vote down vote up
def to_string(self, **opts):
        from weasyprint import HTML, CSS
        html = HTMLConverter(self.kp).to_string()
        return HTML(string=html).write_pdf(stylesheets=[CSS(string='body { font-family: Helvetica, sans-serif !important }')]) 
Example 20
Project: paper2remarkable   Author: GjjvdBurg   File: html.py    License: MIT License 5 votes vote down vote up
def retrieve_pdf(self, pdf_url, filename):
        """Turn the HTML article in a clean pdf file"""
        # Steps
        # 1. Pull the HTML page using requests
        # 2. Extract the article part of the page using readability
        # 3. Convert the article HTML to markdown using html2text
        # 4. Convert the markdown back to HTML (this is done to sanitize HTML)
        # 4. Convert the HTML to PDF, pulling in images where needed
        # 5. Save the PDF to the specified filename.
        request_text = get_page_with_retry(pdf_url, return_text=True)
        doc = readability.Document(request_text)
        title = doc.title()
        raw_html = doc.summary(html_partial=True)

        h2t = html2text.HTML2Text()
        h2t.wrap_links = False
        text = h2t.handle(raw_html)

        # Add the title back to the document
        article = "# {title}\n\n{text}".format(title=title, text=text)

        # Convert to html, fixing relative image urls.
        md = markdown.Markdown()
        md.treeprocessors.register(ImgProcessor(pdf_url), "img", 10)
        html_article = md.convert(article)

        if self.debug:
            with open("./paper.html", "w") as fp:
                fp.write(html_article)

        font_config = weasyprint.fonts.FontConfiguration()
        html = weasyprint.HTML(string=html_article, url_fetcher=url_fetcher)
        css = weasyprint.CSS(string=CSS, font_config=font_config)

        html.write_pdf(filename, stylesheets=[css], font_config=font_config) 
Example 21
Project: html2pdf-server   Author: spoqa   File: html2pdfd.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def render_to_jpeg(html: HTML, buffer: io.BytesIO):
    png_buffer = io.BytesIO()
    html.write_png(png_buffer)
    png_buffer.seek(0)
    with Image(file=png_buffer) as image:
        image.background_color = Color('#fff')
        image.alpha_channel = 'remove'
        image.format = 'jpeg'
        image.save(file=buffer) 
Example 22
Project: html2pdf-server   Author: spoqa   File: html2pdfd.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(
        description='HTTP server that renders HTML to PDF'
    )
    parser.add_argument('--host', '-H',
                        default='0.0.0.0', help='host to listen [%(default)s]')
    parser.add_argument('--port', '-p',
                        type=int, default=8080,
                        help='port to listen [%(default)s]')
    parser.add_argument('--pong-path',
                        help='pong path to respond to to ping (e.g. /pong/)')
    parser.add_argument('--debug', '-d',
                        action='store_true', help='debug mode')
    args = parser.parse_args()
    pong_path = args.pong_path
    if pong_path is None:
        wsgi_app = app
    else:
        if not pong_path.startswith('/'):
            parser.error('--pong-path value must start with a slash (/)')
            return

        @Request.application
        def wsgi_app(request: Request):
            if request.path == pong_path:
                return Response('true', mimetype='application/json')
            return app
    if args.debug:
        run_simple(args.host, args.port, wsgi_app,
                   use_debugger=True, use_reloader=True)
    else:
        logging.basicConfig(level=logging.INFO, format='%(message)s')
        for logger_name in 'html2pdfd', 'aiohttp', 'aiohttp_wsgi':
            logging.getLogger(logger_name).setLevel(logging.INFO)
        wsgi_handler = WSGIHandler(wsgi_app)
        aio_app = Application()
        aio_app.router.add_route('*', '/{path_info:.*}', wsgi_handler)
        logging.getLogger('html2pdfd').info('Serving on http://%s:%d',
                                            args.host, args.port)
        run_app(aio_app, host=args.host, port=args.port) 
Example 23
Project: docker-weasyprint   Author: aquavitae   File: wsgi.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate():
    name = request.args.get('filename', 'unnamed.pdf')
    app.logger.info('POST  /pdf?filename=%s' % name)
    html = HTML(string=request.data)
    pdf = html.write_pdf()
    response = make_response(pdf)
    response.headers['Content-Type'] = 'application/pdf'
    response.headers['Content-Disposition'] = 'inline;filename=%s' % name
    app.logger.info(' ==> POST  /pdf?filename=%s  ok' % name)
    return response 
Example 24
Project: docker-weasyprint   Author: aquavitae   File: wsgi.py    License: GNU General Public License v3.0 5 votes vote down vote up
def multiple():
    name = request.args.get('filename', 'unnamed.pdf')
    app.logger.info('POST  /multiple?filename=%s' % name)
    htmls = json.loads(request.data.decode('utf-8'))
    documents = [HTML(string=html).render() for html in htmls]
    pdf = documents[0].copy([page for doc in documents for page in doc.pages]).write_pdf()
    response = make_response(pdf)
    response.headers['Content-Type'] = 'application/pdf'
    response.headers['Content-Disposition'] = 'inline;filename=%s' % name
    app.logger.info(' ==> POST  /multiple?filename=%s  ok' % name)
    return response 
Example 25
Project: jorvik   Author: CroceRossaItaliana   File: files.py    License: GNU General Public License v3.0 5 votes vote down vote up
def genera_e_salva_con_python(self, nome='File.pdf', scadenza=None, corpo={},
        modello='pdf_vuoto.html', posizione='allegati/', **kwargs):

        scadenza = scadenza or domani()
        corpo.update({"timestamp": datetime.now()})

        html_string = render_to_string(modello, corpo).encode('utf-8')
        html = HTML(string=html_string)
        result = html.write_pdf()

        self.salva(posizione, nome, result, scadenza) 
Example 26
Project: openwisp-radius   Author: openwisp   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_pdf(radbatch_uuid):
    template = get_template(app_settings.BATCH_PDF_TEMPLATE)
    data = load_model('RadiusBatch').objects.get(pk=radbatch_uuid)
    html = HTML(string=template.render({'users': data.user_credentials}))
    buffer = BytesIO()
    html.write_pdf(target=buffer)
    pdf = buffer.getvalue()
    buffer.close()
    return pdf 
Example 27
Project: king-phisher-plugins   Author: rsmusllp   File: __init__.py    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def process_attachment_file(self, input_path, output_path, target=None):
		output_path, _ = os.path.splitext(output_path)
		output_path += '.pdf'
		try:
			with codecs.open(input_path, 'r', encoding='utf-8') as file_:
				msg_template = file_.read()
		except UnicodeDecodeError as error:
			gui_utilities.show_dialog_error(
				'PDF Build Error',
				self.application.get_active_window(),
				"HTML template not in UTF-8 format.\n\n{error}".format(error=error)
			)
			return

		try:
			formatted_message = mailer.render_message_template(msg_template, self.application.config, target)
		except jinja2.exceptions.TemplateSyntaxError as error:
			gui_utilities.show_dialog_error(
				'PDF Build Error',
				self.application.get_active_window(),
				"Template syntax error: {error.message} on line {error.lineno}.".format(error=error)
			)
			return
		except jinja2.exceptions.UndefinedError as error:
			gui_utilities.show_dialog_error(
				'PDF Build Error',
				self.application.get_active_window(),
				"Template undefined error: {error.message}.".format(error=error)
			)
			return
		except TypeError as error:
			gui_utilities.show_dialog_error(
				'PDF Build Error',
				self.application.get_active_window(),
				"Template type error: {0}.".format(error.args[0])
			)
			return

		css_style = self.config.get('css_stylesheet')
		if css_style:
			css_style = css_style.strip()
			if not (os.path.isfile(css_style) and os.access(css_style, os.R_OK)):
				self.logger.warning('invalid css file path: ' + css_style)
				css_style = None

		weasyprint_html = HTML(string=formatted_message, base_url=os.path.dirname(input_path))
		weasyprint_html.write_pdf(
			output_path,
			stylesheets=[css_style] if css_style else None,
			presentational_hints=True
		)
		return output_path 
Example 28
Project: Django-2-by-Example   Author: PacktPublishing   File: views.py    License: MIT License 4 votes vote down vote up
def payment_process(request):
    order_id = request.session.get('order_id')
    order = get_object_or_404(Order, id=order_id)

    if request.method == 'POST':
        # retrieve nonce
        nonce = request.POST.get('payment_method_nonce', None)
        # create and submit transaction
        result = braintree.Transaction.sale({
            'amount': '{:.2f}'.format(order.get_total_cost()),
            'payment_method_nonce': nonce,
            'options': {
                'submit_for_settlement': True
            }
        })
        if result.is_success:
            # mark the order as paid
            order.paid = True
            # store the unique transaction id
            order.braintree_id = result.transaction.id
            order.save()

            # create invoice e-mail
            subject = 'My Shop - Invoice no. {}'.format(order.id)
            message = 'Please, find attached the invoice for your recent purchase.'
            email = EmailMessage(subject,
                                 message,
                                 'admin@myshop.com',
                                 [order.email])

            # generate PDF
            html = render_to_string('orders/order/pdf.html', {'order': order})
            out = BytesIO()
            stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]
            weasyprint.HTML(string=html).write_pdf(out,
                                                   stylesheets=stylesheets)
            # attach PDF file
            email.attach('order_{}.pdf'.format(order.id),
                         out.getvalue(),
                         'application/pdf')
            # send e-mail
            email.send()

            return redirect('payment:done')
        else:
            return redirect('payment:canceled')
    else:
        # generate token 
        client_token = braintree.ClientToken.generate()
        return render(request, 
                      'payment/process.html', 
                      {'order': order,
                       'client_token': client_token}) 
Example 29
Project: Django-2-by-Example   Author: PacktPublishing   File: views.py    License: MIT License 4 votes vote down vote up
def payment_process(request):
    order_id = request.session.get('order_id')
    order = get_object_or_404(Order, id=order_id)

    if request.method == 'POST':
        # retrieve nonce
        nonce = request.POST.get('payment_method_nonce', None)
        # create and submit transaction
        result = braintree.Transaction.sale({
            'amount': '{:.2f}'.format(order.get_total_cost()),
            'payment_method_nonce': nonce,
            'options': {
                'submit_for_settlement': True
            }
        })
        if result.is_success:
            # mark the order as paid
            order.paid = True
            # store the unique transaction id
            order.braintree_id = result.transaction.id
            order.save()

            # create invoice e-mail
            subject = 'My Shop - Invoice no. {}'.format(order.id)
            message = 'Please, find attached the invoice for your recent purchase.'
            email = EmailMessage(subject,
                                 message,
                                 'admin@myshop.com',
                                 [order.email])

            # generate PDF
            html = render_to_string('orders/order/pdf.html', {'order': order})
            out = BytesIO()
            stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]
            weasyprint.HTML(string=html).write_pdf(out,
                                                   stylesheets=stylesheets)
            # attach PDF file
            email.attach('order_{}.pdf'.format(order.id),
                         out.getvalue(),
                         'application/pdf')
            # send e-mail
            email.send()

            return redirect('payment:done')
        else:
            return redirect('payment:canceled')
    else:
        # generate token 
        client_token = braintree.ClientToken.generate()
        return render(request, 
                      'payment/process.html', 
                      {'order': order,
                       'client_token': client_token}) 
Example 30
Project: troupon   Author: andela   File: views.py    License: MIT License 4 votes vote down vote up
def get(self, request, *args, **kwargs):
        """
        Handles get request to the 'download_ticket' named route

        Returns:
            A PDF response containing the ticket
        """
        user = request.user
        deal_id = kwargs['deal_id']
        deal = Deal.objects.get(pk=deal_id)
        quantity = int(request.GET.get('qty'))
        price = quantity * deal.price
        qr_img, unique_id = self.generate_unique_code(deal, user)
        logo_url = deal.advertiser.logo_image_url()

        # add ticket to database
        ticket = Ticket(
            user=user, item=deal, quantity=quantity,
            advertiser=deal.advertiser, ticket_id=unique_id
        )
        ticket.save()

        context = {
            'deal': deal,
            'logo_url': logo_url,
            'qr_img': qr_img,
            'issue_date': ticket.date_created,
            'quantity': quantity,
            'price': price,
            'user': user
        }
        html_template = get_template('tickets/ticket.html')
        rendered_html = html_template.render(
            RequestContext(request, context)).encode(encoding="UTF-8")
        styles = [
            CSS(string='.well-print { background-color: grey !important }'),
            CSS(
                settings.STATIC_ROOT + '/bootstrap/dist/css/bootstrap.min.css'
            ),
            CSS(settings.STATIC_ROOT + '/css/base_styles.css'),
        ]
        pdf_file = HTML(
            string=rendered_html,
            base_url=request.build_absolute_uri()
        ).write_pdf(stylesheets=styles)

        http_response = HttpResponse(pdf_file, content_type='application/pdf')
        http_response['Content-Disposition'] = ('attachment; '
                                                'filename=%s') % deal.slug
        return http_response