Beispiel #1
1
    def print_certidao(self, request, diligencias):
        """
        :param diligencias:
        :return:
        """
        from weasyprint import HTML, CSS
        from django.conf import settings
        from app.models import Diligencia
        from django.utils import datetime_safe


        modelo_html = ''
        for i in range(len(diligencias)):
            if i == 0:                                          #primeira certidão # '<meta charset="utf-8" />'
                modelo_html += '<html>' \
                               '<head>' \
                               '<meta charset="utf-8" />' \
                               '<base href="http://ofjusapp.pythonanywhere.com/">'\
                               '</head>' \
                               '<body>' \
                               '<div style="float: none;">' \
                               '<div>'
                modelo_html += diligencias[i].documento
                modelo_html += '</div>'
            else:                                               #certidões intermediarias
                modelo_html += '<div style="page-break-before:always;">'
                modelo_html += diligencias[i].documento
                modelo_html += '</div>'
        modelo_html += '</div></body></html>'
        pdf_html = HTML(string=modelo_html)
        main_doc = pdf_html.render()
        pdf_file = main_doc.write_pdf()
        diligencias.update(imprimir=False)
        #pdf_file = HTML('http://weasyprint.org/').write_pdf('/tmp/weasyprint-website.pdf')
        return pdf_file  # returns the response.
Beispiel #2
0
def download_pdf(story, output='', message=True):
    """ Download a story to pdf.
    :type message: bool
    """
    if output == '':
        output = _get_download_name(story)
    output = _add_extension(output, 'pdf')
    if message:
        print 'Downloading \'%s\' to %s...' % (story.title, output)
    html = ''
    for chapter in story.get_chapters():
        if message:
            print 'Adding %s...' % (chapter.title)
        html += '<h2>Chapter %d: %s</h2>' % (chapter.number, chapter.title)
        html += chapter.raw_text
        html += '</br>' * 10
    if message:
        print 'Compiling PDF...'

    # This turned out not to work on the command line as it needed an X interface.
    #pdfkit.from_string(html, output)
    # Instead trying with weasyprint
    content = unicode(html.strip(codecs.BOM_UTF8), 'utf-8')
    h = HTML(content)
    h.write_pdf(output)
   def savePDF(self, pdf_filename, parent_soup, target_node, yes_phrase, url, key, school_name):
       if target_node:
          grandparent_node = target_node.parent.parent
          tag = self.highlightedNode(target_node, yes_phrase, parent_soup)
          self.replaceNode(target_node, tag)
          body = Tag(parent_soup,"body")
          body.append(grandparent_node)
       else:
          body = parent_soup
       try:
          weasyprint = HTML(string=body.prettify())
          tmp_filename = 'pdfs/tmp.pdf'
          weasyprint.write_pdf(tmp_filename,stylesheets=[CSS(string='body { font-size: 10px; font-family: serif !important }')])
       except:
          print "weasyprint failed on url: "+url
          if target_node:
             self.replaceNode(tag, target_node) #return to old state
          return

       if target_node:
          self.replaceNode(tag, target_node) #return to old state

       sep_filename = "pdfs/sep.pdf"
       self.makeSepPage(sep_filename, url, key, school_name)

       merger = PdfFileMerger()
       if (os.path.exists(pdf_filename)):
           merger.append(PdfFileReader(file(pdf_filename, 'rb')))
       merger.append(PdfFileReader(file(sep_filename, 'rb')))
       merger.append(PdfFileReader(file(tmp_filename, 'rb')))
       merger.write(pdf_filename)
Beispiel #4
0
def pdf_print(request, requisition_id):
    """Exports the requisition in PDF."""
    # Selecting the requisition
    requisition = get_object_or_404(models.Requisition, pk=requisition_id)

    rendered = render_to_response('purchase/requisition_report.html', {
        'vessel': Vessel.objects.latest('id'),
        'title': _("Requisition"),
        'user': request.user,
        'requisition': requisition,
        'today': datetime.date.today(),
        },
        context_instance=RequestContext(request))

    # Creating the response
    filename = "pharmaship_requisition_{0}.pdf".format(requisition.reference)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="{0}"'.format(filename)

    # Converting it into PDF
    html = HTML(string=rendered.content,
                base_url=request.build_absolute_uri()
                )
    html.write_pdf(response,
                   stylesheets=[
                       CSS(settings.BASE_DIR + '/purchase/static/css/purchase/report.css')
                       ])
    return response
Beispiel #5
0
 def render_pdf(self):
     total = self.doc['total']
     if self.home_country:
         invoice_country_iso = self.doc['address']['country_iso_alpha2']
         if invoice_country_iso and invoice_country_iso != self.home_country:  # no tax in bill
             total = self.doc['amount']
             self.doc['total'] = total
     tpl = self.jinja_env.get_template('invoice_tpl.html')
     self.invoice_fname = "{date}_CHF{total:.2f}_Nr{nr}_hosting-{name}_ta".format(
         date=self.doc['date'].strftime("%Y-%m-%d"),
         total=total,
         nr=self.doc['nr'],
         name=self.client_name_normalized()
     )
     for file_format in ['html', 'pdf']:
         path = "%s/%s" % (self.output_dir, file_format)
         if not os.path.exists(path):
             os.mkdir(path)
     with codecs.open(
         '%s/html/%s.html' % (self.output_dir, self.invoice_fname),
         'w+', encoding="utf-8"
     ) as invoice_html:
         invoice_html.write(tpl.render(**self.doc))
         invoice_html.seek(0)
         base_url = "%s/html" % self.invoice_template_dir
         html = HTML(invoice_html, base_url=base_url)
         html.write_pdf('%s/pdf/%s.pdf' % (self.output_dir, self.invoice_fname))
Beispiel #6
0
def export_schedule_to_pdf(request, callgroup):
	from weasyprint import HTML
	context = get_context(request)

	context['site'] = callgroup.description
	month, year = int(request.GET.get('month', 1)), int(request.GET.get('year', 9999))
	weekstart = int(request.GET.get('weekstart', 0))
	monthstart = datetime.date(year, month, day=1)
	context['month'] = monthstart.strftime("%B %Y")
	monthstart = monthstart - datetime.timedelta(days=monthstart.day - 1)
	# make sure we start on a sunday (or monday if weekstart=1)
	monthstart = monthstart - datetime.timedelta(days=(monthstart.isoweekday() % 7)) + \
		datetime.timedelta(weekstart)
	user = request.session['MHL_Users']['MHLUser']
	context['weeks'] = generateOnCallList(callgroup, monthstart, weekstart, user)
	context['days'] = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
	for _ in range(weekstart):
		context['days'].append(context['days'].pop(0))
	# load template with context and static root for pdf renderer, generate pdf buffer
	static_root = settings.STATICFILES_DIRS[0]
	html = render_to_string('pdf_schedule.html', {'STATIC_ROOT': static_root}, context)
	weasyhtml = HTML(string=html)
	schedcss = join(static_root, 'css', 'pdf_schedule.css')
	pdf = weasyhtml.write_pdf(stylesheets=[schedcss])  # ,target='/tmp/test.pdf') 
	# prepare response, append &nopdf to GET url for test
	response = HttpResponse(pdf, mimetype="application/pdf")
	response["Cache-Control"] = "no-cache"
	response["Accept-Ranges"] = "none"
	response["Content-Disposition"] = "attachment; filename=schedule-%d-%d.pdf" % (year, month)
	return response if 'nopdf' not in request.GET else \
		render_to_response("pdf_schedule.html", context)
Beispiel #7
0
 def make_book(self, filename, config):
     #QtGui.QMessageBox.critical(None, "Network Error","make_book")
     with tempfile.TemporaryDirectory(prefix="pySpellbook-") as tempdir:
         temphtml = tempfile.NamedTemporaryFile(dir=tempdir, delete=False, suffix=".html", mode="w")
         temphtml.write(self.rendered)
         #QtGui.QMessageBox.critical(None, "Network Error","wrote html")
         tmpname = temphtml.name
         temphtml.close()
         #QtGui.QMessageBox.critical(None, "Network Error",tmpname)
         #os.mkdir(os.path.join(tempdir, "resources"))
         #for r in self.resourcelist:
         #    shutil.copy(r, os.path.join(tempdir,"resources"))
         if config['backend'] == 'prince':
             os.system("\"%s\" %s -o %s" % (config['prince_path'], tmpname, filename))
         elif config['backend'] == 'HTML':
             shutil.copy(os.path.join(tempdir, tmpname), filename)
             webbrowser.open_new_tab("file:///%s" % filename)
         elif config['backend'] == 'custom':
             custom_command = config['custom'].replace("$INPUT", temphtml).replace("$OUTPUT", filename)
             shutil.copy(custom_command)
         else:
             if weasy:
                 html = HTML("file://%s" % tmpname)
                 html.write_pdf(target=filename)
             else:
                 import pySpellbook.qtpdf
                 os.chdir(tempdir)
                 printer = pySpellbook.qtpdf.Printer(self.parent)
                 printer.load(tmpname)
                 printer.print(filename)
Beispiel #8
0
def md2pdf(pdf_file_path, md_content=None, md_file_path=None,
           css_file_path=None, base_url=None):
    """
    Convert markdown file to pdf with styles
    """

    # Convert markdown to html
    raw_html = ""
    extras = ["cuddled-lists"]
    if md_file_path:
        raw_html = markdown_path(md_file_path, extras=extras)
    elif md_content:
        raw_html = markdown(md_content, extras=extras)

    if not len(raw_html):
        raise ValidationError('Input markdown seems empty')

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

    # 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
Beispiel #9
0
 def render(test_id):
     document = HTML(safe_join(suite_directory, test_id + ".htm"), encoding="utf8").render(
         stylesheets=[default_stylesheet], enable_hinting=True
     )
     pages = [
         "data:image/png;base64," + document.copy([page]).write_png().encode("base64").replace("\n", "")
         for page in document.pages
     ]
     return render_template("render.html", **locals())
Beispiel #10
0
 def render(test_id):
     document = HTML(
         safe_join(suite_directory, test_id + '.htm'),
         encoding='utf8',
     ).render(stylesheets=[default_stylesheet], enable_hinting=True)
     pages = [
         'data:image/png;base64,' + document.copy([page]).write_png(
             )[0].encode('base64').replace('\n', '')
         for page in document.pages]
     return render_template('render.html', **locals())
Beispiel #11
0
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
Beispiel #12
0
 def get_data():
     if 'wsgi.input' in environ and request_body_size:
         request = environ['wsgi.input'].read(request_body_size)
         content = parse_qs(request.decode('utf-8'))['content'][0]
     else:
         content = DEFAULT_CONTENT
     html = HTML(string=content)
     png = BytesIO()
     html.write_png(png)
     png.seek(0)
     return content, b64encode(png.read()).decode('ascii')
Beispiel #13
0
 def generate_pdf(self):
     ''' renders html from file with given context and creates pdf file from it
     '''
     html_string = Template(self.template.template.read()).render(Context(json.loads(self.content)))
     html = HTML(string=html_string, base_url='')
     filename = self.name.replace('/', '.') + '.pdf'
     buffer = BytesIO()
     html.write_pdf(target=buffer)
     pdf = buffer.getvalue()
     buffer.close()
     self.file.save(filename, ContentFile(pdf))
Beispiel #14
0
def make_pdf(config, data):
    """
    Generate PDF file out of generated 'index.html' page.
    """
    from weasyprint import HTML
    output_dir = config.get('output_dir', 'build')
    output_file = os.path.join(output_dir, config.get('pdf_file', 'resume.pdf'))
    input_file = os.path.join(output_dir, 'index.html')
    theme_location = os.path.join('themes', config['theme'])
    html = HTML(input_file, base_url=theme_location)
    html.write_pdf(output_file)
Beispiel #15
0
def print_order(orders, name, phone):
    template = env.get_template('template.md')

    total = sum(order.price for order in orders)
    md = template.render(name=name, phone=phone, orders=orders, total=total)
    html = markdown.markdown(md, extensions=['markdown.extensions.tables'])
    document = HTML(string=html)

    tmp = tempfile.NamedTemporaryFile(mode='wb', suffix='.pdf')
    document.write_pdf(tmp, stylesheets=[CSS(filename='order-style.css')])

    return tmp
Beispiel #16
0
def render_to_pdf(template_name, pdf_filename=None, template_values=None, css_sheets=None):
    context_extras = {'LANGUAGES': settings.LANGUAGES, 'LANGUAGE_CODE': translation.get_language(),
                      'LANGUAGE_BIDI': translation.get_language_bidi()}
    template_values.update(context_extras)
    html_content = render_to_string(template_name, template_values or {})
    css_objs = [CSS(filename=finders.find(x)) for x in css_sheets] if css_sheets else []
    html_obj = HTML(string=html_content)
    if pdf_filename is None:
        with tempfile.NamedTemporaryFile() as n:
            pdf_filename = n.name

    html_obj.write_pdf(pdf_filename, stylesheets=css_objs)
    return pdf_filename
Beispiel #17
0
def createPdf(htmlreport, outfile=None, css=None, images={}):
    """create a PDF from some HTML.
    htmlreport: rendered html
    outfile: pdf filename; if supplied, caller is responsible for creating
             and removing it.
    css: remote URL of css file to download
    images: A dictionary containing possible URLs (keys) and local filenames
            (values) with which they may to be replaced during rendering.
    # WeasyPrint will attempt to retrieve images directly from the URL
    # referenced in the HTML report, which may refer back to a single-threaded
    # (and currently occupied) zeoclient, hanging it.  All image source
    # URL's referenced in htmlreport should be local files.
    """
    # A list of files that should be removed after PDF is written
    cleanup = []
    css_def = ''
    if css:
        if css.startswith("http://") or css.startswith("https://"):
            # Download css file in temp dir
            u = urllib2.urlopen(css)
            _cssfile = tempfile.mktemp(suffix='.css')
            localFile = open(_cssfile, 'w')
            localFile.write(u.read())
            localFile.close()
            cleanup.append(_cssfile)
        else:
            _cssfile = css
        cssfile = open(_cssfile, 'r')
        css_def = cssfile.read()

    htmlreport = to_utf8(htmlreport)

    for (key, val) in images.items():
        htmlreport = htmlreport.replace(key, val)

    # render
    htmlreport = to_utf8(htmlreport)
    renderer = HTML(string=htmlreport, encoding='utf-8')
    pdf_fn = outfile if outfile else tempfile.mktemp(suffix=".pdf")
    if css:
        renderer.write_pdf(pdf_fn, stylesheets=[CSS(string=css_def)])
    else:
        renderer.write_pdf(pdf_fn)
    # return file data
    pdf_data = open(pdf_fn, "rb").read()
    if outfile is None:
        os.remove(pdf_fn)
    for fn in cleanup:
        os.remove(fn)
    return pdf_data
Beispiel #18
0
    def save(self):
        # PDF report is a list of all documents
        self.summary = '<h1>%s</h1>' % (self.locale['STR_SUMMARY'])

        # To make one PDF report, we have to get all pages of all documents...
        # First step , we obtain a list of sublists like this :
        # [
        #     [doc1.page1, doc1, page2],
        #     [doc2.page1, doc2.page2],
        #     [doc3.page1, doc3.page2, doc3.page3]
        # ]

        # Rendering content
        content = HTML(string=self.content, encoding="utf-8").render(stylesheets=[self.content_css])

        #Priting summary table BEGIN
        self.summary += '<table style="border:0">'

        def _printSummary(bookmarks, indent=0, numer=''):
            for i, (label, (page, _, _), children) in enumerate(bookmarks, 1):
                tr_style = 'style="border-top:1px solid #CCC;border-bottom:1px solid #CCC"'
                title_td_style = 'style="border:0;text-align:left;width:550px;padding:10px;"'
                page_num_td_style = 'style="border:0;width:50px"'
                if indent == 0 and i == 1:
                    tr_style = 'style="border-bottom:1px solid #CCC"'
                self.summary += ('<tr %s><td %s>%s%s. %s</td><td %s>%d</td></tr>' % (
                    tr_style, title_td_style, '&nbsp;' * indent, numer + str(i), label.lstrip('0123456789. '), page_num_td_style, page + 1))
                _printSummary(children, indent + 2, numer + str(i) + '.')
        _printSummary(content.make_bookmark_tree())

        #Priting summary table END
        self.summary += '</table>'

        homepage = HTML(string=self.homepage, encoding="utf-8").render(stylesheets=[self.homepage_css])
        summary = HTML(string=self.summary, encoding="utf-8").render(stylesheets=[self.homepage_css])

        pdf_report = [homepage, summary, content]
        logging.getLogger().warning(pdf_report[2].make_bookmark_tree())

        all_pages = [doc.pages for doc in pdf_report]

        # Second step, clean sublist and make a simple list
        # http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
        all_pages = [item for sublist in all_pages for item in sublist]

        # ...And combine these pages into a single report Document
        pdf_report[0].copy(all_pages).write_pdf(self.path)

        chmod(self.path, 0644)
        return self.path
Beispiel #19
0
    def __call__(self, REQUEST, RESPONSE):
        content = super(ExportaMinutaPDFView, self).__call__(self)
        portal_url = api.portal.get().absolute_url()
        base_url = '{0}/++resource++smdu.participacao/'.format(portal_url)
        html = HTML(string=content, base_url=base_url)
        stylesheets = []
        with open('src/smdu/participacao/browser/static/css/print.css', 'r') as css:
            stylesheets.append(CSS(string=css.read()))
        minuta_exportada_pdf = html.write_pdf(stylesheets=stylesheets)

        RESPONSE.setHeader('Content-Type', 'application/pdf; charset=utf-8')
        RESPONSE.setHeader('Content-Length', len(minuta_exportada_pdf))
        RESPONSE.setHeader('Content-Disposition', 'attachment; filename="Relatorio.pdf"')
        return minuta_exportada_pdf
Beispiel #20
0
 def form_valid(self, form):
     self.post_data = self.request.POST
     if 'download' in self.post_data:
         html = self.render_to_response(self.get_context_data(form=form))
         f = open(os.path.join(
             os.path.dirname(__file__), './static/payslip/css/payslip.css'))
         html = HTML(string=html.render().content)
         pdf = html.write_pdf(stylesheets=[CSS(string=f.read())])
         f.close()
         resp = HttpResponse(pdf, content_type='application/pdf')
         resp['Content-Disposition'] = \
             u'attachment; filename="{}_{}.pdf"'.format(
                 self.date_start.year, self.date_start.month)
         return resp
     return self.render_to_response(self.get_context_data(form=form))
Beispiel #21
0
    def execute(self, id_user, id_meeting):
        render = RenderHtml(id_user, id_meeting, self.__dirToProject)
        value = render.split_question_on_pages()
        with codecs.open(self.__dir, 'w', 'utf8') as f2:
            f2.write(value)

        pdf = HTML(self.__dir)
        newName = str(id_user) + str(id_meeting) + self.__file_name
        pdf.write_pdf(self.__result_dir + newName)

        res = []
        res.append(newName)
        res.append(self.__result_dir)

        return res
Beispiel #22
0
 def _get_pdf(self, markup):
     logger = logging.getLogger(__name__)
     base_url = self.base_url if self.base_url else ''
     pdf_file = StringIO.StringIO()
     logger.info("Creating weasy")
     weasy = HTML(
         file_obj=StringIO.StringIO(markup.encode("UTF-8")),
         encoding='UTF-8',
         base_url=base_url,
         url_fetcher=self._url_fetcher
     )
     logger.info("Starting pdf generation")
     weasy.write_pdf(pdf_file)
     logger.info("PDF generated, returning")
     return pdf_file.getvalue()
Beispiel #23
0
def render():
    html = request.args['html']
    assert html.strip()

    if html:
        assert 'fuu' not in html
        # Save the input HTML
        with open(INPUT, 'w') as fd:
            fd.write(html.encode('utf-8'))

    html = HTML(INPUT, encoding='utf8')
    html.write_pdf(PDF_OUTPUT)
    html.write_png(PNG_OUTPUT)

    return send_file(PNG_OUTPUT, cache_timeout=0)
Beispiel #24
0
def pdf(obj, path, site_url=None):
    activate(obj.language_code)  # required if called from command line

    # first page
    header_url = urljoin(site_url, reverse('activities:print-preview-header', kwargs={'code': obj.code, }))
    header_html_source = url_read(header_url)
    header = HTML(string=header_html_source, base_url=site_url).render()

    # other pages
    content_url = urljoin(site_url, reverse('activities:print-preview-content', kwargs={'code': obj.code, }))
    content_html_source = url_read(content_url)
    content = HTML(string=content_html_source, base_url=site_url).render()

    header.pages += content.pages

    header.write_pdf(path)
Beispiel #25
0
    def execute(self, id_user, id_meeting, css=None, qs=None):
        render = RenderHtml(id_user, id_meeting, self.__dirToProject, css=css, qs=qs)

        value = render.render_doc()

        with codecs.open(self.__dir, 'w', 'utf8') as file:
            file.write(value)

        pdf = HTML(self.__dir)
        newName = str(id_user) + str(id_meeting) + self.__file_name
        pdf.write_pdf(self.__result_dir + newName)

        res = []
        res.append(newName)
        res.append(self.__result_dir)

        return res
Beispiel #26
0
def main():
    submissions = {}
    submissions_path = get_submissions_path(app.root_path)
    for submission_pkl in sorted(glob.glob(os.path.join(submissions_path, '*.pkl'))):
        with open(submission_pkl, 'rb') as submission_file:
            submission = cPickle.loads(submission_file.read())
            submissions[submission['student_email']] = submission
        os.unlink(submission_pkl)

    for s in submissions.values():
        weasy = HTML(string=s['receipt'])
        pdf_path = os.path.join(submissions_path, s['student_name'] + ".pdf")
        weasy.write_pdf(pdf_path)
        response = send_welcome_mail(s, pdf_path)
        print "Response " + str(response.status_code) + " for " + s['student_name'] + " - ",
        print response.json()
        os.unlink(pdf_path)
   def savePDFURL(self, pdf_filename, soup, url, keys, school_name):
       try:
          weasyprint = HTML(string=soup.prettify())
          tmp_filename = 'pdfs/tmp.pdf'
          weasyprint.write_pdf(tmp_filename,stylesheets=[CSS(string='body { font-size: 10px; font-family: serif !important }')])
       except:
          print "weasyprint failed on url: "+url
          return

       sep_filename = "pdfs/sep.pdf"
       self.makeSepPageURL(sep_filename, url, keys, school_name)

       merger = PdfFileMerger()
       if (os.path.exists(pdf_filename)):
           merger.append(PdfFileReader(file(pdf_filename, 'rb')))
       merger.append(PdfFileReader(file(sep_filename, 'rb')))
       merger.append(PdfFileReader(file(tmp_filename, 'rb')))
       merger.write(pdf_filename)
Beispiel #28
0
def md2pdf(pdf_file_path, md_content=None, md_file_path=None,
           css_file_path=None, base_url=None):
    """
    Converts input markdown to styled HTML and renders it to a PDF file.

    Args:
        pdf_file_path: output PDF file path.
        md_content: input markdown raw string content.
        md_file_path: input markdown file path.
        css_file_path: input styles path (CSS).
        base_url: absolute base path for markdown linked content (as images).

    Returns:
        None

    Raises:
        ValidationError: if md_content and md_file_path are empty.
    """

    # Convert markdown to html
    raw_html = ''
    extras = ['cuddled-lists', 'tables']
    if md_file_path:
        raw_html = markdown_path(md_file_path, extras=extras)
    elif md_content:
        raw_html = markdown(md_content, extras=extras)

    if not len(raw_html):
        raise ValidationError('Input markdown seems empty')

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

    # 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
Beispiel #29
0
def create_pdf(username, totals):
    """Test out functionality."""
    html = HTML(string='<body width="600px"><div class="top"><br /><br /><h4>SPRY Report</h4><p>Data about <b>{}</b></p></div>\
        <div><img class="insta" src="./{}.jpg"/></div\
        <div>Total accounts found: {}</div></body>'.format(username, username, totals))
    css = CSS(string='''
    .top { text-align: center; border-bottom: 2px dashed deepskyblue; padding: 5px; }
    p { font-family: mono; font-size: 12px; }
    h2,h3,h4 { font-family: "Andale Mono"; font-size: 14px; }
    ul,li { font-family: "Andale Mono"; font-size: 11px; letter-spacing: 0.08em; }
    ul { list-style: none; }
    ul { width: 500px; margin-bottom: 20px; border-top: 1px solid #ccc; }
    li { border-bottom: 1px solid #ccc; float: left; display: inline;}
    #double li { width:50%;}
    #triple li { width:33.333%; }
    #six li { width:16.666%; }
    #quad li { width:25%; }
    ''')
    html.write_pdf(
        '{}-report.pdf'.format(username), stylesheets=[css])
Beispiel #30
0
    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
Beispiel #31
0
page = 'https://www.w3schools.com/python/python_intro.asp'

# create empty lists to hold scraped pages and actual pages of the pdf document
# to be printed out

documents = []

# loop through each page of the tutorial calling the already declared functions
# on them
while True:
    parent = get_page(page)
    get_next_page(parent)
    html = remove_unwanted(parent)

    # create an html instance
    html_instance = HTML(string=html)

    # call weasyprint's render method on the html instance to obtain in
    # return an instance of the Document class which is stored in the doc object
    doc = html_instance.render()

    # append every consecutive doc object to the documents list
    # that was created earlier.
    documents.append(doc)

    # print the url of the current page to the console, this is solely
    # for debugging and has no effect on the script
    print(page)

    # let the loop sleep for about 3secs before sending another request to
    # to the server, this helps to prevent overloading the server from our end
Beispiel #32
0
def writeReport(client, cryptoCurrency, initialInvestemnt, startTime):
    from datetime import datetime
    from weasyprint import HTML
    import pandas as pd
    import time

    # How many CRY are in the balance
    for currency in client.get_balance()["data"]:
        if currency["wallet"] == cryptoCurrency:
            CRY_available = float(currency["balance"])
            break

    # How much time has it been running
    seconds = time.time() - startTime
    days = int(seconds // (24 * 3600))
    seconds %= (24 * 3600)
    hours = int(seconds // 3600)
    seconds %= 3600
    minutes = int(seconds // 60)
    seconds %= 60

    # Today's date
    today = datetime.now().strftime("%A, %d %B %Y")

    records = pd.read_csv('./reports/records.csv')

    # Record Summary
    onlyCRY = int(CRY_available * float(
        client.get_ticker(market=cryptoCurrency + 'CLP')[0]["last_price"]))
    onlyCLP = int(float(client.get_balance()[3]["balance"]))
    onlySales = int(sum(records.loc[records["Side"] == "sell"]["Total"]))
    onlyPurchases = int(sum(records.loc[records["Side"] == "buy"]["Total"]))
    onlyProfit = onlyCRY + onlyCLP - initialInvestemnt

    # HTML Investment Report

    styleSummary = """
    <style>
      table.summary {width: 75%; margin-left: auto; margin-right: auto; cellpadding="10"; text-align: left; border-collapse: collapse;}
      table.summary td, table.summary th {border: 2px solid #AAAAAA; padding: 6px 6px;}
    </style>
    """
    styleDetail = """
    <style>
      table.dataframe {width: 100%;text-align: left;border-collapse: collapse;}
      table.dataframe td, table.dataframe th {border: 1px solid #AAAAAA;padding: 3px 2px;}
      table.dataframe tbody tr th {text-align: center;}
    </style>
    """

    htmlSummary = """
    <h1 style="text-align: center;">{} Investment Report</h1>
    <p style="text-align: justify;">This report is automatically generated by the Trading Bot using the CryptoMKT API. The following information has been generated after a running time of {} Days, {} Hours, {} Minutes, {} Seconds.</p>
    <p style="text-align: justify;">All the information presented here is dated {}. Therefore, it may be out of date by the time it is read.</p>
    <h2>Trading Summary</h2>
    <table border="1" class="summary">
    <tbody>
    <tr>
    <td>{} assessed in CLP</td>
    <td>{}*</td>
    </tr>
    <tr>
    <td>CLP Balance</td>
    <td>{}</td>
    </tr>
    <tr>
    <td>CLP earned from Sales</td>
    <td>{}</td>
    </tr>
    <tr>
    <td>CLP spent on Purchases</td>
    <td>{}</td>
    </tr>
    <tr>
    <td>Initial Investment</td>
    <td>{}</td>
    </tr>
    <tr>
    <td>Relative Profit Estimate</td>
    <td>{}**</td>
    </tr>
    </tbody>
    </table>
    <p><em>*Its value may vary over time, so this is not a static value.</em></p>
    <p><em>**These are not actual earnings but a profit relative to the value of the {} today.</em></p>
    <h2>Trade Detail</h2>
    """.format(cryptoCurrency, str(days), str(hours), str(minutes),
               str(int(seconds)), today, cryptoCurrency, str(onlyCRY),
               str(onlyCLP), str(onlySales), str(onlyPurchases),
               str(initialInvestemnt), str(onlyProfit), cryptoCurrency)

    records["Total"] = records["Total"].astype(int)
    records["Fees"] = records["Fees"].astype(int)
    htmlDetail = records.to_html().replace('<tr style="text-align: right;">',
                                           '<tr>')

    html = '<html>' + styleSummary + styleDetail + htmlSummary + htmlDetail + '</html>'

    # Write the report in PDF
    HTML(string=html).write_pdf('./reports/report.pdf')
Beispiel #33
0
    def generate(self,
                 documents: List[Document],
                 export_dir: str,
                 filename: str,
                 include_table_of_contents=False,
                 css_file_names: List[str] = None) -> str:
        """
        Merged all documents into one and then exports the merged document to a PDF file in the given directory.

        Allows defining of multiple css files. The base css file will be applied first, followed sequentially
        by files defined in css_file_names.

        The CSS files must be placed in the Settings.document_css_directory directory.
        CSS files placed in Settings.document_css_directory/base will be applied for all exported PDF documents.

        Parameters
        ----------
        documents
            list of documents for which files should be generated
        export_dir
            relative path to the directory (relative to the output root directory) in which the PDF should be saved
        filename
            filename under which the merged document should be saved
        include_table_of_contents
            if True then table of contents will be generated at the beginning of the file
        css_file_names
            names of css files which should be applied for generating the PDF

        Returns
        -------
        the absolute path to the output PDF file that was saved
        """
        css_file_paths = []
        documents = [self._merge_documents(documents, filename)]

        # Find the output directory
        output_dir = self.get_output_dir(export_dir)
        output_filename = os.path.join(output_dir, filename)

        for document in documents:
            if include_table_of_contents:
                self._add_table_of_contents(document)

            # Generate the full document HTML
            self.logger.info("Generating HTML for PDF...")
            html = document.generate_html()

            # Automatically include all the css files in the `document_css/base` directory
            base_css = os.listdir(self._document_css_dir)
            for name in base_css:
                path = os.path.join(self._document_css_dir, name)
                if os.path.isfile(path):
                    css_file_paths.append(CSS(path))

            # If we've set custom css files, add them to the pdf
            if css_file_names is not None:
                for name in css_file_names:
                    css_file_paths.append(
                        CSS(os.path.join(self._document_css_dir,
                                         name + ".css")))

            # Parse the HTML.
            html = HTML(string=html)

            # Write out the PDF.
            self.logger.info("Rendering PDF in {}...".format(output_filename))
            html.write_pdf(output_filename, css_file_paths)

        return output_filename
Beispiel #34
0
import logging
from weasyprint import HTML

logger = logging.getLogger('weasyprint_test')

logger.info('Starting up...')

for i in range(0, 3):
    html = HTML('templates/test.html')
    html.write_pdf(f'templates/output/test{i + 1}.pdf')

logger.info('Success!')
Beispiel #35
0
    def render(self):
        """Generate document.

        thereby summarizing all page content areas

        * if individual pages were specified, generate a hidden h1
        * replace all jinja information {{}} with content from self._variables

        Returns
        -------
        main_doc:
            gerenderte Dokument
        overlay_html: str
             html des gerenderten Overlays
        body_html: str
             html des gerenderten body

        """
        if not self.isRendered:
            self.isRendered = False

        # code für page break
        pageBreak = self.newPage( render=False )

        # alle Page content Bereiche zusammenfassen
        # wenn einzelne Seiten angegeben wurden ein hidden h1 erzeugen
        pagenames = {}
        pagenum = 0
        for pageName in self.pageContent.keys():
            # Die Seitennummern beginnen bei 1
            pagenum += 1
            pagenames[ pagenum ] = pageName

            # pageContent nur beim ersten Funktionsaufruf ändern
            if self.isRendered == False:
                if pageName[0] == "_":
                    h1 = ''
                else:
                    # Versteckter Name für einen Verzeichniseintrag
                    h1 = '<h1 style="visibility: hidden;position:absolute;height:0px">{}</h1>'.format( pageName )

                # Der eigentliche Seiteninhalt
                # der erste Seitenbereich muss mit einer Seite anfangen, deshalb pageBreak
                self.pageContent[ pageName ] = '<div class="pageContent">' + pageBreak + h1 + self.pageContent[pageName] + "</div>"

                # eingefügte autoNumber wieder entfernen
                name = pageName
                cm = name.split(") - ")
                if len(cm) > 1:
                    name = cm[1]

                # Seite einfügen aktuellen contentName setzen und alle variablen ersetzen
                self._variables["contentName"] = name
                self.pageContent[ pageName ] = self._config.render_template( self.pageContent[ pageName ], self._variables, deep_replace=True )

        if self.meta == "":
            # datum aus Datenausgabe verwenden, sonst now()
            try:
                datum = datetime.strptime( self._variables["Datenausgabe"] , "%d.%m.%Y")
            except: # pragma: no cover
                datum = datetime.now()

            self.meta += '<meta name="dcterms.created" content="{}" >'.format( datum.strftime("%Y-%m-%d") )
            self.meta += '<meta name="generator" content="MedPhyDO" >'
            self.meta += '<meta name="keywords" content="{}" >'.format( self._variables["Schlüsselwörter"] )

            # weitere meta möglichkeiten
            #
            '''
            <meta name=author>
            <meta name=description>
            <meta name=dcterms.created>
            <meta name=dcterms.modified>
            <link rel=attachment>
            '''


        # mit pagebreak zusammensetzen pageBreak
        body_html = pageBreak.join( self.pageContent.values() )

        # template zusammensetzten
        main_html = self.template.format(
            title = self.title, meta = self.meta, style = self.style,
            head = self.head, body = body_html
        )

        html = HTML( string=main_html )

        # zusätzliche css file einbinden
        stylesheets = []
        css_file = osp.join(
            self._variables["resources"],
            self._config.get( "pdf.page-style", "mpdf_page.css" )
        )
        # add additional CSS from css_file
        if os.path.isfile(css_file):
            stylesheets.append( CSS(filename=css_file) )

        # css aus PAGE_STYLE zusätzlich verwenden
        style_string = self._config.render_template(self.PAGE_STYLE, self._variables, deep_replace=True )
        stylesheets.append(CSS(string=style_string))

        # html mit stylesheets rendern
        main_doc = html.render(stylesheets=stylesheets)

        attrs = self._variables.copy()
        attrs["pages"] = len(main_doc.pages)

        #
        # Overlays
        #
        overlays = {}
        # style einmal rendern und immer verwenden
        self.OVERLAY_STYLE = self._config.render_template(self.OVERLAY_STYLE, self._variables, deep_replace=True )
        # alle seiten durchgehen und overlays einfügen
        pagenum = 0
        for page in main_doc.pages:

            # Die Seitennummern beginnen bei 1
            pagenum += 1
            # gibt es einen pagename, dann verwenden
            if pagenum in pagenames:
                pagename = pagenames[ pagenum ]
            else:
                pagename = pagenum
            # body der aktuellen Seite bestimmen
            page_body = PdfGenerator.get_element(page._page_box.all_children(), 'body')
            # header und/oder footer element erstellen
            # dabei variables erweitern
            attrs["pagenum"] = pagenum
            overlay, overlay_html = self._page_overlays( attrs )

            overlays[ pagename ] = overlay_html

            # header einfügen
            page_body.children += overlay.all_children()

        self.isRendered = True
        return main_doc, overlay_html, body_html
def reporter_generator(data, scr_status, infos):
    html_out = template.render(data=data, scr_stats=scr_status, infos=infos)
    HTML(string=html_out).write_pdf("report.pdf")
Beispiel #37
0
def render_template(url):
    parts = [
        '''\
<!doctype html>
<meta charset=utf-8>
<title>WeasyPrint Navigator</title>
<style>
  form { position: fixed; z-index: 1; top: 8px; left: 16px; right: 0; }
  nav, input { font: 24px/30px sans-serif }
  input:not([type]) { background: rgba(255, 255, 255, .9); border-width: 2px;
                      border-radius: 6px; padding: 0 3px }
  input:not([type]):focus { outline: none }
  body { margin-top: 0; padding-top: 50px }
  section { box-shadow: 0 0 10px 2px #aaa; margin: 25px;
            position: relative; overflow: hidden; }
  section a { position: absolute; display: block }
  section a[href]:hover, a[href]:focus { outline: 1px dotted }
  nav { margin: 25px }
</style>
<body onload="var u=document.forms[0].url; u.value || u.focus()">
<form action="/" onsubmit="
  window.location.href = '/view/' + this.url.value; return false;">
<input name=url style="width: 80%" placeholder="Enter an URL to start"
  value="'''
    ]
    write = parts.append
    if url:
        html = HTML(url)
        url = html.base_url
        write(url)
    write('" />\n<input type=submit value=Go />\n')
    if url:
        write('<a href="/pdf/')
        write(url)
        write('">PDF</a>\n')
    write('</form>\n')
    if url:
        for width, height, data_url, links, anchors in get_pages(html):
            write('<section style="width: {0}px; height: {1}px">\n'
                  '  <img src="{2}">\n'.format(width, height, data_url))
            for link_type, target, (pos_x, pos_y, width, height) in links:
                href = ('#' + target if link_type == 'internal' else '/view/' +
                        target)
                write('  <a style="left: {0}px; top: {1}px; '
                      'width: {2}px; height: {3}px" href="{4}"></a>\n'.format(
                          pos_x, pos_y, width, height, href))
            for anchor_name, (pos_x, pos_y) in anchors.items():
                # Remove 60px to pos_y so that the real pos is below
                # the address bar.
                write(
                    '  <a style="left: {0}px; top: {1}px;" name="{2}"></a>\n'.
                    format(pos_x, pos_y - 60, anchor_name))
            write('</section>\n')
    else:
        write('''
<nav>
<h2>Examples:</h2>
<ul>
  <li><a href="/view/http://www.webstandards.org/files/acid2/test.html">
      Acid2</a></li>
  <li><a href="/view/http://www.w3.org/Style/CSS/current-work">
      CSS specifications</a></li>
  <li><a href="/view/http://en.wikipedia.org/">
      English Wikipedia</a></li>
</ul>
</nav>
''')
    return ''.join(parts).encode('utf8')
def html2pdf(html, outputfile, stylesheets=None):

    document = HTML(string=html)

    with open(outputfile, 'wb') as f:
        document.write_pdf(f, stylesheets=stylesheets)
Beispiel #39
0
import markdown as md
import codecs
from weasyprint import HTML


def htmlHead(str, styleTag=False):
    if styleTag:
        css_input = 'generic css style'
        outStr = '<html>\n\t<head>\n\t\t<style>' + css_input + '</style>\n\t</head>\n\t<body>' + str + '</body>\n<html>'
    else:
        outStr = '<html>\n\t<body>' + str + '</body>\n<html>'
    return outStr


mdStr = htmlHead('test str here')
fileName = "test.html"
output_file = codecs.open(fileName,
                          "w",
                          encoding="utf-8",
                          errors="xmlcharrefreplace")
output_file.write(mdStr)
HTML(fileName).write_pdf('test.pdf')
Beispiel #40
0
def quote(req, num=None, pdf=False):
    user = req.user
    quote_breadcrumb = Breadcrumb('Quotes', 'eRacks Quote List for %s' % user,
                                  '/quotes/')

    if 0:  # messages_test
        from django.contrib import messages
        #messages.add_message(req, messages.INFO, 'Hello world.')

        #Some shortcut methods provide a standard way to add messages with commonly used tags (which are usually represented as HTML classes for the message):

        messages.debug(req, '%s SQL statements were executed.' % 123)
        messages.info(req, '%s SQL statements were executed.' % 123)
        messages.info(req, 'Three credits remain in your account.')
        messages.success(req, 'Profile details updated.')
        messages.warning(req, 'Your account expires in three days.')
        messages.error(req, 'Document deleted.')

    if num:
        # render it directly

        try:
            q = Quote.objects.get(quote_number=num)
        except Quote.DoesNotExist:
            raise Http404

        if q:
            address1 = Address.objects.filter(customer=q.customer)
        #print address1
        shipping_addr = None
        billing_addr = None
        if address1:
            for address in address1:
                print address.type
                if address.type == "shipping":
                    shipping_addr = address
                if address.type == "billing":
                    billing_addr = address
                if address.type == "both":
                    shipping_addr = address
                    billing_addr = address

        prod = dict(
            address1=address1,
            shipping_addr=shipping_addr,
            billing_addr=billing_addr,
            q=q,
            totprice=q.totprice,
            summary=q.summary,
            notes=q.header_items,  # terms, discounts, etc?
            #qty        = q.totqty,
            qty=1,
            opts={},
            baseprice=q.totprice,
            weight=q.shipping,
            sku='Quote/%s' % q.quote_number,
            order_total=q.totprice + q.shipping)

        if req.POST.get('add', None):  # add quote to cart as product
            prod = dict(
                totprice=q.totprice,
                summary=q.summary,
                notes=q.header_items,  # terms, discounts, etc?
                #qty        =   q.totqty,
                qty=1,
                opts={},
                baseprice=q.totprice,
                weight=q.shipping,
                sku='Quote/%s' % q.quote_number,
                order_total=q.totprice + q.shipping)
            ses = req.session
            ses['cart'] = ses.get('cart', []) + [prod]
            ses['prod'] = {}

            return HttpResponseRedirect('/cart/')

        text = "Your email confirmation, as PDF attachment\n\n"
        html_string = render_to_string('pdf/index.html', context=prod)
        html = HTML(string=html_string, base_url=req.build_absolute_uri())
        pdf = html.write_pdf()
        #return HttpResponse (pdf, content_type='application/pdf')

        msg = EmailMultiAlternatives(
            'Your %s eracks quote #%s' % (settings.HNN[0], q.quote_number),
            text,  # nope: '',  # let's try attaching the text,
            settings.ORDER_FROM_EMAIL,
            ['*****@*****.**'])
        msg.attach('eRacks_Quote_#%s.pdf' % q.quote_number, pdf,
                   "application/pdf")
        # msg.send()

        if req.POST.get('pdf', None):  # Render PDF file & return to user
            response = HttpResponse(content_type='application/pdf')
            response[
                'Content-Disposition'] = 'attachment; filename=eRacks_Quote_#%s.pdf' % q.quote_number
            response.write(pdf)
            return response

        # Drop thru: email admin, render the quote_number

        if not user.is_staff:
            subject = "%s user accessed %s" % (settings.HOST_NAME, req.path)
            ip = req.META.get(
                'HTTP_X_FORWARDED_FOR',
                req.META.get('HTTP_X_REAL_IP',
                             req.META.get('REMOTE_ADDR', 'unknown')))
            message = quote_viewed_template.format(s=settings,
                                                   ip=ip,
                                                   u=user,
                                                   r=req)
            to = settings.CONTACT_EMAILS
            fm = '*****@*****.**'  # user.email
            send_mail(subject,
                      message,
                      fm,
                      to,
                      fail_silently=not settings.DEBUG)

        for line in q.quotelineitem_set.all(
        ):  # lame: dj templates can't do multiplcation or expressions
            line.ext = line.quantity * line.price

        return render_to_response(
            'quote.html',
            dict(title="Quote: %s" % q.quote_number,
                 q=q,
                 breadcrumbs=(quote_breadcrumb,
                              Breadcrumb('Quote %s' % q.quote_number,
                                         'Quote %s' % q.quote_number,
                                         '/quotes/%s' % q.quote_number))),
            context_instance=RequestContext(req))
    else:
        # render the list
        if user.is_staff:
            qs = Quote.objects.filter(approved_by=user)
        else:
            qs = Quote.objects.filter(customer__user=user)

        return render_to_response('entries.html',
                                  dict(
                                      entries=qs,
                                      title='Quote list for %s' % user,
                                      breadcrumbs=(quote_breadcrumb, ),
                                  ),
                                  context_instance=RequestContext(req))
Beispiel #41
0
def printreport(request, permit_request):
    """Return a PDF of the permit request generated using weasyprint.

    Parameters
    ----------
    request : <class 'django.core.handlers.wsgi.WSGIRequest'>
        The user request.
    permit_request : <class 'permits.models.PermitRequest'>
        The permit request.

    Returns
    -------
    pdf_permit : <class 'bytes'>
        The PDF of the permit request.
    """

    geo_times = permit_request.geo_time.all()
    printurl = get_map_url(geo_times, permit_request.pk)
    print_date = timezone.now()
    validations = permit_request.validations.all()
    objects_infos = services.get_permit_objects(permit_request)
    actor_types = dict(models.ACTOR_TYPE_CHOICES)

    contacts = [(actor_types.get(contact['actor_type'].value(), ''), [
        (field.label, field.value()) for field in contact
        if field.name not in {'id', 'actor_type'}
    ]) for contact in services.get_permitactorformset_initiated(permit_request)
                if contact['id'].value()]

    author = permit_request.author
    administrative_entity = permit_request.administrative_entity

    html = render(
        request, "permits/print/printpermit.html", {
            'permit_request':
            permit_request,
            'contacts':
            contacts,
            'author':
            author,
            'objects_infos':
            objects_infos,
            'print_date':
            print_date,
            'administrative_entity':
            administrative_entity,
            'geo_times':
            geo_times,
            'map_image':
            printurl,
            'validations':
            validations,
            'logo_main':
            b64encode(
                administrative_entity.logo_main.open().read()).decode("utf-8")
            if administrative_entity.logo_main else '',
            'logo_secondary':
            b64encode(administrative_entity.logo_secondary.open().read(
            )).decode("utf-8") if administrative_entity.logo_secondary else '',
            'image_signature_1':
            b64encode(administrative_entity.image_signature_1.open().read()).
            decode("utf-8") if administrative_entity.image_signature_1 else '',
            'image_signature_2':
            b64encode(administrative_entity.image_signature_2.open().read()).
            decode("utf-8") if administrative_entity.image_signature_2 else '',
        })

    pdf_permit = HTML(
        string=html.content, base_url=request.build_absolute_uri()).write_pdf(
            stylesheets=[CSS('/code/static/css/printpermit.css')])

    file_name = 'permis_' + str(permit_request.pk) + '.pdf'
    permit_request.printed_file.save(file_name, ContentFile(pdf_permit), True)
    permit_request.printed_at = timezone.now()
    permit_request.printed_by = request.user.get_full_name()
    permit_request.save()

    return pdf_permit
Beispiel #42
0
    <meta charset="utf-8">
</head>
<body>
'''
for k in all_html:
    html += k + '<br>' + all_html[k] + '<hr>'

html += "</body></html>"

font_config = FontConfiguration()
css = CSS(string='''
    * {
        font-size : 0.8rem;
    }
    body {
        backgroud: black;
    }
    @font-face {
        font-family: Gentium;
        src: url(http://example.com/fonts/Gentium.otf);
    }
    h1 { font-family: Gentium }
    img {width: 30; height: 60}''',
          font_config=font_config)

#print(html)
report_html = HTML(string=html)
report_html.write_pdf(target='test.pdf',
                      stylesheets=[css],
                      font_config=font_config)
Beispiel #43
0
def render(cat_image, background_image, text):
    ugly_text = uglify(text)
    font = random.choice(fonts)
    color = random.choice(colors)
    pixabay_logo = os.path.join(os.getcwd(), 'spreukbot/pixabay-logo.png')
    cat_url, cat_width, cat_height = cat_image
    bg_url, bg_width, bg_height = background_image
    demo_page = f'''
        data:text/html,
        <!doctype html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>LOL</title>
            <link href="https://fonts.googleapis.com/css?family=Pacifico|Baloo+Tamma|Merriweather|Poiret+One" rel="stylesheet">
            <style>
                @page {{
                    margin: 0;
                    size: {cat_width * 3}px {cat_height}px;
                }}
                * {{
                    padding: 0;
                    margin: 0;
                    text-shadow: #FC0 1px 0 10px;
                }}
                html, body {{
                    text-align: center;
                    padding: 0;
                }}
                body:before {{
                    content: "";
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background-size: cover;
                    background-image: url('{bg_url.replace('https://pixabay.com', 'http://spreukbot-pixabay.barkr.uk')}');
                    background-repeat: no-repeat;
                }}
                p {{
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    font-family: {font};
                    font-size: 32px;
                    color: {color};
                    text-stroke: 2px white;
                }}
                p.shadow {{
                    color: black !important;
                    top: 1px;
                    left: 1px;
                }}
                div.watermark {{
                    position: absolute;
                    right: 10%;
                    bottom: 10%;
                    transform: rotate(-45deg);
                    opacity: .2;
                    width: 20%;
                }}
                img.pixabay {{
                    position: absolute;
                    right: 0;
                    top: 0;
                }}
            </style>
        </head>
        <body>
        <p>text</p>
        <div class="watermark">
            Wijze spreuken om te delen van Marko V. Keten
        </div
        <img class="pixabay" src="cat_url">
        </body>
        </html>
    '''
    from weasyprint import HTML
    from weasyprint.logger import LOGGER as weasyprint_logger
    import logging
    logging.getLogger('weasyprint').setLevel(logging.DEBUG)
    weasyprint_logger.addFilter(WeasyprintLoggerFilter())
    weasyprint_logger.setLevel(logging.DEBUG)
    data = HTML(string=demo_page).write_png()
    return data
Beispiel #44
0
def html_to_pdf(html: str, template_name: str):
    html = HTML(string=html)
    css = CSS(filename=get_css_location(template_name),
              font_config=font_config)
    return html.write_pdf(stylesheets=[css], font_config=font_config)
Beispiel #45
0
    def mk_report(self, start_time, end_time, profeat, path=None):
        """Produce PDF report.

        Args:
          start_time (int): start time UNIX timestamp.
          end_time (int): end time UNIX timestamp.
          profeat (dict): profile features.
          path (string): report file path (opt).

        Returns:
          None: writes PDF report.
        """

        # From time to timestamp
        start_time = datetime.datetime.fromtimestamp(start_time)
        start_time = start_time.strftime('%Y-%m-%d %H:%M:%S')
        end_time = datetime.datetime.fromtimestamp(end_time)
        end_time = end_time.strftime('%Y-%m-%d %H:%M:%S')

        # Load template
        gpdir = pkg_resources.resource_filename(const.PACK_NAME, '')
        gpdir += '/static/'
        env = Environment(loader=FileSystemLoader(gpdir))
        env.filters['type'] = type
        env.filters['has_key'] = lambda a, b: b in a.keys()
        template = env.get_template("report_template.html")

        # Prepare variables to fill the template
        tempv = {
            'profeat':
            profeat,
            'starttime':
            start_time,
            'endtime':
            end_time,
            'basedir':
            self.basedir,
            'outdir':
            self.outdir,
            'logpath':
            self.logpath,
            'reg':
            self.reg,
            'ext':
            self.ext,
            'skip': [
                const.STEP_DESCR[i - 1] for i in self.skip
                if i in range(len(const.STEP_DESCR))
            ],
            'ncores':
            self.ncores,
            #'correctca' : self.correctCA,
            'verbose':
            self.verbose,
            'debugging':
            self.debugging,
            'suffix':
            self.suffix,
            'dna_names':
            self.dna_names,
            'sig_names':
            self.sig_names,
            'plotting':
            self.plotting,
            'fontsize':
            self.font_size,
            'nbins':
            self.nbins,
            'sigma_smooth':
            self.sigma_smooth,
            'sigma_density':
            self.sigma_density,
            'seg_type':
            const.SEG_LABELS[self.seg_type],
            'adp_thr':
            self.adaptive_neighbourhood,
            'radius_interval':
            self.radius_interval,
            'min_z_size':
            self.min_z_size,
            'offset':
            self.offset,
            'rm_z_tips':
            self.do_clear_Z_borders,
            'an_type':
            const.AN_LABELS[self.an_type],
            'mid_type':
            const.MID_SEC_LABELS[self.mid_type],
            'dist_type':
            self.dist_type,
            'aspect':
            self.aspect,
            'nsf': [
                const.NSEL_NAMES[i] for i in self.nsf
                if i in range(len(const.NSEL_NAMES))
            ],
            'part_n_erosion':
            self.part_n_erosion,
            'norm_d':
            self.normalize_distance,
            'rescale_deconvolved':
            self.rescale_deconvolved,
            'notes':
            self.notes,
            'conds':
            self.conds,
            'cnuclei':
            [sum([len(s.nuclei) for s in c.series]) for c in self.conds],
            'cdescr':
            self.cdescr
        }

        # Escape characters
        for (k, v) in tempv.items():
            if type('') == type(v):
                tempv[k] = v.replace('<', '&lt;').replace('>', '&gt;')

        # Fill template
        html_out = template.render(tempv)

        # Hide CSS warnings
        logger = logging.getLogger('weasyprint')
        logger.handlers = []
        logger.addHandler(logging.FileHandler('/tmp/weasyprint.log'))

        # Output
        suffix = datetime.datetime.fromtimestamp(time.time())
        suffix = suffix.strftime('%Y-%m-%d %H:%M:%S')
        fname = self.outdir + 'report.' + suffix + '.pdf'
        HTML(string=html_out).write_pdf(fname)
Beispiel #46
0
    def postpub(self):
        """
        main publication function
        """
        res = []
        pivot = self.pivot
        body = pivot.xpath('/*/*[local-name() = "body"]')[0]
        head = pivot.xpath('/*/*[local-name() = "head"]')[0]

        # add css
        css = self.scriptdef.xpath('string(parameters/parameter[@name="CSS"]/@value)')
        logger.debug(css)
        baseurl = "file://%s"%(self.getOsPath("/"))
        csslink = "%s/kolekti/publication-templates/weasyprint/css/%s.css"%(baseurl,css)
 
        logger.debug(csslink)
        ET.SubElement(head,'link',attrib = {
            "rel":"stylesheet",
            "type":"text/css",
            "href": csslink
            })
        ET.SubElement(head,'base',attrib = {
            "href": baseurl
            })
        
       
        # make image urls relative in pivot
        for media in pivot.xpath("//h:img[@src]|//h:embed[@src]", namespaces=self.nsmap):
            src = media.get('src')
            if src[0] == "/":
                media.set('src', src[1:])


        # produce pdf once
        pubdir = self.pubdir(self.assembly_dir, self.profile)        
        pdf = os.path.join(self.getOsPath(pubdir),self.publication_file+'.pdf')
        
        HTML(string = ET.tostring(pivot)).write_pdf(pdf)

        if self.scriptdef.xpath('boolean(parameters/parameter[@name="two_passes"]/@value = "yes")'):
            # count pages in pdf
            with open(pdf, 'rb') as pdffile:
                nbpages = PdfFileReader(pdffile).getNumPages() 
                
            logger.debug( "pdf nbpages : %d"%(nbpages,))
    
            # update pivot body attributes
            body.set('data-pagecount', str(nbpages))
            body.set('data-pagecount-mod-2', str(nbpages % 2))
            body.set('data-pagecount-mod-4', str(nbpages % 4))
            body.set('data-pagecount-mod-8', str(nbpages % 8))
            body.set('data-pagecount-mod-16', str(nbpages % 16))


            pivfile = pubdir + "/document_nbpage_attrs.xhtml"
            self.xwrite(pivot, pivfile, sync = False)
            
            # produce pdf with modified pivot
            HTML(string = ET.tostring(pivot)).write_pdf(pdf)

        subst = {}
        for p in self.scriptdef.xpath('parameters/parameter'):
            subst.update({p.get('name'):p.get('value')})
                
        pubdir = self.pubdir(self.assembly_dir, self.profile)
        subst.update({
            "APPDIR":self._appdir,
            "PLUGINDIR":self._plugindir,
            "PUBDIR":self.getOsPath(pubdir),
            "SRCDIR":self.getOsPath(self.assembly_dir),
            "BASEURI":self.getUrlPath(self.assembly_dir) + '/',
            "PUBURI":pubdir,
            "PUBNAME":self.publication_file,
        })
        xl=self.scriptspec.find('link')
        outfile=self._substscript(xl.get('name'), subst, self.profile)
        outref=self._substscript(xl.get('ref'), subst, self.profile)
        outtype=xl.get('type')

        res=[{"type":outtype, "label":outfile, "url":outref, "file":outref}]
        return res
Beispiel #47
0
def download_multiple_worksheet(request, **kwargs):
    """Download pdf and sample zip file from multiple worksheets."""

    project_slug = kwargs.pop('project_slug')
    project = Project.objects.get(slug=project_slug)
    worksheets_obj = request.GET.get('worksheet')
    worksheets = json.loads(worksheets_obj)

    def get_context_data(pk):
        """Get the context data which is passed to a template.

        :param kwargs: Any arguments to pass to the superclass.
        :type kwargs: dict

        :returns: Context data which will be passed to the template.
        :rtype: dict
        """
        context = {}
        context['worksheet'] = Worksheet.objects.get(pk=pk)
        context['requirements'] = Specification.objects.filter(worksheet=pk)

        questions = WorksheetQuestion.objects.filter(worksheet=pk)
        context['questions'] = OrderedDict()
        for question in questions:
            context['questions'][question] = Answer.objects.filter(
                question=question)

        context['further_reading'] = FurtherReading.objects.filter(
            worksheet=pk)

        context['file_title'] = \
            context['worksheet'].section.name \
            + '_' + context['worksheet'].title
        context['file_title'] = context['file_title'].encode("utf8")
        return context

    s = BytesIO()
    zf = zipfile.ZipFile(s, "w")
    initial_numbering = ''
    final_numbering = ''

    for pk in worksheets:
        numbering = worksheets[pk]
        array_numbering = numbering.split('.')

        if initial_numbering == '':
            initial_numbering = numbering
        else:
            array_initial_numbering = initial_numbering.split('.')
            if int(array_numbering[0]) < int(array_initial_numbering[0]):
                initial_numbering = numbering
            elif int(array_numbering[0]) == int(array_initial_numbering[0]):
                if int(array_numbering[1]) < int(array_initial_numbering[1]):
                    initial_numbering = numbering

        if final_numbering == '':
            final_numbering = numbering
        else:
            array_final_numbering = final_numbering.split('.')
            if int(array_numbering[0]) > int(array_final_numbering[0]):
                final_numbering = numbering
            elif int(array_numbering[0]) == int(array_final_numbering[0]):
                if int(array_numbering[1]) > int(array_final_numbering[1]):
                    final_numbering = numbering

        pk = int(pk)
        worksheet = Worksheet.objects.get(pk=pk)
        pdf_title = '{}. {}'.format(numbering, worksheet.module.encode("utf8"))
        context = get_context_data(pk)
        context['section_number'] = numbering.split('.')[0]
        context['module_number'] = numbering
        response = render_to_response('worksheet/print.html', context=context)

        pdf_response = HttpResponse(content_type='application/pdf')
        pdf_response['Content-Disposition'] = \
            'attachment; filename={}'.format(pdf_title)

        html_object = HTML(
            string=response.content,
            base_url='file://',
        )
        html_object.write_pdf(pdf_response)

        with open('/tmp/{}.pdf'.format(pdf_title), 'wb') as pdf:
            pdf.write(pdf_response.content)

        fpath = '/tmp/{}.pdf'.format(pdf_title)

        dir_number = numbering.split('.')[0]
        zip_subdir = '{}. {}'.format(dir_number, worksheet.section.name)

        fdir, fname = os.path.split(fpath)
        zip_path = os.path.join(zip_subdir, fname)

        zf.write(fpath, zip_path)

        if worksheet.external_data:
            data_path = worksheet.external_data.url
            zip_data_path = settings.MEDIA_ROOT + data_path[6:]
            zip_path = os.path.join(zip_subdir, pdf_title + '.zip')
            zf.write(zip_data_path, zip_path)

    zf.close()

    downloaded_module = ''
    if len(worksheets) > 0:
        if len(worksheets) == 1:
            downloaded_module = 'module {}'.format(initial_numbering)
        else:
            downloaded_module = 'module {} to {}'.format(
                initial_numbering, final_numbering)

    zip_response = HttpResponse(s.getvalue(),
                                content_type="application/x-zip-compressed")
    zip_response['Content-Disposition'] = \
        'attachment; filename={}-worksheet {}.zip'.format(
            project.name.encode('utf8'), downloaded_module)
    return zip_response
Beispiel #48
0
def _create_pdf(rendered_template, absolute_url):
    from weasyprint import HTML
    pdf_file = (HTML(string=rendered_template,
                     base_url=absolute_url).write_pdf())
    return pdf_file
Beispiel #49
0
 def render(filename):
     return HTML(resource_filename(filename)).render()
def generate_report(url, username, password, component_key):
    server_version = get_string(url, username, password, "/api/server/version")

    json_data = get_json(
        url, username, password,
        "/api/navigation/component?componentKey=" + component_key)
    project_name = json_data["name"]
    project_organization = json_data["organization"]
    project_quality_gate = json_data["qualityGate"]
    project_quality_profiles = json_data["qualityProfiles"]
    project_analysis_date = dateutil.parser.parse(json_data["analysisDate"])
    project_analysis_date_utc = str(
        datetime.datetime.utcfromtimestamp(
            project_analysis_date.timestamp())) + " UTC"
    project_version = json_data["version"]

    quality_gates_table = ""
    if project_quality_gate:
        quality_gates_table += "<table><tr><th>Key</th><th>Name</th><th>Is Default</th></tr>"
        if 'key' in project_quality_gate:
            quality_gates_table += "<td>" + str(
                project_quality_gate['key']) + "</td>"
        else:
            quality_gates_table += "<td></td>"
        if 'name' in project_quality_gate:
            quality_gates_table += "<td>" + project_quality_gate[
                'name'] + "</td>"
        else:
            quality_gates_table += "<td></td>"
        if 'isDefault' in project_quality_gate:
            quality_gates_table += "<td>" + str(
                project_quality_gate['isDefault']) + "</td>"
        else:
            quality_gates_table += "<td></td>"

    quality_gates_table += "</table>"

    quality_profiles_table = ""
    if len(project_quality_profiles) > 0:
        quality_profiles_table += "<table><tr><th>Key</th><th>Name</th><th>Language</th></tr>"
        for quality_profile in project_quality_profiles:
            quality_profiles_table += "<tr>"
            if 'key' in quality_profile:
                quality_profiles_table += "<td>" + quality_profile[
                    'key'] + "</td>"
            else:
                quality_profiles_table += "<td></td>"
            if 'name' in quality_profile:
                quality_profiles_table += "<td>" + quality_profile[
                    'name'] + "</td>"
            else:
                quality_profiles_table += "<td></td>"
            if 'language' in quality_profile:
                quality_profiles_table += "<td>" + quality_profile[
                    'language'] + "</td>"
            else:
                quality_profiles_table += "<td></td>"
            quality_profiles_table += "</tr>"

    quality_profiles_table += "</table>"

    json_data = get_json(
        url, username, password,
        "/api/measures/component?additionalFields=metrics%2Cperiods&componentKey="
        + component_key +
        "&metricKeys=alert_status%2Cquality_gate_details%2Cbugs%2Cnew_bugs%2Creliability_rating%2Cnew_reliability_rating%2Cvulnerabilities%2Cnew_vulnerabilities%2Csecurity_rating%2Cnew_security_rating%2Ccode_smells%2Cnew_code_smells%2Csqale_rating%2Cnew_maintainability_rating%2Csqale_index%2Cnew_technical_debt%2Ccoverage%2Cnew_coverage%2Cnew_lines_to_cover%2Ctests%2Cduplicated_lines_density%2Cnew_duplicated_lines_density%2Cduplicated_blocks%2Cncloc%2Cncloc_language_distribution%2Cprojects%2Cnew_lines"
    )
    measures = json_data['component']['measures']
    periods = json_data["periods"]
    metrics = json_data["metrics"]

    quality_gate_status = get_value_for_metric_key("alert_status", measures)
    if quality_gate_status == "ERROR":
        quality_gate_status = "Failed"
    bugs = get_value_for_metric_key("bugs", measures)
    vulnerabilities = get_value_for_metric_key("vulnerabilities", measures)
    security_rating = get_value_for_metric_key("security_rating", measures)
    code_smells = get_value_for_metric_key("code_smells", measures)
    coverage = get_value_for_metric_key("coverage", measures)
    duplicated_blocks = get_value_for_metric_key("duplicated_blocks", measures)
    duplicated_lines_density = get_value_for_metric_key(
        "duplicated_lines_density", measures)
    ncloc = get_value_for_metric_key("ncloc", measures)
    ncloc_language_distribution = get_value_for_metric_key(
        "ncloc_language_distribution", measures)
    reliability_rating = get_value_for_metric_key("reliability_rating",
                                                  measures)
    sqale_index = get_value_for_metric_key("sqale_index", measures)
    sqale_rating = get_value_for_metric_key("sqale_rating", measures)

    period_index = 0
    period_details_table = ""

    if len(periods) > 0:
        period = periods[period_index]
        period_since = "previous version"
        if "parameter" in period:
            period_since = period["parameter"]
        else:
            if "mode" in period:
                period_since = period["mode"]
        period_started = period["date"]
        new_bugs = get_value_for_metric_key_and_period_index(
            "new_bugs", measures, period_index)
        new_vulnerabilities = get_value_for_metric_key_and_period_index(
            "new_vulnerabilities", measures, period_index)
        new_security_rating = get_value_for_metric_key_and_period_index(
            "new_security_rating", measures, period_index)
        new_code_smells = get_value_for_metric_key_and_period_index(
            "new_code_smells", measures, period_index)
        new_lines = get_value_for_metric_key_and_period_index(
            "new_lines", measures, period_index)
        new_lines_to_cover = get_value_for_metric_key_and_period_index(
            "new_lines_to_cover", measures, period_index)
        new_reliability_rating = get_value_for_metric_key_and_period_index(
            "new_reliability_rating", measures, period_index)
        new_technical_debt = get_value_for_metric_key_and_period_index(
            "new_technical_debt", measures, period_index)
        new_maintainability_rating = get_value_for_metric_key_and_period_index(
            "new_maintainability_rating", measures, period_index)
        period_details_table += "<h3>Leak Period: since " + period_since + ", started " + period_started + "</h3>"
        period_details_table += "<table><tr><th>Issue Type</th><th>Value</th></tr>"
        period_details_table += "<tr><td>New Bugs</td><td>" + new_bugs + "</td></tr>"
        period_details_table += "<tr><td>New Vulnerabilities</td><td>" + new_vulnerabilities + "</td></tr>"
        period_details_table += "<tr><td>Security Rating on New Code</td><td>" + new_security_rating + "</td></tr>"
        period_details_table += "<tr><td>New Code Smells</td><td>" + new_code_smells + "</td></tr>"
        period_details_table += "<tr><td>New Lines</td><td>" + new_lines + "</td></tr>"
        period_details_table += "<tr><td>Lines to Cover on New Code</td><td>" + new_lines_to_cover + "</td></tr>"
        period_details_table += "<tr><td>Reliability Rating on New Code</td><td>" + new_reliability_rating + \
                                "</td></tr>"
        period_details_table += "<tr><td>Added Technical Debt</td><td>" + new_technical_debt + "</td></tr>"
        period_details_table += "<tr><td>Maintainability Rating on New Code</td><td>" + new_maintainability_rating + \
                                "</td></tr>"
        period_details_table += "</table><br>"

    quality_gate_details = get_value_for_metric_key("quality_gate_details",
                                                    measures)
    quality_gate_details_table = ""
    if quality_gate_details:
        conditions = json.loads(quality_gate_details)["conditions"]
        if len(conditions) > 0:
            quality_gate_details_table += "<table><tr><th>Metric</th><th>Actual Value</th><th>Operand</th>" \
                                          "<th>Expected Value</th></tr>"
            for condition in conditions:
                quality_gate_details_table += "<tr>"
                if 'level' in condition and condition['level'] == "ERROR":
                    if 'metric' in condition:
                        metric_name = get_name_for_metric_key(
                            condition['metric'], metrics)
                        quality_gate_details_table += "<td>" + metric_name + "</td>"
                    else:
                        quality_gate_details_table += "<td></td>"
                    if 'actual' in condition:
                        quality_gate_details_table += "<td>" + condition[
                            'actual'] + "</td>"
                    else:
                        quality_gate_details_table += "<td></td>"
                    if 'op' in condition:
                        quality_gate_details_table += "<td>" + condition[
                            'op'] + "</td>"
                    else:
                        quality_gate_details_table += "<td></td>"
                    if 'error' in condition:
                        quality_gate_details_table += "<td>" + condition[
                            'error'] + "</td>"
                    else:
                        quality_gate_details_table += "<td></td>"

            quality_gate_details_table += "</tr></table>"

    json_data = get_json(
        url, username, password, "/api/issues/search?componentKeys=" +
        component_key + "&statuses=OPEN&ps=1")
    if json_data['total'] == 0:
        print("no data returned - no report will be generated")
    else:
        print("found " + str(json_data['total']) +
              " issues. Report will be generated...")
        json_all = "["

        # GET ALL ISSUES (max. 500) OF TYPE VULNERABILITY
        json_vulnerabilities = get_json(
            url, username, password, "/api/issues/search?componentKeys=" +
            component_key + "&statuses=OPEN&ps=500&types=VULNERABILITY")
        if json_vulnerabilities['total'] > 0:
            print("found " + str(json_vulnerabilities['total']) +
                  " issues of type VULNERABILITY")
            json_vulnerabilities = filter_json(json_vulnerabilities)
            json_all += json_vulnerabilities

        # GET ALL ISSUS (max. 500) OF TYPE BUG
        json_bugs = get_json(
            url, username, password, "/api/issues/search?componentKeys=" +
            component_key + "&statuses=OPEN&ps=500&types=BUG")
        if json_bugs['total'] > 0:
            print("found " + str(json_bugs['total']) + " issues of type BUG")
            json_bugs = filter_json(json_bugs)
            if json_all != "[":
                json_all += ","
            json_all += json_bugs

        # GET ALL ISSUES (max. 500) OF TYPE CODE_SMELL
        json_codesmells = get_json(
            url, username, password, "/api/issues/search?componentKeys=" +
            component_key + "&statuses=OPEN&ps=500&types=CODE_SMELL")
        if json_codesmells['total'] > 0:
            print("found " + str(json_codesmells['total']) +
                  " issues of type CODE_SMELL")
            json_codesmells = filter_json(json_codesmells)
            if json_all != '[':
                json_all += ","
            json_all += json_codesmells

        json_all += "]"

        # GENERATE PDF
        json_data = json.loads(json_all)
        html_issues = ""

        for i in json_data:
            html_issues += "<tr>"
            if 'type' in i:
                html_issues += "<td>" + i['type'] + "</td>"
            else:
                html_issues += "<td></td>"
            if 'component' in i:
                component = i['component']
                component = component.split(":")[-1]
                html_issues += "<td>" + component + "</td>"
            else:
                html_issues += "<td></td>"
            if 'startLine' in i:
                html_issues += "<td>" + str(i['startLine']) + "</td>"
            else:
                html_issues += "<td></td>"
            if 'endLine' in i:
                html_issues += "<td>" + str(i['endLine']) + "</td>"
            else:
                html_issues += "<td></td>"
            if 'message' in i:
                html_issues += "<td>" + i['message'] + "</td>"
            else:
                html_issues += "<td></td>"
            html_issues += "</tr>"

        now_in_utc = datetime.datetime.utcfromtimestamp(
            datetime.datetime.now().timestamp())
        creation_date = str(now_in_utc) + " UTC"

        env = Environment(loader=FileSystemLoader('.'))
        template = env.get_template(TEMPLATE)
        template_vars = {
            "project": component_key,
            "server_version": server_version,
            "creation_date": creation_date,
            "quality_gate_status": quality_gate_status,
            "bugs": bugs,
            "vulnerabilities": vulnerabilities,
            "security_rating": security_rating,
            "code_smells": code_smells,
            "coverage": coverage,
            "duplicated_blocks": duplicated_blocks,
            "duplicated_lines_density": duplicated_lines_density,
            "ncloc": ncloc,
            "ncloc_language_distribution": ncloc_language_distribution,
            "reliability_rating": reliability_rating,
            "sqale_index": sqale_index,
            "sqale_rating": sqale_rating,
            "issue_table": html_issues,
            "quality_gate_details_table": quality_gate_details_table,
            "project_name": project_name,
            "project_organization": project_organization,
            "project_version": project_version,
            "quality_gates_table": quality_gates_table,
            "quality_profiles_table": quality_profiles_table,
            "project_analysis_date": project_analysis_date_utc
        }
        html_out = template.render(template_vars)
        report_name = "sonarqube_report_" + project_name + "_" + now_in_utc.strftime(
            "%Y%m%d%H%M%S") + ".pdf"
        HTML(string=html_out,
             base_url=".").write_pdf(report_name, stylesheets=["style.css"])
Beispiel #51
0
 def pdfreport(self, html_obj, analysis):
     pdf_name = "report_{0}.pdf".format(analysis['_id'])
     pdf_file = path.join(fame_config.temp_path, pdf_name)
     HTML(html_obj).write_pdf(pdf_file)
     print(">>> PDF Report {0} generated").format(analysis['_id'])
     return pdf_file
Beispiel #52
0
def document_png():
    # We didn’t bother to make a ``render_png`` helper
    # but of course you can still use WeasyPrint’s PNG output.
    return Response(HTML('/').write_png(), mimetype='image/png')
Beispiel #53
0
from __future__ import print_function
from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML
import pandas as pd

config = "Output/config.csv"

df = pd.read_csv(config)

env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("report_template.html")

html_out = template.render(items=df)

HTML(string=html_out).write_pdf("test.pdf", stylesheets=["reportstyle.css"])
Beispiel #54
0
    def generar_pdf(self, request, orden_examen):
        if not orden_examen.especial:
            multifirma = OrdenExamen.objects.select_related(
                'examen', 'examen__subgrupo_cups').prefetch_related(
                    'mis_firmas',
                    'mis_firmas__especialista',
                    'mis_firmas__especialista__especialidad',
                ).annotate(can_firmas=Count("mis_firmas")).filter(
                    pk=orden_examen.id,
                    can_firmas__gt=1,
                    examen__especial=False,
                    examen_estado=2,
                )

            una_firma = OrdenExamenFirmas.objects.select_related(
                'especialista',
                'especialista__especialidad',
                'orden_examen',
                'orden_examen__examen',
                'orden_examen__examen__subgrupo_cups',
            ).annotate(especialist=F('especialista'),
                       can_firmas=Count("orden_examen__mis_firmas")).filter(
                           orden_examen=orden_examen,
                           orden_examen__examen__especial=False,
                           can_firmas=1,
                           orden_examen__examen_estado=2,
                       )

            ctx = {
                'paciente': orden_examen.orden.paciente,
                'orden': orden_examen.orden,
                'entidad': orden_examen.orden.entidad,
                'medico_remitente': orden_examen.orden.medico_remitente,
                'multifirma': multifirma,
                'una_firma': una_firma,
                'examen': orden_examen,
            }
            html_get_template = get_template(
                'email/ordenes/resultados/datos_orden.html').render(ctx)
            html = HTML(string=html_get_template,
                        base_url=request.build_absolute_uri())
            header_datos = html.render(stylesheets=[
                CSS(string='div {position: fixed; top: 0, margin:0, padding:0}'
                    )
            ])

            header_datos_page = header_datos.pages[0]
            header_datos_body = get_page_body(
                header_datos_page._page_box.all_children())
            header_datos_body = header_datos_body.copy_with_children(
                header_datos_body.all_children())

            html_get_template = get_template(
                'email/ordenes/resultados/resultados.html').render(ctx)

            html = HTML(string=html_get_template,
                        base_url=request.build_absolute_uri())

            main_doc = html.render(
                stylesheets=[CSS('static/css/pdf_ordenes_resultado.min.css')])
            for i, page in enumerate(main_doc.pages):
                page_body = get_page_body(page._page_box.all_children())
                page_body.children += header_datos_body.all_children()

            output = BytesIO()
            main_doc.write_pdf(target=output)
            orden_examen.pdf_examen.delete()
            filename = "%s_ALE%s.pdf" % (orden_examen.nro_examen,
                                         random.randint(1000, 9999))
            orden_examen.pdf_examen.save(filename, File(output))
            output.close()
Beispiel #55
0
onepage = onepage.replace('{{ content }}', '') # cleans up the last spaceholder
onepageFile.write(onepage)
onepageFile.close()

if not nopdf:
	if not quiet:
		print('Generating the PDF...')

	# Create the PDF version of the documentation
	pdfpage = pdfpage.replace('{% tree %}', opsidebar) # create the TOC
	pdfpage = pdfpage.replace('{{ content }}', '') # cleans up the last spaceholder
	pdfpage = pdfpage.replace('{{ today }}', global_today)
	pdfpage = pdfpage.replace('{{ today_iso }}', global_today_iso)
	pdfpage = pdfpage.replace('src="/images/', 'src="images/') # makes images links relative
	pdfpage = pdfpage.replace('url(\'/images/', 'url(\'images/') # CSS images links relative
	# Write it to disk (optional, can be removed)
	pdfpageFile = open(global_site_dir + 'pdf.html', 'w')
	pdfpageFile.write(pdfpage)
	pdfpageFile.close()

	# Generating the actual PDF with weasyprint (https://weasyprint.org/)
	from weasyprint import HTML
	from weasyprint.fonts import FontConfiguration
	html_font_config = FontConfiguration()
	doc = HTML(string = pdfpage, base_url = global_site_dir)
	doc.write_pdf(global_site_dir + 'manual.pdf', font_config = html_font_config)

if not quiet:
	print('Processed ' + str(fileCount) + ' files.')

Beispiel #56
0
from utils import *
import pandas as pd
import numpy as np
import pprint
sched = get_schedule()
extra_key = str(max([int(x) for x in sched.keys()]))
del sched[extra_key]

html_str = ''
for i in sched:
    df = pd.DataFrame.from_dict(sched[i]).transpose()
    df.index.name = "Match-ID"
    df.columns = ['Player 1', 'Player 2']
    html_str += "<h2>Day {}</h2>".format(i) + "\n" + df.to_html() + "\n\n"

from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("matches.html")
template_vars = {"title": "Matchups", "national_pivot_table": html_str}
html_out = template.render(template_vars)
from weasyprint import HTML
HTML(string=html_out).write_pdf("matchups.pdf", stylesheets=["style.css"])
Beispiel #57
0
 parser = argparse.ArgumentParser(description='Generate PDF report')
 parser.add_argument('infile',
                     type=argparse.FileType('r'),
                     help="report source file in Excel")
 parser.add_argument('outfile',
                     type=argparse.FileType('w'),
                     help="output file in PDF")
 args = parser.parse_args()
 # Read in the file and get our pivot table summary
 df = pd.read_excel(args.infile.name)
 sales_report = create_pivot(df, args.infile.name)
 # Get some national summary to include as well
 manager_df = []
 for manager in sales_report.index.get_level_values(0).unique():
     manager_df.append(
         [manager, sales_report.xs(manager, level=0).to_html()])
 # Do our templating now
 # We can specify any directory for the loader but for this example, use current directory
 env = Environment(loader=FileSystemLoader('.'))
 template = env.get_template("myreport.html")
 template_vars = {
     "title": "National Sales Funnel Report",
     "CPU": get_summary_stats(df, "CPU"),
     "Software": get_summary_stats(df, "Software"),
     "national_pivot_table": sales_report.to_html(),
     "Manager_Detail": manager_df
 }
 # Render our file and create the PDF using our css style file
 html_out = template.render(template_vars)
 HTML(string=html_out).write_pdf(args.outfile.name,
                                 stylesheets=["style.css"])
Beispiel #58
0
def vir_typer_results(request, vir_typer_pk):
    from django.core.files.storage import FileSystemStorage
    from django.http import HttpResponse
    from django.template.loader import render_to_string
    import datetime
    manager_codes = {
        'NOVI': {
            'code':
            'NOV1-SEQ',
            'comments_en':
            'Norovirus genogroup I was confirmed by gene sequencing of the amplicon.',
            'comments_fr':
            'Le séquençage de l\'amplicon confirme la présence du Norovirus génogroup I.'
        },
        'NOVII': {
            'code':
            'NOV2-SEQ',
            'comments_en':
            'Norovirus genogroup II was confirmed by gene sequencing of the amplicon.',
            'comments_fr':
            'Le séquençage de l\'amplicon confirme la présence du Norovirus génogroup II.'
        },
        'HAV': {
            'code':
            'HAV-SEQ',
            'comments_en':
            'Hepatitis A was confirmed by gene sequencing of the amplicon.',
            'comments_fr':
            'Le séquençage de l\'amplicon confirme la présence du Hepatitis A.'
        },
        'MNV': {
            'code':
            'MNV-SEQ',
            'comments_en':
            'Murine norovirus was confirmed by gene sequencing of the amplicon.',
            'comments_fr':
            'Le séquençage de l\'amplicon confirme la présence du Murine norovirus.'
        },
    }
    vir_typer_project = get_object_or_404(VirTyperProject, pk=vir_typer_pk)

    vir_typer_samples = list(
        VirTyperRequest.objects.filter(project_name__pk=vir_typer_pk))
    vir_typer_result = list()
    parse = False
    for sample in vir_typer_samples:
        vir_files = list(
            VirTyperFiles.objects.filter(sample_name__pk=sample.pk))
        for vir_file in vir_files:
            try:
                vir_typer_result.append(
                    VirTyperResults.objects.get(sequence_file__pk=vir_file.pk))
            except:
                parse = True
    # Parse the JSON report, and enter the results into the database if necessary
    if parse:
        parse_report(vir_typer_json=vir_typer_project.report,
                     vir_typer_samples=vir_typer_samples)
    vir_typer_samples = list(
        VirTyperRequest.objects.filter(project_name__pk=vir_typer_pk))
    pn = vir_typer_project.project_name
    vir_files = list()
    full_results = dict()
    full_results['data'] = list()
    codes = set()
    alleles = dict()
    outputs = list()
    samples = list()
    for sample in VirTyperRequest.objects.filter(
            project_name__pk=vir_typer_pk):
        samples.append(sample.sample_name)
    for sorted_sample in sorted(samples):
        for sample in VirTyperRequest.objects.filter(
                project_name__pk=vir_typer_pk):
            if sample.sample_name == sorted_sample:
                sequences = list()
                sample_dict = dict()
                sample_dict['sample_project'] = pn
                sample_dict['sample_name'] = sample.sample_name
                sample_dict['lsts'] = sample.LSTS_ID
                sample_dict['date_received'] = '{:%Y-%m-%d}'.format(
                    sample.date_received)
                sample_dict['isolate_source'] = sample.isolate_source
                sample_dict['organism'] = sample.putative_classification
                try:
                    codes.add(
                        (sample.putative_classification,
                         manager_codes[sample.putative_classification]['code'],
                         manager_codes[sample.putative_classification]
                         ['comments_en'], manager_codes[
                             sample.putative_classification]['comments_fr']))
                except KeyError:
                    pass
                sample_dict['identifier'] = list()
                sample_dict['allele'] = list()
                sample_dict['sequence'] = list()
                sample_dict['sequence_length'] = list()
                sample_dict['variable_locations'] = list()
                sample_dict['mean_quality'] = list()
                sample_dict['stdev_quality'] = list()
                alleles[sample.sample_name] = set()
                for vir_file in VirTyperFiles.objects.filter(
                        sample_name__pk=sample.pk):
                    vir_files.append(vir_file)
                    seq_identifier_well = str(
                        os.path.splitext(
                            vir_file.sequence_file)[0].split('_')[-2])
                    seq_identifier_num = os.path.splitext(
                        vir_file.sequence_file)[0].split('_')[-1]
                    seq_identifier_code = '_'.join(
                        (seq_identifier_well, seq_identifier_num))
                    sample_dict['identifier'].append(seq_identifier_code +
                                                     '\n')
                    result = VirTyperResults.objects.filter(
                        sequence_file__pk=vir_file.pk)
                    for vir_typer_result in result:
                        sample_dict['allele'].append(vir_typer_result.allele +
                                                     '\n')
                        alleles[sample.sample_name].add(
                            vir_typer_result.allele)
                        sequences.append({
                            sample.sample_name + '_' + seq_identifier_code:
                            vir_typer_result.trimmed_sequence
                        })
                        sample_dict['sequence_length'].append(
                            vir_typer_result.trimmed_sequence_len + '\n')
                        sample_dict['mean_quality'].append(
                            vir_typer_result.trimmed_quality_mean)
                        sample_dict['stdev_quality'].append(
                            vir_typer_result.trimmed_quality_stdev)

                consensus_sequence = sequence_consensus(
                    sequences, vir_typer_pk)
                for vir_file in VirTyperFiles.objects.filter(
                        sample_name__pk=sample.pk):
                    result = VirTyperResults.objects.filter(
                        sequence_file__pk=vir_file.pk)
                    for vir_typer_result in result:
                        html_string, variable_locations = sequence_html_string(
                            vir_typer_result.trimmed_sequence,
                            consensus_sequence)
                        sample_dict['variable_locations'].append(
                            variable_locations)
                        sample_dict['sequence'].append(html_string + '\n')
                full_results['data'].append(sample_dict)
                outputs.append(sample_dict)
    json_path = 'olc_webportalv2/static/ajax/vir_typer/{pk}/arrays.txt'.format(
        pk=vir_typer_pk)
    data_tables_path = '../../../../static/ajax/vir_typer/{pk}/arrays.txt'.format(
        pk=vir_typer_pk)
    os.makedirs(
        'olc_webportalv2/static/ajax/vir_typer/{pk}'.format(pk=vir_typer_pk),
        exist_ok=True)
    os.makedirs('olc_webportalv2/media/vir_typer/{pk}'.format(pk=vir_typer_pk),
                exist_ok=True)
    # Create the JSON-formatted output file
    with open(json_path, 'w') as json_out:
        json.dump(full_results, json_out)
    if request.method == 'POST':
        # Create a string of the HTML output using the appropriate template and variables
        html_string = render_to_string(
            'vir_typer/vir_typer_results_to_pdf.html', {
                'vir_typer_project': vir_typer_project,
                'date': '{:%Y-%m-%d}'.format(datetime.datetime.now()),
                'codes': sorted(list(codes)),
                'results': outputs,
                'vir_typer_samples': vir_typer_samples,
            })
        # Create an HTML object from the HTML string
        html = HTML(string=html_string, base_url=request.build_absolute_uri())
        # Set the links to the CSS files
        bootstrap_css = CSS(
            filename='olc_webportalv2/static/css/bootstrap.min.css')
        project_css = CSS(filename='olc_webportalv2/static/css/project.css')
        all_css = CSS(filename='olc_webportalv2/static/fonts/css/all.css')
        # Create a custom CSS string to make the page letter sized, with landscape orientation
        page_css = CSS(string='@page { size: Letter landscape; margin: 1cm }')
        #
        html.write_pdf(
            target=
            'olc_webportalv2/media/vir_typer/{pk}/VirusTyperReport_{pn}.pdf'.
            format(pk=vir_typer_pk, pn=vir_typer_project.project_name),
            stylesheets=[bootstrap_css, project_css, all_css, page_css],
            presentational_hints=True)
        # Download
        fs = FileSystemStorage(
            'olc_webportalv2/media/vir_typer/{pk}/'.format(pk=vir_typer_pk))
        with fs.open("VirusTyperReport_{pn}.pdf".format(
                pn=vir_typer_project.project_name)) as pdf:
            response = HttpResponse(pdf, content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename="VirusTyperReport_{pn}.pdf"'\
                .format(pn=vir_typer_project.project_name)
            return response
    return render(
        request, 'vir_typer/vir_typer_results.html', {
            'vir_typer_project': vir_typer_project,
            'date': '{:%Y-%m-%d}'.format(datetime.datetime.now()),
            'codes': sorted(list(codes)),
            'json_results': data_tables_path,
            'results': outputs,
            'vir_typer_samples': vir_typer_samples,
            'vir_typer_files': vir_files,
        })
Beispiel #59
0
def get_pdf(filename):
    html_file = "./html/{}.html".format(filename)
    pdf_file = "./pdf/{}.pdf".format(filename)
    HTML(html_file).write_pdf(pdf_file)
    print("Done")
Beispiel #60
0
from weasyprint import HTML
import logging

logging.basicConfig(level=logging.DEBUG)

URL = "http://tools.hde.nl/menc/site/guides/Pliss%C3%A9%20%26%20Duette%C2%AE%20Bottom-Up%20programming/"
OUT = "/home/admin-s/test.pdf"

for lp in range(0, 300):
    try:
        HTML(URL).write_pdf(OUT)
    except OSError as e:
        logging.exception(
            "**************** ERROR AT ATTEMPT: {} *******************".format(
                lp))
        break