def generar_fichero_pdf_mes(listaArchivosXLSX): # esto es para escoger el archivo xlsx print(f"Archivos de excel encontrados en directorio") for i in range(len(listaArchivosXLSX)): print(f"{(i+1)} = {listaArchivosXLSX[i]}") opcion_archivo = introducirOpcion(len(listaArchivosXLSX)) archivo_xlsx_escogido = listaArchivosXLSX[(opcion_archivo - 1)] # esto es para escoger el sheet del archivo escogido xlsx_File = pd.ExcelFile(archivo_xlsx_escogido) xlsx_Sheets = xlsx_File.sheet_names for y in range(len(xlsx_Sheets)): print(f"{(y+1)} = {xlsx_Sheets[y]}") opcion_sheet = introducirOpcion(len(xlsx_Sheets)) opcion_sheet_escogido = xlsx_Sheets[(opcion_sheet - 1)] # creamos dataframe y lo devolvemos como pdf dfMes = pd.read_excel(archivo_xlsx_escogido, sheet_name=opcion_sheet_escogido) dataframe = dfMes.loc[:, [ 'fecha', 'tmin', 'horatmin', 'tmax', 'horatmax', 'tmed' ]] #replace .xlsx a .pdf archivo_pdf = archivo_xlsx_escogido.replace(".xlsx", ".pdf") # Convertimos la plantilla .pug a html, especificando el valor html = pug_to_html("C:\\WPy64-3810\\notebooks\\L13\\template_mes.pug", title="Informe mensual temperaturas Agoncillo", dataframe=dataframe) write_report(html, archivo_pdf)
def create_report_summary(variables): variables = { 'title': 'Brain Health Report', 'logo': '/Users/suhaas/Desktop/ReactN/analytics/reactrack/REACT_logo.png', 'exam_history_and_map_graph': '/Users/suhaas/Desktop/ReactN/analytics/test.png', 'user_id': 'random_hash_basically', 'name': 'Mary Smith', 'age': '55', 'location': 'LCB - Norwood', 'date': '4/26/2020 1:11p', 'VOR_phase_lag': 0.5, 'VOR_bpm': 100, 'VOR_nystagmus': 'No', 'default_color': 'teal', 'self_paced': None, 'prosaccade_reaction_time_color': 'red', 'prosaccade_acc_color': 'green', 'prosaccade_catch_up_color': 'purple' } html = pug_to_html('./VOR_battery2_template.pug', **variables) write_report(html, 'VOR_2_Summary_Example.pdf')
def write_to(self, path: str): with tempfile.NamedTemporaryFile(suffix=".pug", mode="w") as pugfile: figures = 0 for element in self.__body._flatten(): if element["kind"] == "title": level = max(min(element["level"], 6), 1) pugfile.write("h%d %s\n\n" % (level, element["text"])) elif element["kind"] == "paragraph": pugfile.write("p %s\n\n" % (element["text"], )) elif element["kind"] == "figure": figures += 1 pugfile.write('img(src="%s", alt="Figure %d")\n\n' % (element["url"], figures)) elif element["kind"] == "table": pugfile.write("table.ui.celled.table\n") table: PDFReportsReportTable = element["table"] for i, row in enumerate(table._rows): row = [str(el) for el in row] cell_el = "td" if i == 0: pugfile.write(" thead\n") cell_el = "th" elif i == 1: pugfile.write(" tbody\n") pugfile.write(" tr\n") for cell in row: pugfile.write(" %s %s\n" % (cell_el, cell)) pugfile.write("\n") else: raise NotImplementedError(str(element)) pugfile.flush() html = pug_to_html(pugfile.name) write_report(html, path)
def test_basics(tmpdir): template_path = os.path.join('tests', 'data', "example_template.pug") pdf_path = os.path.join(str(tmpdir), 'test.pdf') html = pug_to_html(template_path, title="Summary of your order") write_report(html, pdf_path) with open(pdf_path, "rb") as f: reader = PdfFileReader(f) assert reader.numPages == 2
def main(): # Get user input topic = sys.argv[1] mode = int(sys.argv[2]) # Mode dictionary modeselect = { 0: noblank, 1: kanjitest, 2: hiraganatest, 3: englishtest, 4: randomtest, } # import vocabulary from csv file filename = topic + ".xls" try: vocabulary = pd.read_excel("xls_files/" + filename) vocabulary.columns = ['kanji', 'hiragana', 'english'] except: print("Filename " + "xls_files/" + filename + " invalid (wrong path or xls format invisible character)") return (1) try: toprint, modetitle = modeselect.get(mode, lambda: "error mode")(vocabulary) # Shuffle toprint = toprint.iloc[np.random.permutation(len(toprint))] except: print("Mode " + str(mode) + " invalid") print( "Mode => 0: noblank - 1: Kanji test - 2: reading test - 3: translation test - 4: random test" ) return (1) # Convert to pdf date = strftime("%Y_%m_%d", gmtime()) pdffilename = topic + "_" + modetitle + "_" + date html = pug_to_html("template.pug", title="Japanese for Engineering", vocab=topic, dataframe=toprint, size=len(toprint)) try: print("PDF saving as " + pdffilename) write_report(html, pdf_path + pdffilename + ".pdf") print("Done !") return (0) except: print("Please close the existing pdf with the same name") return (1)
def generar_fichero_pdf_todos_meses(listaArchivosXLSX): for i in range(len(listaArchivosXLSX)): # creamos dataframe y lo devolvemos como pdf archivo_xlsx = listaArchivosXLSX[i] dfMes = pd.read_excel(archivo_xlsx, sheet_name="Sheet1") dataframe = dfMes.loc[:, [ 'fecha', 'tmin', 'horatmin', 'tmax', 'horatmax', 'tmed' ]] #replace .xlsx a .pdf archivo_pdf = archivo_xlsx.replace(".xlsx", ".pdf") # Convertimos la plantilla .pug a html, especificando el valor html = pug_to_html("C:\\WPy64-3810\\notebooks\\L13\\template_mes.pug", title="Informe mensual temperaturas Agoncillo", dataframe=dataframe) write_report(html, archivo_pdf)
def sequenticon_batch_pdf(sequences, target=None, title="Sequenticons batch"): """Generate a PDF report with sequenticons for a batch of sequences. Parameters ---------- sequences A list of either ``name, sequence`` tuples, or Biopython records (with different IDs), or paths to genbank or fasta files containing one or more record each. target path to a PDF file, file-like object, or None to return raw PDF data. title Title that will appear in the document """ now = datetime.now().strftime("%Y-%m-%d %H:%M") sequenticons = sequenticon_batch(sequences, output_format='html_image') html = pug_to_html( PUG_TEMPLATE, sidebar_text="Generated on %s by Sequenticon version %s" % (now, __version__), sequenticon_logo_url=os.path.join(ASSETS_PATH, 'logo.png'), sequenticons=sequenticons, title=title) return write_report(html, target, extra_stylesheets=(STYLESHEET, ))
def statistics_report(analysis_results, outfile, replacements=()): """Procude a PDF reports from the results of ``find_statistical_saboteurs()``. Parameters ---------- analysis_results The result of ``saboteurs.find_statistical_saboteurs``. outfile Path to the final PDF file, or file-like object, or '@memory' to return binary data of the PDF report. replacements A list of the form ``[("text_to_replace", "text_replacing"), ...]``. """ if len(analysis_results["significant_members"]) == 0: html = saboteurs_pug_to_html( members_table=None, groups_table=None, f1_score=None, saboteurs_found=False ) else: html = saboteurs_pug_to_html( members_table=make_members_table(analysis_results), groups_table=make_groups_table(analysis_results), f1_score=analysis_results["f1_score"], saboteurs_found=True, ) html = replace_in_text(html, capitalize=True, replacements=replacements) return write_report(html, outfile, extra_stylesheets=(STYLESHEET,))
def test_with_plots_and_tables(tmpdir): template_path = os.path.join('tests', 'data', "with_plots_and_tables.pug") assert os.path.exists(template_path) dataframe = pandas.DataFrame.from_records({ "Name": ["Anna", "Bob", "Claire", "Denis"], "Age": [12,22,33,44], "Height (cm)": [140, 175, 173, 185] }, columns=["Name", "Age", "Height (cm)"]) pdf_path = os.path.join(str(tmpdir), 'test.pdf') html = pug_to_html(template_path, dataframe=dataframe) write_report(html, pdf_path) with open(pdf_path, "rb") as f: reader = PdfFileReader(f) assert reader.numPages == 2 pdf_data = write_report(html) assert len(pdf_data) > 10000
def write_simulation_pdf_report(target, simulation_info): summary_table = dataframe_to_html(simulation_info, extra_classes=("definition", )) def tr_modifier(tr): tds = list(tr.find_all("td")) if len(tds) == 0: return outcome, number = tds if outcome.text == "Valid": if number.text == "0": add_css_class(tr, "negative") else: add_css_class(tr, "positive") elif number.text != "0": add_css_class(tr, "negative") summary_table = style_table_rows(summary_table, tr_modifier) html = dnacauldron_pug_to_html(DOMESTICATION_REPORT_TEMPLATE, summary_table=summary_table) write_report(html, target, extra_stylesheets=(STYLESHEET, ))
def write_pdf_domestication_report(target, domestication_infos, domesticators): summary_table = dataframe_to_html(domestication_infos, extra_classes=("definition", )) def tr_modifier(tr): tds = list(tr.find_all("td")) if len(tds) == 0: return if len(tds) == 6: name, order_id, dom, final, added, edited = tds else: name, order_id, dom, final, added, edited, barcode = tds if "Failed" in final.text: add_css_class(tr, "negative") if edited.text != "0": add_css_class(edited, "warning") summary_table = style_table_rows(summary_table, tr_modifier) html = genedom_pug_to_html(DOMESTICATION_REPORT_TEMPLATE, summary_table=summary_table, domesticators=domesticators) write_report(html, target, extra_stylesheets=(STYLESHEET, ))
def generate_report(context,\ outfilename='default.pdf'): """ Generate a pdf report. Args: context (dict) : context contains the information to fill in the report """ module_id = context['module_id'] module_name = context['module_name'] title = f'Calibration results for module #{module_id} "{module_name}"' css = preload_stylesheet(args.template_style) #for i in range(context['ndetectors']): #testplot = os.path.abspath(context['det1_nm'][0]) testplot = '' html = pug_to_html(args.template,\ title=title,\ context=context,\ my_name=context['name'],\ det_id1='n.a.',\ det_1_stripA=testplot) write_report(html, outfilename, extra_stylesheets=[css])
from pdf_reports import pug_to_html, write_report, preload_stylesheet css = preload_stylesheet('style.scss') html = pug_to_html("template.pug", title="My report", my_name='Zulko') write_report(html, "example.pdf", extra_stylesheets=[css])
from pdf_reports import pug_to_html, write_report # Convertimos la plantilla .pug a html, especificando el valor html = pug_to_html("template_EjemploSencillo1.pug", title="Informe") write_report(html, "EjemploSencillo1.pdf")
"""PDF report generation from a Pug template embedding code to generate plots and tables. A HTML page is generated from a template and rendered as a local PDF file. """ import pandas import matplotlib.pyplot as plt from pdf_reports import pug_to_html, write_report dataframe = pandas.DataFrame.from_records( { "Name": ["Anna", "Bob", "Claire", "Denis"], "Age": [12, 22, 33, 44], "Height (cm)": [140, 175, 173, 185] }, columns=["Name", "Age", "Height (cm)"]) html = pug_to_html("with_plots_and_tables.pug", dataframe=dataframe) write_report(html, "with_plots_and_tables.pdf")
def test_preload_stylesheet(tmpdir): css = preload_stylesheet(os.path.join('tests', 'data', 'style.scss')) html = pug_to_html(string="p {{ var }}", var="Bla") pdf_path = os.path.join(str(tmpdir), 'test.pdf') write_report(html, pdf_path, extra_stylesheets=[css])
'lecturas muy largas[%]' ] antes = filtrado_df[antes_col] #.index('total de lecturas antes del filtrado') desp = filtrado_df[ despues_col] #.set_index('total de lecturas despues del filtrado') NNN = filtrado_df[NNN_col] #.set_index('lecturas lowqual[%]') ###profundidad prof = pd.read_csv(bam_dp, sep='\t', index_col=0, header=None).T prof_df_1 = prof.iloc[:, 1:5] prof_df_2 = prof.iloc[:, 5:] ###alineamiento alineamiento = pd.read_csv(a_qual, sep='\t', index_col=0, header=0).T alineamiento_df = alineamiento.iloc[:, 0:] html = pug_to_html( pug_template, title=sample_id, genero=sex_df, antes=antes, despues=desp, NNN=NNN, prof1=prof_df_1, prof2=prof_df_2, TSO=TSO, fecha=fecha_corrida, alineamiento=alineamiento_df ) #, profundidad= muestra_prof_lib,version= version, N_lecturas_antes = N_lecturas_antes, N_lecturas_dps = N_lecturas_dps, N_lecturas_dps_percent = N_lecturas_dps_percent, lecturas_lowqual = lecturas_lowqual, lecturas_NN = lecturas_NN, short_reading = short_reading, too_long=too_long, q_30_bef=q_30_bef,q_30_aft=q_30_aft, q20_bef= q20_bef, q20_after=q20_after) write_report(html, outfile)
def test_write_pdf(): data = write_report("<h1>Test</h1>") assert len(data) > 100
import collections import os import pickle from pdf_reports import pug_to_html, write_report with open('result.pkl', 'rb') as fd: data = pickle.load(fd) # reorder tags data tags_data = collections.OrderedDict( sorted(data['tags'].items(), key=lambda x: x[1]['number'], reverse=True)) html = pug_to_html("template.pug", title='NER 模型性能报告', sentence=data['sentence'], tags=tags_data) # Remove old file if os.path.exists('report.pdf'): os.remove('report.pdf') write_report(html, "report.pdf")
"""Basic PDF report generation from a JINJA template with pdf_reports. A HTML page is generated from a template and rendered as a local PDF file. """ from pdf_reports import pug_to_html, write_report html = pug_to_html("example_template.pug", title="My report") write_report(html, "example.pdf")
import pandas as pd from datetime import datetime from pdf_reports import pug_to_html, write_report planilha = pd.read_excel("content/controle_de_gastos.xlsx") hoje = datetime.now().date() html = pug_to_html("content/modelo_de_relatorio.pug", planilha=planilha, hoje=hoje) write_report(html, "controle_de_gastos_rel.pdf")