Пример #1
0
 def print_buttom(self):
     vn = self.ViewName()
     render_pdf(url_for(vn, pk=str(self.id)))
     return Markup(
         '<a href="' + url_for(vn) +
         '" class="btn btn-sm btn-primary" data-toggle="tooltip" rel="tooltip"'
         + 'title="Print">' + '<i class="fa fa-edit"></i>' + '</a>')
Пример #2
0
    def test_pdf(self):
        client = app.test_client()
        response = client.get('/foo.pdf')
        assert response.status_code == 200
        assert response.mimetype == 'application/pdf'
        pdf = response.data
        assert pdf.startswith(b'%PDF')
        # The link is somewhere in an uncompressed PDF object.
        assert b'/URI (http://packages.python.org/Flask-WeasyPrint/)' in pdf

        with app.test_request_context('/foo/'):
            response = render_pdf(HTML(string=document_html()))
        assert response.mimetype == 'application/pdf'
        assert 'Content-Disposition' not in response.headers
        assert response.data == pdf

        with app.test_request_context('/foo/'):
            response = render_pdf(HTML(string=document_html()),
                                  download_filename='bar.pdf')
        assert response.mimetype == 'application/pdf'
        assert (response.headers['Content-Disposition'] ==
                'attachment; filename=bar.pdf')
        assert response.data == pdf

        with app.test_request_context('/foo/'):
            response = render_pdf(HTML(string=document_html()),
                                  download_filename='bar.pdf',
                                  automatic_download=False)
        assert response.mimetype == 'application/pdf'
        assert (response.headers['Content-Disposition'] ==
                'inline; filename=bar.pdf')
        assert response.data == pdf
Пример #3
0
def getRightResponse(form, imgUrl, imgTitle, imgExplanation):
    # checking what kind of output the user wanted either 'pdf' or 'webpage'

    # there are 2 layers if-elif-else statements
    # the first one decide btw. 'pdf' or 'webpage' and sends an error message
    # in case it's neither.
    # the second layer which is only present in the case of PDF from 1st layer
    # ^ check btw. with/without header&footer

    if form['outputType'] == 'pdf':  # user wants pdf
        # -- send pdf to front end in whatever format the user has asked for --

        # checking what kind of pdf the user wants
        if form['pdfType'] == 'yesBanner':
            # -- send with banner pdf --

            # get and store the with banner verion in html
            src = render_template('showImg.html',
                                  imgSrc=imgUrl,
                                  imgTitle=imgTitle,
                                  imgExplanation=imgExplanation)

            # convert to pdf and send
            return render_pdf(HTML(string=src))

        elif form['pdfType'] == 'noBanner':
            # -- send without banner pdf --

            # get and store the withOUT banner verion in html
            src = render_template('noHeader.html',
                                  imgSrc=imgUrl,
                                  imgTitle=imgTitle,
                                  imgExplanation=imgExplanation)

            # convert to pdf and send
            return render_pdf(HTML(string=src))

        # never trust the user's input / form data :-)
        else:
            flash('Error: pdftType can only be "yesBanner" or "noBanner".')
            return redirect(url_for('viewForm'))

    elif form['outputType'] == 'webpage':  # user wants webpage

        # send user the webpage
        return render_template('showImg.html',
                               imgSrc=imgUrl,
                               imgTitle=imgTitle,
                               imgExplanation=imgExplanation)

    # if any other kind of value has been sent, flash error
    # might happen in the case of an attacker trying to make an exploit
    # leaving aside the fact that this is just an APOD kind of API XD
    else:

        flash('Error: outputType can only be "pdf" or "webpage".')
        redirect(url_for('viewForm'))
Пример #4
0
def export_diary_by_date():
    user_name = request.form.get('user_name')
    date = request.form.get('date')
    if '-' in date:
        yyyy, mm, dd = date.split("-")
        date = mm + dd + yyyy
    file_location = DIARY_FOLDER + user_name + '/' + date + '.json'
    if not os.path.exists(file_location):
        return render_pdf(HTML(string="No diary entry for this day: %s" %
                               date))
    pdf_content = ''
    f = open(file_location)
    for l in f:
        pdf_content += l.rstrip()
    f.close()

    pdf_content = json.loads(pdf_content)
    html_content = '<h2>%s</h2>' % date
    for key in pdf_content:
        if key == 'content':
            html_content += '<p>%s</p>' % pdf_content[key]
    html_content += '<img class="diary_image" src="/static/photos/%s/%s.jpg" />' % (
        user_name, date)

    ## pdfkit method for exporting only works locally.
    ## does not work on pythonanywhere, since it requires wkhtmltopdf which cannot be installed without root
    # pdf = pdfkit.from_string(pdf_content, False) # pdfkit can also export from file and url. buggy not solved.
    #
    # print(pdf)
    # response = make_response(pdf)
    # response.headers["Content-Type"] = "application/pdf"
    # response.headers["Content-Disposition"] = "inline; filename=%s.pdf" % date
    # return response

    ## testing weasyprint
    # html = HTML(string='<h1>The title</h1>')
    html = HTML(string=html_content)
    css = CSS(string='''
        @font-face {
            font-family: Gentium;
            src: url(http://example.com/fonts/Gentium.otf);
        }
        h1 { font-family: Gentium }
        .diary_image { width: 100%; }
        ''')

    # html.write_pdf(
    #     '/tmp/example.pdf', stylesheets=[css])

    return render_pdf(html, stylesheets=[css])
Пример #5
0
def document_pdf():
	calc_id = 22
	query = "select id, timestamp, TipoC, h1, h2, d, b, L, Coh, roz, Dens, AcSis, TipoProt, DistCor, SH_B, SV_B, LongBulon, DiamAcero, Adh, fck, DiamPerf, FSI, FR, R1, R1Cumple, R2, R2Cumple, R1R2, R1R2Cumple, PNd,  P1, P1Cumple, P2, P2Cumple, P3, P3Cumple,FSfinal, FSfinalCumple from calculations where id = %s" % calc_id
	cur = db.session.execute(query)
	form = CalcForm()
	results = cur.fetchone()
	
	# reutilizamos el template de presentacion de resultados
	
	form.id.data = calc_id
	form.TipoC.data = results[2]
	form.h1.data= results[3]
	form.h2.data= results[4]
	form.d.data= results[5]
	form.b.data= results[6]
	form.L.data= results[7]
	form.Coh.data= results[8]
	form.Roz.data= results[9]
	form.Dens.data= results[10]
	form.AcSis.data= results[11]
	form.TipoProt.data= results[12]
	
	#html = render_template('core/calc_prot.html', TipoC = form.TipoC.data, TipoProt = "NetProtect", form=form,  method = "POST")

	html =render_template('core/test_pdf.html', TipoC = "C1" )
	print "Html ok"
	
	return render_pdf(HTML(string=html))
Пример #6
0
def view_report_pdf(report_id):
	# Find report
	consultation_report = ConsultationReport.query.get(report_id)
	if consultation_report is None:
		flash('This report could not be found.', 'error')
		return redirect(url_for('consultations.view_consultations'))

	# Load the consultation
	consultation = Consultation.query.get(consultation_report.consultation_id)
	if consultation is None:
		flash('This consultation could not be found.', 'error')
		return redirect(url_for('consultations.view_consultations'))

	# Load student and teacher
	student = User.query.get(consultation.student_id)
	teacher = User.query.get(consultation.teacher_id)

	if app.models.is_admin(current_user.username) or consultation.student_id == current_user.id:
		html = reference_pdf(
			consultation_report = consultation_report,
			consultation = consultation,
			student = student,
			teacher = teacher
		)
		return render_pdf (HTML(string=html))
	abort (403)
Пример #7
0
def collection(locale):

    form = toPDF_wrap(locale)()
    print(request.method)
    collection_ids = getCollection()
    collection = []
    custom_image_ids = []

    # Get pairs from session object
    for id in collection_ids:
        collection.append(Word.query.get(int(id)))

    custom_image_ids = custom_images_in_collection(collection)

    print(custom_image_ids)

    if request.method == "POST":
        if getCollection():
            if form.validate_on_submit():
                # Background file name is defined in the declaration of wtf choices in forms.py
                bgfilename = form.background.data
                template = render_template("mypdf.html", collection=collection)
                html = HTML(string=template, base_url=request.base_url)

                # This bit of CSS is dynamically generated, the rest is hard coded in the template
                css = CSS(
                    string=
                    '@page :left { background-image: url(/static/permaimages/'
                    + bgfilename + '.png);}')

                count_as_used(collection_ids)

                return render_pdf(html, stylesheets=[css])

    return render_template("collection.html", collection=collection, form=form)
Пример #8
0
def dash_pdf():
    dash_list = session.get('dash_list')
    vendor_name = session.get('vendor_name')
    html = render_template('dashboard_pdf.html',
                           dash_list=dash_list,
                           vendor_name=vendor_name)
    return render_pdf(HTML(string=html))
Пример #9
0
def pdf_case_report(institute_id, case_name):
    """Download a pdf report for a case"""

    institute_obj, case_obj = institute_and_case(store, institute_id,
                                                 case_name)
    data = controllers.case_report_content(store, institute_obj, case_obj)

    # add coverage report on the bottom of this report
    if current_app.config.get("SQLALCHEMY_DATABASE_URI"):
        data["coverage_report"] = controllers.coverage_report_contents(
            store, institute_obj, case_obj, request.url_root)

    # workaround to be able to print the case pedigree to pdf
    if case_obj.get("madeline_info") is not None:
        with open(os.path.join(cases_bp.static_folder, "madeline.svg"),
                  "w") as temp_madeline:
            temp_madeline.write(case_obj["madeline_info"])

    html_report = render_template(
        "cases/case_report.html",
        institute=institute_obj,
        case=case_obj,
        format="pdf",
        **data,
    )
    return render_pdf(
        HTML(string=html_report),
        download_filename=case_obj["display_name"] + "_" +
        datetime.datetime.now().strftime("%Y-%m-%d") + "_scout.pdf",
    )
Пример #10
0
def render_label_as_pdf():
    if request.method == 'POST':
        wine_label = request.form['wine-label']

        review_site = request.form['review-site']

        points = request.form['points']
        points_length = len(points)

        description = request.form['description']

        star = request.form['star']

        blank = request.form['blank']

        html = render_template('results.html',
                               wine_label=wine_label,
                               review_site=review_site,
                               points=points,
                               description=description,
                               star=star,
                               blank=blank,
                               points_length=points_length)

    return render_pdf(HTML(string=html))
Пример #11
0
def pdf():
    cartdetails, totalsum, product_pricing = getusercartdetails()
    html = render_template("pdf.html",
                           cartData=cartdetails,
                           totalsum=totalsum,
                           product_pricing=product_pricing)
    return render_pdf(HTML(string=html))
Пример #12
0
def inspection_report_pdf(room=None, date=None, inp_date_time=None):
    """ Make a PDF from inspection_report view """
    return render_pdf(
        url_for('inspection_report',
                room=room,
                date=date,
                inp_date_time=inp_date_time))
Пример #13
0
def panel_export(panel_id):
    """Export panel to PDF file"""
    panel_obj = store.panel(panel_id)
    data = controllers.panel_export(store, panel_obj)
    data['report_created_at'] = datetime.datetime.now().strftime("%Y-%m-%d")
    html_report = render_template('panels/panel_pdf_simple.html', **data)
    return render_pdf(HTML(string=html_report), download_filename=data['panel']['panel_name']+'_'+str(data['panel']['version'])+'_'+datetime.datetime.now().strftime("%Y-%m-%d")+'_scout.pdf')
Пример #14
0
def document_pdf():
    calc_id = 22
    query = "select id, timestamp, TipoC, h1, h2, d, b, L, Coh, roz, Dens, AcSis, TipoProt, DistCor, SH_B, SV_B, LongBulon, DiamAcero, Adh, fck, DiamPerf, FSI, FR, R1, R1Cumple, R2, R2Cumple, R1R2, R1R2Cumple, PNd,  P1, P1Cumple, P2, P2Cumple, P3, P3Cumple,FSfinal, FSfinalCumple from calculations where id = %s" % calc_id
    cur = db.session.execute(query)
    form = CalcForm()
    results = cur.fetchone()

    # reutilizamos el template de presentacion de resultados

    form.id.data = calc_id
    form.TipoC.data = results[2]
    form.h1.data = results[3]
    form.h2.data = results[4]
    form.d.data = results[5]
    form.b.data = results[6]
    form.L.data = results[7]
    form.Coh.data = results[8]
    form.Roz.data = results[9]
    form.Dens.data = results[10]
    form.AcSis.data = results[11]
    form.TipoProt.data = results[12]

    #html = render_template('core/calc_prot.html', TipoC = form.TipoC.data, TipoProt = "NetProtect", form=form,  method = "POST")

    html = render_template('core/test_pdf.html', TipoC="C1")
    print "Html ok"

    return render_pdf(HTML(string=html))
Пример #15
0
def pdf(sid,giveback=False):
    if sid == "None":
        student = models.Student()
        thepdf = render_template('leaps/admin/student_pdf', students=[student.data])
    elif sid == "selected":
        query = json.loads(request.values.get('q','{"query":{"match_all":{}}}'))
        selected = json.loads(request.values.get('selected','[]'))
        s = models.Student.query(q=query)
        students = []
        for i in s.get('hits',{}).get('hits',[]):
            if len(selected) == 0 or i['_source']['id'] in selected:
                students.append( i['_source'] )
        if len(students) == 0:
            abort(404)
        else:
            thepdf = render_template('leaps/admin/student_pdf', students=students)
    else:
        student = models.Student.pull(sid)
        if student is None:
            abort(404)
        else:
            thepdf = render_template('leaps/admin/student_pdf', students=[student.data])

    if giveback:
        return thepdf
    else:
        return render_pdf(HTML(string=thepdf))
Пример #16
0
def receipt(sdatetime, booking):

    bookingob = models.Booking.query.filter_by(id=booking).first()
    userid = bookingob.user_id
    user = models.User.query.filter_by(id=userid).first()
    useremail = user.email
    datebooked = bookingob.booking_time
    name = user.name
    endtime = bookingob.end_time
    starttime = bookingob.start_time

    # strdatetime = datetime.datetime.strptime(sdatetime,"%Y-%m-%dT%H:%M")
    duration = endtime - starttime
    duration_hours = duration.total_seconds() / 3600.0

    time = duration_hours
    numbikes = bookingob.bike_amount
    total = bookingob.cost

    html = render_template('receipt.html',
                           datebooked=datebooked,
                           booking=booking,
                           name=name,
                           useremail=useremail,
                           starttime=starttime,
                           endtime=endtime,
                           time=time,
                           numbikes=numbikes,
                           latefee=0,
                           total=total)

    return render_pdf(HTML(string=html))
Пример #17
0
def download_pdf(schema, eq_id, form_type):
    session_data = get_session_store().session_data

    if _is_submission_viewable(schema.json, session_data.submitted_time):
        submitted_data = data_access.get_by_key(SubmittedResponse,
                                                session_data.tx_id)

        if submitted_data:
            filename = '{}_{}.pdf'.format(eq_id, form_type)
            html = _render_submission_page(session_data, submitted_data,
                                           schema, eq_id, form_type)
            css = """
                .header__main {
                    background: none !important;
                }
                .header__title {
                    color: black !important;
                }
            """

            return render_pdf(HTML(string=html), [CSS(string=css)], filename)

    return redirect(
        url_for('post_submission.get_thank_you',
                eq_id=eq_id,
                form_type=form_type))
Пример #18
0
def endereco_acervo(cpf):
    global bearer_token
    data = get_data_requerimentos(cpf, bearer_token['access_token'])
    html = render_template('endereco_acervo.html',
                           data=data,
                           hoje=date.today())
    return render_pdf(HTML(string=html))
Пример #19
0
def mousereport_pdf(animal_id):
    html = mousereport(animal_id=animal_id)
    stylesheets = [
        CSS(url_for('static', filename='styles.css')),
        CSS(url_for('static', filename='datajoint.css'))
    ]
    return render_pdf(HTML(string=html), stylesheets=stylesheets)
Пример #20
0
def pdf(index, presentation):
    """Make a PDF from a presentation."""
    return render_pdf(
        url_for('presentation',
                action='view',
                index=index,
                presentation=presentation))
Пример #21
0
def report_12(mg_id):
    sam = SampleInfo.query.filter(SampleInfo.mg_id == mg_id).first()
    mutations = Mutation.query.filter(Mutation.mg_id == mg_id).all()

    req_mg = sam.req_mg
    path_rep = path.join(os.getcwd(), current_app.config['REPORT_FILE'],
                         req_mg)
    file_report = os.path.join(path_rep, '迈景基因检测报告_{}.pdf'.format(req_mg))
    mutation = []
    for mu in mutations:
        for tag in mu.tag:
            if '审核通过' in tag.name:
                mutation.append(mu)
    explanation = Explanation.query.filter(Explanation.mg_id == mg_id).all()
    html = render_template('report/base_pgm.html',
                           sam=sam,
                           mutation=mutation,
                           explanation=explanation)
    # return html
    # pdf = render_pdf(HTML(string=html))
    # HTML(string=html).write_pdf(file_report)
    #
    return render_pdf(HTML(string=html),
                      download_filename='{}.pdf'.format(req_mg),
                      automatic_download=True)
Пример #22
0
def index():
    id_variable = request.args.get('i', default=False, type=str)
    download = request.args.get('d', default=0, type=int)
    if id_variable:
        post = db.session.query(Invoice).filter_by(id=id_variable).all()
        output = json.loads(json.dumps(post, cls=AlchemyEncoder))
        items = literal_eval(post[0].items)

        html_text = render_template("invoice-template.html",
                                    post=post[0],
                                    items=items)
        if download:
            return render_pdf(
                HTML(string=html_text, base_url=""),
                download_filename="AndreaHasani-{}-{}.pdf".format(
                    post[0].type, post[0].id))
        else:
            return render_template("invoice-template.html",
                                   post=post[0],
                                   items=items)
    else:
        if current_user.is_authenticated:
            return redirect(url_for('dashboard'))
        else:
            return redirect(url_for('login'))
Пример #23
0
def reimbursements_pdf(code, invoice_year, invoice_quarter):
    practice = Practice.query.filter(Practice.code == code).first()

    q = Recruit.query.filter(Recruit.practice_code == code).filter(
        Recruit.invoice_year == invoice_year).filter(
            Recruit.invoice_quarter == invoice_quarter)

    participants = q.order_by(Recruit.recruited_date.asc()).all()

    totals = {
        'count': len(participants),
        'submitted':
        sum(1 for i in participants if i.reimbursed_status == 'Yes'),
        'excluded': sum(1 for i in participants if i.status == 'Excluded'),
        'value':
        sum(1 for i in participants if i.reimbursed_status == 'Yes') * 16,
    }

    html = render_template('practices/reimbursements/pdf.html',
                           participants=participants,
                           practice=practice,
                           invoice_year=invoice_year,
                           invoice_quarter=invoice_quarter,
                           totals=totals,
                           now=datetime.datetime.utcnow())
    return render_pdf(HTML(string=html))
Пример #24
0
def pdf_case_report(institute_id, case_name):
    """Download a pdf report for a case"""

    institute_obj, case_obj = institute_and_case(store, institute_id,
                                                 case_name)
    data = controllers.case_report_content(store, institute_obj, case_obj)

    # add coverage report on the bottom of this report
    if current_app.config.get('SQLALCHEMY_DATABASE_URI'):
        data['coverage_report'] = controllers.coverage_report_contents(
            store, institute_obj, case_obj, request.url_root)

    # workaround to be able to print the case pedigree to pdf
    if case_obj.get('madeline_info') is not None:
        with open(os.path.join(cases_bp.static_folder, 'madeline.svg'),
                  'w') as temp_madeline:
            temp_madeline.write(case_obj['madeline_info'])

    html_report = render_template('cases/case_report.html',
                                  institute=institute_obj,
                                  case=case_obj,
                                  format='pdf',
                                  **data)
    return render_pdf(HTML(string=html_report),
                      download_filename=case_obj['display_name'] + '_' +
                      datetime.datetime.now().strftime("%Y-%m-%d") +
                      '_scout.pdf')
Пример #25
0
 def pdf_view(self):
     inst_id = request.args.get('id', '')
     inst = self.model.query.filter(self.model.id == inst_id).first()
     extra = {'name': inst.instoreCategory}
     return render_pdf(
         HTML(string=self._view_handler(self.pdf_template, inst_id, True, **
                                        extra)))
Пример #26
0
def workshops():
    if request.method == 'GET':
        printparam  = request.args.get('print')
        if printparam:
            n = 0
            html = render_template('printregistrationdetails.html',
            enumerate=enumerate,len=len,utc_to_local=utc_to_local,
            datetime=datetime,workshops=app.config['WORKSHOPS'],page="workshops")
            return render_pdf(HTML(string=html))

        return render_template('workshops.html',workshops=app.config['WORKSHOPS'],page="workshops")
    else:
        register = request.form.get('register')
        unregister = request.form.get('unregister')
        #app.logger.info('Unregister: {}'.format(unregister))
        if register:
            if register+'_registered' in User.__dict__:
                if g.user.__dict__[register+'_registered'] == False:
                    setattr(g.user,register+'_registered',True)
                    setattr(g.user,register+'_registered_on',datetime.datetime.utcnow())
                    db.session.commit()
            
        elif unregister:
            if unregister+'_registered' in User.__dict__:
                if g.user.__dict__[unregister+'_registered'] == True:
                    setattr(g.user,unregister+'_registered',False)
                    setattr(g.user,unregister+'_registered_on',None)
                    db.session.commit()

        return render_template('workshops.html',workshops=app.config['WORKSHOPS'],page="workshops")
Пример #27
0
def panel_export(panel_id):
    """Export panel to PDF file"""
    panel_obj = store.panel(panel_id)
    data = controllers.panel_export(store, panel_obj)
    data['report_created_at'] = datetime.datetime.now().strftime("%Y-%m-%d")
    html_report = render_template('panels/panel_pdf_simple.html', **data)
    return render_pdf(HTML(string=html_report), download_filename=data['panel']['panel_name']+'_'+str(data['panel']['version'])+'_'+datetime.datetime.now().strftime("%Y-%m-%d")+'_scout.pdf')
Пример #28
0
def generate_pdf(version=None):
    import StringIO
    from flask_weasyprint import HTML, render_pdf

    now = datetime.datetime.now().strftime('%d.%m.%Y');

    #users = models.Aasi.query.all()

    # fetch the latest print_version from the database
    latest = db.session.query(db.func.max(models.Aasi.print_version)).one()[0]

    if version == None or version == 0:
        # if no version parameter given, print all
        users = models.Aasi.query.filter_by(verified=True)
    elif int(version) <= latest:
        # otherwise fetch older print versions and create the pdf
        users = models.Aasi.query.filter_by(verified=True, print_version=int(version))
    else:
        # else, get all the unprinted ones and append their version
        users = models.Aasi.query.filter_by(verified=True, print_version=0)

        for user in users:
            user.print_version = latest+1
            db.session.add(user)
        db.session.commit()

        # TODO: find a way to refresh the session?
        users = models.Aasi.query.filter_by(verified=True, print_version=latest+1)

    html = render_template('piikki.html', users=users, now=now)

    return render_pdf(HTML(string=html))
Пример #29
0
def pdf_clases():  # flag de generar pdf
    """
    Listado de personas
    """
    check_edit_or_admin()

    roles = db.session.query(Rol).filter(Rol.tipo_rol == 'C')\
                                 .join(relacion_miembros_roles,
                                       relacion_miembros_roles.c.id_rol ==
                                       Rol.id)\
                                 .join(Miembro,
                                       Miembro.id ==
                                       relacion_miembros_roles.c.id_miembro)\
                                 .add_columns(
                                     Miembro.id,
                                     Rol.nombre_rol)

    query = db.session.query(Miembro)\
                      .outerjoin(relacion_miembros_roles,
                                 Miembro.id ==
                                 relacion_miembros_roles.c.id_miembro)\
                      .outerjoin(Rol,
                                 Rol.id ==
                                 relacion_miembros_roles.c.id_rol)\
                      .outerjoin(Direccion,
                                 Miembro.id_direccion ==
                                 Direccion.id)\
                      .outerjoin(TipoMiembro,
                                 Miembro.id_tipomiembro ==
                                 TipoMiembro.id)\
                      .outerjoin(EstadoCivil,
                                 Miembro.id_estadocivil ==
                                 EstadoCivil.id)\
                      .filter(Rol.tipo_rol == 'C')\
                      .add_columns(
                              Miembro.id,
                              Miembro.fullname,
                              Miembro.email,
                              Miembro.telefono_fijo,
                              Miembro.telefono_movil,
                              EstadoCivil.nombre_estado,
                              TipoMiembro.nombre_tipomiembro,
                              Direccion.tipo_via,
                              Direccion.nombre_via,
                              Direccion.nro_via,
                              Direccion.portalescalotros_via,
                              Direccion.cp_via,
                              Direccion.ciudad_via,
                              Direccion.provincia_via,
                              Direccion.pais_via)

    query_miembros = query.all()

    from flask_weasyprint import HTML, render_pdf

    salida = render_template('informes/pdf_clases.html',
                             informes=query_miembros,
                             roles=roles)

    return render_pdf(HTML(string=salida))
Пример #30
0
def show_report(uuid):
    REPORTS = {
        "students":
        lambda report: report.teacher.students.filter_by(is_active=True).join(
            User, Student.user).order_by(User.name.asc()),
        "lessons":
        lambda report: report.teacher.lessons.filter(
            and_(
                Appointment.is_approved == True,
                Appointment.date < report.until,
                Appointment.date > report.since,
            )),
        "kilometers":
        lambda report: report.teacher.kilometers.filter(
            and_(
                Kilometer.date < report.until,
                Kilometer.date > report.since,
                Kilometer.car == report.car,
            )),
    }
    report = Report.query.filter_by(uuid=uuid).first()
    if not report:
        raise RouteError("Report was not found.")
    report_data = REPORTS.get(report.report_type.name)
    html = flask.render_template(
        f"reports/{report.report_type.name}.html",
        data=report_data(report).all(),
        teacher=report.teacher,
        report=report,
    )
    return render_pdf(HTML(string=html))
Пример #31
0
def paperpdf():

    exp_length = 30

    currency_amount = 5.00
    currency_type = 'USD'
    crypto_currency = 'NANO'
    nano_amount = modules.currency.get_fiat_conversion(currency_type, crypto_currency, currency_amount)

    if currency_type == 'USD':
        currency_mark = '$'
    elif currency_type == 'EUR':
        currency_mark = u"\u20AC"
    else:
        currency_mark = u"\u00A3"

    gen_date = datetime.now().strftime("%b %d, %y")
    exp_date = (datetime.now() + timedelta(days=exp_length)).strftime("%b %d, %y")
    nano_price = modules.currency.get_fiat_price(currency_type, crypto_currency)
    qr_img = "papertipqr.png"
    qr_link = "https://nanotipbot.com/tips/iaoi4fat-haa-32aaa"
    num_tip = 12

    html = render_template('papertip.html', nano_amount=nano_amount, currency_mark=currency_mark,
                           currency_amount=currency_amount, gen_date=gen_date, exp_date=exp_date, nano_price=nano_price,
                           qr_img=qr_img, qr_link=qr_link, num_tip=num_tip, currency=CURRENCY)

    return render_pdf(HTML(string=html))
Пример #32
0
def scanreport_pdf(animal_id, session, scan_idx):
    html = scanreport(animal_id=animal_id, session=session, scan_idx=scan_idx)
    stylesheets = [
        CSS(url_for('static', filename='styles.css')),
        CSS(url_for('static', filename='datajoint.css'))
    ]
    return render_pdf(HTML(string=html), stylesheets=stylesheets)
 def get_certificate(user_id):
     user = userservice.check_hackers(user_id)
     if user is None:
         return 'Sorry but you have not participated devsummit'
     mail_template = EmailHackaton("devsummit-hackathon-certificate.html")
     mail_template = mail_template.build(user.first_name + ' ' + user.last_name)
     return render_pdf(HTML(string=mail_template))
Пример #34
0
def get_patient_admission_discharge_summary_pdf(patient_id, admission_id):
    query = md.Admission.query\
        .filter(md.Admission.patient_id == patient_id)\
        .filter(md.Admission.id == admission_id)\
        .filter(md.Admission.end_time != None)

    admission = query.first()

    if admission is None:
        return errors.resource_not_found("Item with not found.")

    return render_pdf(
        HTML(
            string=render_template(
                'admission/discharge-summary.html',
                admission=admission
            )
        ),
        stylesheets=[
            CSS(
                string=render_template(
                    'admission/discharge-summary.css'
                )
            )
        ]
    )
Пример #35
0
def render_report(story):
    data = Parser(story)
    results = data.receive()
    html = render_template('page.html',
                           story=story,
                           results=results)
    return render_pdf(HTML(string=html))
Пример #36
0
def confirm_pdf(booking_id):
    booking = Book.query.get(booking_id)
    journey = Journey.query.get(booking.journey_id)
    from_city = City.query.get(journey.from_city_id)
    to_city = City.query.get(journey.to_city_id)
    flight = Flight.query.get(journey.flight_id)
    html = render_template('pdf.html', booking = booking,journey=journey,from_city=from_city,to_city=to_city,flight=flight)
    return render_pdf(HTML(string=html))
Пример #37
0
def new():
    if request.method == 'GET':
        return render_template('new.invoice.html')

    name = request.form['name']
    html = render_template('invoice.pdf.html', name=name)
    #return html
    return render_pdf(HTML(string=html))
Пример #38
0
def export_project_pdf(project_id):
    '''
    Make a PDF straight from HTML in a string and send it to the user.
    '''
    html = ''
    for value in generate(project_id):
        html += value
    return render_pdf(HTML(string=html))
Пример #39
0
    def printable(pid):
        profile = manager.db.profile.get(pid)
        qr_string = "WIFI:S:%s;T:WPA;P:%s" % (profile.ssid, profile.psk)
        if profile is None:
            flask.flash('Network disappeared in the meantime.', 'warning')
            return flask.redirect('/')

        html = flask.render_template('printable.html', **locals())
        return render_pdf(HTML(string=html))
Пример #40
0
def generate_pdf_flask_response(pdf_data):
    """
    Return a Flask response object with a PDF as an attachment.
    :param pdf_data: String of data to input into PDF.
    :return: Flask Response
    """
    html = HTML(string=pdf_data)

    return render_pdf(html)
Пример #41
0
def report_to_pdf():
    chatroom = request.args.get('chatroom')
    begin_date = request.args.get('begin_date')
    end_date = request.args.get('end_date')
    
    return render_pdf(url_for('report_to_html',
                              chatroom=chatroom,
                              begin_date=begin_date,
                              end_date=end_date))
Пример #42
0
def spielerZettel(runde, begegnungen):
    from flask_weasyprint import HTML, render_pdf

    l = begegnungen.split('!')

    now = datetime.now().strftime("%d.%m.%Y")
    html = render_template('spieler_zettel.html', begegnungen=zip(l[0::2], l[1::2]),
                           runde=runde, date=now, tables=_Counter())
    return render_pdf(HTML(string=html), download_filename='begegnungen_runde{}.pdf'.format(runde))
def display_title_pdf(title_number):
    title = _get_register_title(title_number)
    if title:
        full_title_data = api_client.get_official_copy_data(title_number)
        if full_title_data:
            sub_registers = full_title_data.get('official_copy_data', {}).get('sub_registers')
            if sub_registers:
                html = _create_pdf_template(sub_registers, title, title_number)
                return render_pdf(HTML(string=html))
    abort(404)
Пример #44
0
def pdf (calc_id=1):

	
	query = "select id, timestamp, TipoC, h1, h2, d, b, L, Coh, roz, Dens, AcSis, TipoProt, DistCor, SH_B, SV_B, LongBulon, DiamAcero, Adh, fck, DiamPerf, FSI, FR, R1, R1Cumple, R2, R2Cumple, R1R2, R1R2Cumple, PNd,  P1, P1Cumple, P2, P2Cumple, P3, P3Cumple,FSfinal, FSfinalCumple from calculations where id = %s" % calc_id
	cur = db.session.execute(query)
	
	
	# reutilizamos el template de presentacion de resultados
	
	form = CalcForm()
	
	results = cur.fetchone()
	
	form.id.data = calc_id
	form.TipoC.data = results[2]
	form.h1.data= results[3]
	form.h2.data= results[4]
	form.d.data= results[5]
	form.b.data= results[6]
	form.L.data= results[7]
	form.Coh.data= results[8]
	form.Roz.data= results[9]
	form.Dens.data= results[10]
	form.AcSis.data= results[11]
	form.TipoProt.data= results[12]
	form.DistCor.data= results[13]
	form.SH_B.data= results[14]
	form.SV_B.data= results[15]
	form.LongBulon.data= results[16]
	form.DiamAcero.data= results[17]
	form.Adh.data= results[18]
	form.fck.data= results[19]
	form.DiamPerf.data= results[20]
	form.FSI.data= results[21]
	form.FR.data= results[22]
	form.R1.data= results[23]
	form.R1Cumple.data= results[24]
	form.R2.data= results[25]
	form.R2Cumple.data= results[26]
	form.R1R2.data= results[27]
	form.R1R2Cumple.data= results[28]
	form.PNd.data= results[29]
	form.P1.data= results[30]
	form.P1Cumple.data= results[31]
	form.P2.data= results[32]
	form.P2Cumple.data= results[33]
	form.P3.data= results[34]
	form.P3Cumple.data= results[35]
	form.FSfinal.data= results[36]
	form.FSfinalCumple.data= results[37]
	
	html =render_template('core/report.html', form=form )
	
	return render_pdf(HTML(string=html))
Пример #45
0
	def render(self) :
		html = HTML(string = render_template(
				self.template,
				user = self.user,
				all_courses = self.courses
			),
			encoding = Config.encoding
		)
		css = [ CSS(url_for("static", filename = "css/bootstrap.min.css")) ]
		doc = render_pdf(html, stylesheets = css, download_filename = self.filename.encode(Config.encoding))
		return doc
Пример #46
0
def getpdf(sid):
    school = current_user.is_school
    
    student = models.Student.pull(sid)
    if student is None:
        abort(404)
    elif student.data['status'] in ["new","awaiting_interview","absent"] and (current_user.is_super or current_user.do_admin or student.data['school'] == school):
        thepdf = pdf(sid,True)
        return render_pdf(HTML(string=thepdf))
    else:
        abort(401)
Пример #47
0
def pdf():
    data_dict = request.form if request.method == 'POST' else request.args
    # make a PDF from another view
    response = render_pdf(url_for('report.report', **data_dict))

    # check if the request is to download the file right away
    if 'dl' in request.args:
        fname = 'coverage-report.pdf'
        header = "attachment; filename={}".format(fname)
        response.headers['Content-Disposition'] = header

    return response
Пример #48
0
def bid_create_pdf(bid_id_pdf, save_to_disk):
    bid = Bid.query.get(bid_id_pdf)
    address = Address.query.get(bid.address_id)
    customer = Customer.query.get(address.customer_id)
    html = render_template('bid_pdf.html',
                           bid_id=bid_id_pdf,
                           sum_of_items=sum_all_items_one_bid(bid_id_pdf),
                           items=query_one_bid_items(bid_id_pdf),
                           bid=query_bid(bid_id_pdf),
                           bid_time=datetime.datetime.now(pytz.timezone('US/Central')).strftime('%x'),
                           address=address,
                           customer=customer)
    if save_to_disk:
        # useful path examples http://stackoverflow.com/questions/5137497/find-current-directory-and-files-directory

        # Set appropriate slash depending on OS
        if os.name =='nt':
            base_dir = "{}\\{}".format(os.getcwd(), 'customer_data')
        else:
            base_dir = "{}/{}".format(os.getcwd(), 'customer_data')

        # Escape illegal directory path characters and replace with underscore
        customer_name = customer.name
        for character in ['<', '>', ':', '"', '/', '\\', '|', '?', '*', ' ']:
            if character in customer_name:
                customer_name = customer_name.replace(character, "_")

        # Set appropriate slash depending on OS
        if os.name =='nt':
            customer_folder = "{}_{}\\".format(customer_name, customer.id)
        else:
            customer_folder = "{}_{}/".format(customer_name, customer.id)

        # Create the directory path
        directory = os.path.join(base_dir, customer_folder)

        # Create directory if it doesnt exist
        if not os.path.isdir(directory):
            os.makedirs(directory)

        # Combine generate filename and combine with path
        current_date = datetime.datetime.now(pytz.timezone('US/Central')).strftime('%Y%m%d%H%M')
        filename = "{}_{}.pdf".format(customer_name, current_date)
        path = directory + filename

        # Create pdf and store it on server
        HTML(string=html).write_pdf(path)

        flash("The bid was saved to hard disk")
        return redirect(url_for('bid.bid_edit', bid_edit_id=bid.id))

    #return html
    return render_pdf(HTML(string=html))
Пример #49
0
def pdf(sid,giveback=False):
    if sid == "None":
        student = models.Student()
        thepdf = render_template('leaps/admin/student_pdf', students=[student.data])
    elif sid == "selected":
        query = json.loads(request.values.get('q','{"query":{"match_all":{}}}'))
        selected = json.loads(request.values.get('selected','[]'))
        s = models.Student.query(q=query)
        students = []
        for i in s.get('hits',{}).get('hits',[]):
            if len(selected) == 0 or i['_source']['id'] in selected:
                if not i['_source'].get('simd_pc',False):
                    if i['_source']['simd_decile'] == 'unknown':
                        i['_source']['simd_pc'] = 'unknown'
                    else:
                        try:
                            dec = int(i['_source'].get('simd_decile',0))
                            if dec == 10 and int(i['_source'].get('simd_quintile',0)) == 5:
                                dec = 100
                            elif dec < 10:
                                dec = dec * 10
                            i['_source']['simd_pc'] = str(dec)
                        except:
                            i['_source']['simd_pc'] = 'unknown'
                students.append( i['_source'] )
        if len(students) == 0:
            abort(404)
        else:
            thepdf = render_template('leaps/admin/student_pdf', students=students)
    else:
        student = models.Student.pull(sid)
        if student is None:
            abort(404)
        else:
            if not student.data.get('simd_pc',False):
                if student.data['simd_decile'] == 'unknown':
                    student.data['simd_pc'] = 'unknown'
                else:
                    try:
                        dec = int(student.data.get('simd_decile',0))
                        if dec == 10 and int(student.data.get('simd_quintile',0)) == 5:
                            dec = 100
                        elif dec < 10:
                            dec = dec * 10
                        student.data['simd_pc'] = str(dec)
                    except:
                        student.data['simd_pc'] = 'unknown'
            thepdf = render_template('leaps/admin/student_pdf', students=[student.data])

    if giveback:
        return thepdf
    else:
        return render_pdf(HTML(string=thepdf))
Пример #50
0
def pdf(group_id):
    data_dict = request.form if request.method == "POST" else request.args

    # make a PDF from another view
    response = render_pdf(url_for("report.report", group_id=group_id, **data_dict))

    # check if the request is to download the file right away
    if "dl" in request.args:
        fname = "coverage-report_{}.pdf".format(group_id)
        header = "attachment; filename={}".format(fname)
        response.headers["Content-Disposition"] = header

    return response
Пример #51
0
def bid_create_receipt(bid_id_pdf):
    bid = Bid.query.get(bid_id_pdf)
    address = Address.query.get(bid.address_id)
    customer = Customer.query.get(address.customer_id)
    html = render_template('receipt_pdf.html',
                           bid_id=bid_id_pdf,
                           sum_of_items=sum_all_items_one_bid(bid_id_pdf),
                           items=query_one_bid_items(bid_id_pdf),
                           bid=query_bid(bid_id_pdf),
                           bid_time=datetime.datetime.now(pytz.timezone('US/Central')).strftime('%x'),
                           address=address,
                           customer=customer)
    return render_pdf(HTML(string=html))
Пример #52
0
def download():
    # Get report
    report = renderRequest(request)
    # turn Flask rendered response into WeasyPrint HTML Object
    report = HTML(string = report)
    # render html object into PDF
    report = render_pdf(report)
    # Return pdf as download attachment  w/ cookie - for use with the jquery.FileDownload plugin
    response = make_response(report)
    response.headers["Content-Disposition"] = "attachment; filename=town_profile.pdf"
    response.headers["Set-Cookie"] = "fileDownload=true; path=/"

    return response
Пример #53
0
def pdf(route, filter_id):
  # make a PDF from another view
  if route in ('samples', 'groups'):
    response = render_pdf(url_for("report.{}".format(route),
                          filter_id=filter_id))
  else:
    return abort(404)

  # check if the request is to download the file right away
  if 'dl' in request.args:
    fname = "coverage-report_{}.pdf".format(filter_id)
    response.headers['Content-Disposition'] = 'attachment; filename=' + fname

  return response
Пример #54
0
    def test_pdf(self):
        client = app.test_client()
        response = client.get('/foo.pdf')
        assert response.status_code == 200
        assert response.mimetype == 'application/pdf'
        pdf = response.data
        assert pdf.startswith(b'%PDF')
        # The link is somewhere in an uncompressed PDF object.
        assert b'/URI (http://packages.python.org/Flask-WeasyPrint/)' in pdf

        with app.test_request_context('/foo/'):
            response = render_pdf(HTML(string=document_html()))
        assert response.mimetype == 'application/pdf'
        assert 'Content-Disposition' not in response.headers
        assert response.data == pdf

        with app.test_request_context('/foo/'):
            response = render_pdf(HTML(string=document_html()),
                                  download_filename='bar.pdf')
        assert response.mimetype == 'application/pdf'
        assert (response.headers['Content-Disposition']
                == 'attachment; filename=bar.pdf')
        assert response.data == pdf
Пример #55
0
def export_notes():
    '''
    GET request returns the notes associated with this photo in pdf form.
    '''
    if request.method == 'POST':
        return 'Bad request', 400

    id = request.args.get('id')

    photo = get_photo_from_id(id)
    tmp = render_template('notes.html', notes=Markup(photo.notes))

    response = render_pdf(HTML(string=tmp), download_filename='notes.pdf')

    return response
Пример #56
0
def termin_pdf(termin_id):

	termin = Termin.query.get(termin_id)
	abort(404) if termin is None else False
	

	zoznam=[]
	for student_terminu in termin.prihlaseni_studenti:
	 	sp = Student_predmet.query.filter_by(student=student_terminu.student,predmet=termin.predmet).first()
	 	zoznam.append(sp)

	# Make a PDF straight from HTML in a string.
	html = render_template('ucitel/template_pre_pdf.html',
		prihlaseni_studenti=zoznam)
	return render_pdf(HTML(string=html))
Пример #57
0
 def get(self): 
      #se obtiene los datos de post del server
     idProyecto=flask.request.args.get('idProyecto', '')
     
     if idProyecto=='' or idProyecto == None:
         return
     idProyecto=int(idProyecto)
     #html=self.getHead()
     html=''
     html="<table><tr><td><div><img src='/static/images/blue-23957_640.png' width='150px'/></div></td><td>"
     html=html+"<h3>Informe de Solicitudes de Cambio</h3></tr>"
     proyecto=sesion.query(Proyecto).filter(Proyecto.idProyecto==idProyecto).first()
     lider=sesion.query(Usuario).join(Proyecto).filter(Usuario.id==Proyecto.projectLeaderId).first()
     html=html+"<tr><td><h4>Proyecto:    "+proyecto.nombreProyecto+"</h4></td><td><h4> Lider:    "+lider.username+  "</h4></td></tr></table>"
     solicitudes=sesion.query(SolicitudCambio).filter(SolicitudCambio.idProyecto==idProyecto).all()
     for solicitud in solicitudes:
         
         
         
         html=html+"<div><hr></hr></div>"
         html=html+"<div><table>"
         html=html+"<tr><td><h5>Solicitud: "+solicitud.descripcion+"</h5></td><td><h5>Estado: "+solicitud.estado+"</h5></td></tr>"
         solicitante=sesion.query(Usuario).filter(Usuario.id==solicitud.idSolicitante).first()
         html=html+"<tr><td><h5>Solicitante: "+solicitante.apellidos+", "+solicitante.nombres+" ["+solicitante.username+"]</h5></td></tr>"
         votos=sesion.query(Voto).filter(Voto.solicitud==solicitud.id).all()
         html=html+"<tr><td><h5>Votantes:</h5></td></tr>"
         html=html+"</table></div>"
         html=html+"<div><table>"
         for voto in votos:
             votante=sesion.query(Usuario).filter(Usuario.id==voto.votante).first()
             html=html+"<tr><td><p>Votante: "+votante.apellidos+", "+votante.nombres+" ["+votante.username+"]</p></td>"
             elVoto=''
             if voto.voto=="si":
                 elVoto="Aprobar"
             elif voto.voto=="no":
                 elVoto="Rechazar"
             elif voto.voto=="p":
                 elVoto="Pendiente"
             html=html+"<td>_____</td><td><p>Voto:   "+elVoto+"</p><td></tr> "
         html=html+"</table></div>"
         lbRotas=sesion.query(LineaBase).filter(LineaBase.scAfecto==solicitud.id).all()
         html=html+"<div><table>"
         html=html+"<tr><td><h5>Linea/s Base/s Afectada/s</h5></td></tr>"
         for lb in lbRotas:
             fase=sesion.query(Fase).filter(Fase.idFase==lb.idFase).first()
             html=html+"<tr><td><p>Fase: "+fase.tag+"____Linea Base: "+lb.descripcion+"</p></td>"
         html=html+"</table></div>"
     return render_pdf(HTML(string=html))
Пример #58
0
	def render(style, otype=None):
		otype = otype or request.args.get('type', 'html')
		source = request.args.get('source')

		if source:
			parent = p.dirname(p.dirname(__file__))
			path = p.join(parent, source)
			stream = file(path, 'r')
			items = yaml.safe_load(stream).items()
			[setattr(g, k, v) for k, v in items]

		if otype.startswith('html'):
			html = render_template('%s.html' % style).replace('<table>', table)
			html_doc = HTML(string=html)
			stylesheets = find_stylesheets(
				html_doc.root_element,
				html_doc.media_type,
				html_doc.url_fetcher,
			)
			urls = [sheet.base_url for sheet in stylesheets]
			style_urls = filter(lambda x: x.endswith('css'), urls)
			styles = _get_styles(app, style_urls)
			kwargs = {'styles': styles}

			if source:
				[setattr(g, k, v) for k, v in items]

			return render_template('%s.html' % style, **kwargs).replace(
				'<table>', table)
		elif otype.startswith('md'):
			h = html2text.HTML2Text()
			# h.ignore_links = True
			h.ignore_emphasis = True
			h.body_width = 65
			return h.handle(render_template('%s.html' % style))
		elif otype.startswith('pdf'):
			kwargs = {'to_print': True}
			return render_pdf(url_for('index', style=style))
		elif otype.startswith('png'):
			kwargs = {'to_print': True}
			html = render_template('%s.html' % style, **kwargs).replace(
				'<table>', table)
			html_doc = HTML(string=html)
			return Response(html_doc.write_png(), mimetype='image/png')
		else:
			pass
Пример #59
0
def pdf_case_report(institute_id, case_name):
    """Download a pdf report for a case"""

    institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
    data = controllers.case_report_content(store, institute_obj, case_obj)

    # add coverage report on the bottom of this report
    if current_app.config.get('SQLALCHEMY_DATABASE_URI'):
        data['coverage_report'] = controllers.coverage_report_contents(store, institute_obj, case_obj, request.url_root)

    # workaround to be able to print the case pedigree to pdf
    if case_obj.get('madeline_info') is not None:
        with open(os.path.join(cases_bp.static_folder, 'madeline.svg'), 'w') as temp_madeline:
            temp_madeline.write(case_obj['madeline_info'])

    html_report = render_template('cases/case_report.html', institute=institute_obj, case=case_obj, format='pdf', **data)
    return render_pdf(HTML(string=html_report), download_filename=case_obj['display_name']+'_'+datetime.datetime.now().strftime("%Y-%m-%d")+'_scout.pdf')