def generate_pdf(pdf_data): """ Generate a PDF from a string of data. :param pdf_data: String of data to input into PDF. :return: PDF File object """ html = HTML(string=pdf_data) f = html.write_pdf() return f
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
def create_pdf_for_diagram_for_user(username, from_date, to_date): available_images = plotter.get_diagram_json(username, from_date, to_date) now = datetime.datetime.now() date = now.strftime("%Y%m%d-%H%M") html = render_template('diagram_pdf_template.html', available_images=available_images, actual_user=username, from_date=from_date, to_date=to_date) return render_pdf(HTML(string=html), download_filename=username + "_diagram_" + from_date + "-" + to_date + "_" + date + ".pdf")
def confirma(minimo, maximo, nome): servidores = Servidor.query.filter_by(usuario_id=current_user.id, nome=nome) servidor_id = servidores.value('id') dados = Dados.query.filter_by(usuario_id=current_user.id, servidor_id=servidor_id) html = render_template('impressao_faixa.html', minimo=float(minimo), maximo=float(maximo), dados=dados, servidores=servidores) return render_pdf(HTML(string=html))
def generate_pdf(): invoice = Invoice.query.filter_by(id=4).first() client = Client.query.filter_by(id=2).first() service = Service.query.filter_by(client_id=client.id).first() html = render_template('invoice-templates/template.html', invoice=invoice, client=client, service=service, name=invoice.invoice_no) pdf = HTML(string=html).write_pdf() if Config.INVOICE_FOLDER: f = open(Config.INVOICE_FOLDER + invoice.invoice_no + '.pdf', 'wb') f.write(pdf) return url_for('main.invoices')
def pdf(enquiry_id): """ 文件下载 :param enquiry_id: :return: """ enquiry_info = get_enquiry_row_by_id(enquiry_id) # 检查资源是否存在 if not enquiry_info: abort(404) # 检查资源是否删除 if enquiry_info.status_delete == STATUS_DEL_OK: abort(410) enquiry_print_date = time_utc_to_local( enquiry_info.update_time).strftime('%Y-%m-%d') enquiry_code = '%s%s' % ( g.ENQUIRIES_PREFIX, time_utc_to_local( enquiry_info.create_time).strftime('%y%m%d%H%M%S')) # 获取客户公司信息 supplier_info = get_supplier_row_by_id(enquiry_info.supplier_cid) # 获取客户联系方式 supplier_contact_info = get_supplier_contact_row_by_id( enquiry_info.supplier_contact_id) # 获取询价人员信息 user_info = get_user_row_by_id(enquiry_info.uid) enquiry_items = get_enquiry_items_rows(enquiry_id=enquiry_id) # 文档信息 document_info = DOCUMENT_INFO.copy() document_info['TITLE'] = _('enquiry edit') template_name = 'enquiry/pdf.html' html = render_template(template_name, enquiry_id=enquiry_id, enquiry_info=enquiry_info, supplier_info=supplier_info, supplier_contact_info=supplier_contact_info, user_info=user_info, enquiry_items=enquiry_items, enquiry_print_date=enquiry_print_date, enquiry_code=enquiry_code, **document_info) # return html return render_pdf( html=HTML(string=html), stylesheets=[CSS(string='@page {size:A4; margin:35px;}')], download_filename='询价单.pdf'.encode('utf-8'))
def pdf(delivery_id): """ 文件下载 :param delivery_id: :return: """ delivery_info = get_delivery_row_by_id(delivery_id) # 检查资源是否存在 if not delivery_info: abort(404) # 检查资源是否删除 if delivery_info.status_delete == STATUS_DEL_OK: abort(410) delivery_print_date = time_utc_to_local( delivery_info.update_time).strftime('%Y-%m-%d') delivery_code = '%s%s' % ( g.ENQUIRIES_PREFIX, time_utc_to_local( delivery_info.create_time).strftime('%y%m%d%H%M%S')) # 获取客户公司信息 customer_info = get_customer_row_by_id(delivery_info.customer_cid) # 获取客户联系方式 customer_contact_info = get_customer_contact_row_by_id( delivery_info.customer_contact_id) # 获取出货人员信息 user_info = get_user_row_by_id(delivery_info.uid) delivery_items = get_delivery_items_rows(delivery_id=delivery_id) # 文档信息 document_info = DOCUMENT_INFO.copy() document_info['TITLE'] = _('delivery pdf') template_name = 'delivery/pdf.html' html = render_template(template_name, delivery_id=delivery_id, delivery_info=delivery_info, customer_info=customer_info, customer_contact_info=customer_contact_info, user_info=user_info, delivery_items=delivery_items, delivery_print_date=delivery_print_date, delivery_code=delivery_code, **document_info) # return html return render_pdf( html=HTML(string=html), stylesheets=[CSS(string='@page {size:A4; margin:35px;}')], download_filename='销售出货.pdf'.encode('utf-8'))
def pdf(purchase_id): """ 文件下载 :param purchase_id: :return: """ purchase_info = get_purchase_row_by_id(purchase_id) # 检查资源是否存在 if not purchase_info: abort(404) # 检查资源是否删除 if purchase_info.status_delete == STATUS_DEL_OK: abort(410) purchase_print_date = time_utc_to_local( purchase_info.update_time).strftime('%Y-%m-%d') purchase_code = '%s%s' % ( g.ENQUIRIES_PREFIX, time_utc_to_local( purchase_info.create_time).strftime('%y%m%d%H%M%S')) # 获取渠道公司信息 supplier_info = get_supplier_row_by_id(purchase_info.supplier_cid) # 获取渠道联系方式 supplier_contact_info = get_supplier_contact_row_by_id( purchase_info.supplier_contact_id) # 获取进货人员信息 user_info = get_user_row_by_id(purchase_info.uid) purchase_items = get_purchase_items_rows(purchase_id=purchase_id) # 文档信息 document_info = DOCUMENT_INFO.copy() document_info['TITLE'] = _('purchase pdf') template_name = 'purchase/pdf.html' html = render_template(template_name, purchase_id=purchase_id, purchase_info=purchase_info, supplier_info=supplier_info, supplier_contact_info=supplier_contact_info, user_info=user_info, purchase_items=purchase_items, purchase_print_date=purchase_print_date, purchase_code=purchase_code, **document_info) # return html return render_pdf( html=HTML(string=html), stylesheets=[CSS(string='@page {size:A4; margin:35px;}')], download_filename='销售出货.pdf'.encode('utf-8'))
def pdf_template(patient_id, upload_id): form = PatientsForm() upload = Upload.query.filter_by(id=upload_id).first() upload_list = upload.patient.upload.order_by( Upload.date_uploaded.desc()).all() if len(upload_list) > 1: upload_index = upload_list.index(upload) + 1 previous_upload_list = upload_list[upload_index:] else: previous_upload_list = [] ct_scan = upload.ct_scan patient = upload.patient specs_list = list( itertools.chain(*[ health_info_dict['biopsy_test'], health_info_dict['genetic_test'] ])) specs_dict = dict( zip(specs_list, [getattr(patient, spec) for spec in specs_list])) if ct_scan.binary_prediction == 0: result_text = 'NOT having lung cancer' treatment = 'No treatment required' medicine = 'No medicine required' elif ct_scan.binary_prediction == 1: result = additional_specs(ct_scan.diameter, specs_dict) result_text = f"stage {result['stage']}, {result['cell_type']}, grade {result['grade']}, {result['invasive_type']}" treatment = result['treatment'] medicine = result['medicine'] else: result_text = f'{round(ct_scan.binary_prediction*100, 2)}% chance of having lung cancer' treatment = 'No treatment required' medicine = 'No medicine required' # if not upload.result_text: # upload.result_text = result_text # db.session.commit() rendered = render_template('pdf_template.html', form=form, upload=upload, ct_scan=ct_scan, result_text=result_text, treatment=treatment, medicine=medicine, result_percent=ct_scan.binary_prediction, previous_upload_list=previous_upload_list, health_info_dict=health_info_dict) return render_pdf(HTML(string=rendered))
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", )
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))
def create_quittance(date, date_paiement): "create pdf quittance" with open('data.json', 'r') as f: json_dict = json.load(f) splitdate = date.split('/') month_range = calendar.monthrange(int(splitdate[1]), int(splitdate[0])) firstday, lastday = month_range formatted_firstday = "01/" + date formatted_lastday = str(lastday) + "/" + date format = "%d/%m/%Y" today = datetime.now() today_str = today.strftime(format) for data in json_dict: html = render_template('quittance.html', data=data, firstday=formatted_firstday, lastday=formatted_lastday, today=today_str, paymentdate=date_paiement) pdf = render_pdf(HTML(string=html)) HTML(string=html, base_url='.').write_pdf( 'quittance.pdf', stylesheets=[CSS(filename='static/style.css')])
def chat_results_pdf(scenario_id): c = check_input(True, scenario_id) if c != '': return c scenario = db.get_scenario(scenario_id) #get the data for the page, and redirect it to rende_pdf method html = render_template('result_pdf.html', score=session['score'], results=session['results'], scenario=scenario, scenario_id=scenario_id) return render_pdf(HTML(string=html))
def index(): form = MyForm(request.form) if request.method == 'POST': url = request.form['url'] if form.validate(): fn = hashlib.md5(url.encode('utf-8')).hexdigest() + '.pdf' return render_pdf(HTML(url), download_filename=fn) else: flash('Invalid URL!') return render_template('index.html', form=Form)
def getPDF(): if not request.args.get('data'): return abort(400, 'data parameter missing') if not request.args.get('title'): return abort(400, 'title parameter missing') text = request.args.get('text') if request.args.get('text') else "" html = render_template('qrpdf.html', title=request.args.get('title'), qr_data=request.args.get('data'), text=text) return render_pdf(HTML(string=html))
def generate_pdf(result): controls = { item.number: item for item in Control.query.filter_by(language=get_locale().language) } data = render_template( 'results/document.html', all_controls=controls, results=result ) return render_pdf(HTML(string=data))
def generate_pdf(id): '''Pdf generatie route. Genereert een pdf met de gegevens van de fiets. Returns: pdf: opent een pdf in de browser die geprint kan worden ''' f = Fiets.query.filter_by(Nummer=id).first() # Datum van nu t = datetime.datetime.now().strftime("%Y-%m-%d") html = render_template('pdf_formulier.html', r=f, t=t) return render_pdf(HTML(string=html))
def fullscan(target, dowebscan="do", render_as_pdf=True): print("Calling : " + api_url + "/fullscan/" + target) ping = requests.get(api_url + "/ping/" + target) ping = ping.json() #We get the ports from the API ports = requests.get(api_url + "/portscan/" + target) ports = ports.json() if "443" in ports: ciphers = requests.get(api_url + "/cipherscan/" + target) ciphers = ciphers.json() else: ciphers = [] portlist = [] for key in ports: print(key) portlist.append(key) portstring = portlist[0] for port in portlist[1:]: portstring = portstring + "," portstring = portstring + port services = requests.get(api_url + "/servicescan/" + target + "/" + portstring) services = services.json() if dowebscan == "do": nikto = requests.get(api_url + "/webappscan/" + target) nikto = nikto.json() else: nikto = [] bytestring = render_template('fullscan.html', portscan_json=ports, cipher_json=ciphers, service_json=services, ping_json=ping, webapp_json=nikto) if render_as_pdf == "do": return render_pdf(HTML(string=bytestring)) return render_template('fullscan.html', portscan_json=ports, cipher_json=ciphers, service_json=services, ping_json=ping, webapp_json=nikto)
def remision(num_remision): """ Imprimir Remisión """ cursor_remision = connectiondb.cursor() sql_remision = """SELECT * FROM Remision WHERE num_remision = '%s'""" % num_remision cursor_remision.execute(sql_remision) remision = cursor_remision.fetchone() cursor_remision.close() # Formato a los valores de la remision remision['sub_total'] = format(remision['sub_total'], ",d") remision['val_iva'] = format(remision['val_iva'], ",d") remision['val_total'] = format(remision['val_total'], ",d") cursor_items_remision = connectiondb.cursor() sql_items_remision = """SELECT consecutivo, cantidad_item, referencia, val_unitario, valor_item FROM ItemsRemision WHERE num_remision = '%s'""" % num_remision cursor_items_remision.execute(sql_items_remision) items_remision = cursor_items_remision.fetchall() cursor_items_remision.close() for item in items_remision: item['val_unitario'] = format(item['val_unitario'], ",d") item['valor_item'] = format(item['valor_item'], ",d") # Datos del cliente cursor_datos_cliente = connectiondb.cursor() sql_datos_cliente = """SELECT Remision.num_remision, Cliente.nombre_cliente, Cliente.identificacion_cliente, Cliente.direccion, Cliente.ciudad, Cliente.telefono FROM Remision INNER JOIN Cliente ON Remision.identificacion_cliente = Cliente.identificacion_cliente WHERE Remision.num_remision = '{}' ORDER BY Remision.num_remision DESC;""".format( remision['num_remision']) cursor_datos_cliente.execute(sql_datos_cliente) datos_cliente = cursor_datos_cliente.fetchone() cursor_datos_cliente.close() html = render_template('remision-pdf.html', remision=remision, datos_cliente=datos_cliente, items_remision=items_remision, name=current_user.username) return render_pdf(HTML(string=html))
def create_pdf_for_compare(from_date, to_date): available_images = plotter.get_compare_json("Total", "Total", from_date, to_date) now = datetime.datetime.now() date = now.strftime("%Y%m%d-%H%M") html = render_template('compare_pdf_template.html', available_images=available_images, actual_user_1="Total", actual_user_2="Total", from_date=from_date, to_date=to_date) return render_pdf(HTML(string=html), download_filename="Total_Total_compare_" + from_date + "-" + to_date + "_" + date + ".pdf")
def api_pdf_results(): user = session['name'] public = False formatted_time = "Generated on %A, %B %d, %Y at %I:%M %p Server Time" time_str = datetime.today().strftime(formatted_time) results = utils.current_results() winners = utils.choose_winners() votes = Vote.query.all() t_s = TimeSettings.query.first() alert = t_s.status == 'open' vote_html = render_template("pdf_results.html", time=time_str, user=user, candidates=results, winners=winners, votes=votes, public=public, alert=alert) return render_pdf(HTML(string=vote_html))
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))
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
def pdf(): from flask_weasyprint import HTML, render_pdf v = request.form['variant'] # should contain short name, not full name html = render_template('grid_pdf.html', puzzle=render_grid_pdf( sudoku.grid_from_string(request.form['code'], v), v), variant=full_name(v), v_code=v, difficulty=request.form['difficulty']) return render_pdf(HTML(string=html))
def delegates_pdf(code): practice = Practice.query.filter(Practice.code == code).first() delegates = Delegate.query.filter(Delegate.practice_code == code).order_by( Delegate.instance).all() html = render_template('practices/delegates/pdf.html', delegates=delegates, practice=practice, now=datetime.datetime.utcnow()) return render_pdf(HTML(string=html), download_filename='{}_{}_staff.pdf'.format( practice.code, practice.name, ))
def view_letter_template(filetype): """ POST /preview.pdf with the following json blob { "letter_contact_block": "contact block for service, if any", "template": { "template data, as it comes out of the database" } "values": {"dict of placeholder values"} } """ try: if filetype not in ('pdf', 'png'): abort(404) if filetype == 'pdf' and request.args.get('page') is not None: abort(400) json = request.get_json() validate_preview_request(json) try: logo_file_name = current_app.config['LOGO_FILENAMES'][ json['dvla_org_id']] except KeyError: abort(400) template = LetterPreviewTemplate( json['template'], values=json['values'] or None, contact_block=json['letter_contact_block'], # we get the images of our local server to keep network topography clean, # which is just http://localhost:6013 admin_base_url='http://localhost:6013', logo_file_name=logo_file_name, ) string = str(template) html = HTML(string=string) pdf = render_pdf(html) if filetype == 'pdf': return pdf elif filetype == 'png': return send_file(**png_from_pdf( pdf, page_number=int(request.args.get('page', 1)))) except Exception as e: current_app.logger.error(str(e)) raise e
def print_letter_template(): """ POST /print.pdf with the following json blob { "letter_contact_block": "contact block for service, if any", "template": { "template data, as it comes out of the database" } "values": {"dict of placeholder values"}, "filename": {"type": "string"} } """ json = get_and_validate_json_from_request(request, preview_schema) filename = f'{json["filename"]}.svg' if json['filename'] else None template = LetterPrintTemplate( json['template'], values=json['values'] or None, contact_block=json['letter_contact_block'], # letter assets are hosted on s3 admin_base_url=current_app.config['LETTER_LOGO_URL'], logo_file_name=filename, ) html = HTML(string=str(template)) pdf = BytesIO(html.write_pdf()) cmyk_pdf = convert_pdf_to_cmyk(pdf) response = send_file( cmyk_pdf, as_attachment=True, attachment_filename='print.pdf' ) response.headers['X-pdf-page-count'] = get_page_count(cmyk_pdf.read()) cmyk_pdf.seek(0) return response
def pdf_ggcc(): # flag de generar pdf """ Listado de ggcc """ check_edit_or_admin() integrantes = db.session.query(Miembro)\ .join(GrupoCasero, GrupoCasero.id == Miembro.id_grupocasero)\ .join(TipoMiembro, TipoMiembro.id == Miembro.id_tipomiembro)\ .add_columns( Miembro.id_grupocasero, Miembro.id, Miembro.fullname, TipoMiembro.nombre_tipomiembro ) query = db.session.query(GrupoCasero)\ .join(Direccion, GrupoCasero.id_direccion == Direccion.id)\ .add_columns( GrupoCasero.id, GrupoCasero.id_direccion, GrupoCasero.nombre_grupo, GrupoCasero.descripcion_grupo, 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_ggcc.html', informes=query_miembros, integrantes=integrantes) print(salida) return render_pdf(HTML(string=salida))
def download_report_pdf(): term = request.args.get("term") student = Student.query.get(request.args.get("student_id")) active_session = Sessions.query.get(request.args.get("active_session")) records = get_student_results(student.id, term, active_session.id, student.classroom_id, StudentResults, Subject) student_report_template = render_template("student_report.html", student=student, term=term, active_session=active_session, records=records) return render_pdf( HTML(string=student_report_template), download_filename=f"{student.firstname}_{student.surname}_report.pdf")
def download_hpo_genes(institute_id, case_name): """Download the genes contained in a case dynamic gene list""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) # Create export object consisting of dynamic phenotypes with associated genes as a dictionary phenotype_terms_with_genes = controllers.phenotypes_genes(store, case_obj) html_content = "" for term_id, term in phenotype_terms_with_genes.items(): html_content += f"<hr><strong>{term_id} - {term.get('description')}</strong><br><br>{term.get('genes')}<br>" return render_pdf( HTML(string=html_content), download_filename=case_obj["display_name"] + "_" + datetime.datetime.now().strftime("%Y-%m-%d") + "_dynamic_phenotypes.pdf", )
def makePDF(note_title, note_id): ids = re.search('[0-9]+', note_id) if ids is None: flash( 'Note not found. If you think this is in error, please contact us.', 'danger') return redirect(url_for('members')) n = Notes.query.get(int(ids.group(0))) if note_check_out(n): if n.passphrased: flash('Password encrypted notes are not supported yet.', 'danger') return redirect(url_for('members')) html = decrypt_it(n.body).decode('utf8', errors='ignore') return render_pdf(HTML(string=html)) else: return redirect(url_for('members'))
def print_vehicles(id): from flask_weasyprint import HTML, render_pdf fleet = Fleet.query.get(id) if fleet: fleet_vehicles = Vehicle.query.filter_by(fleet_id=fleet.id).order_by( Vehicle.created_at.desc()).all() html = render_template('fleets/pdf_fleet_vehicles.html', fleet=fleet, fleet_vehicles=fleet_vehicles) pdfname = fleet.name + '.pdf' return render_pdf(HTML(string=html)) #return render_template('trackers/pdf_logs.html', logs=logs,tracker=tracker,from_date=from_date,to_date=to_date) else: return 'error'