def generate_bill(a_family, a_cost_per_person): a_title = DIR_UBERSICHT + "Vorauszahlung_Ubersicht_"+a_family+".pdf" pdf = PDFDocument(a_title) pdf.init_report() pdf.p_markup("Automatisch generiert am: "+ str(date.today()), pdf.style.right) pdf.spacer(20) pdf.h1("Übersicht Vorauszahlung für Familie " + a_family) pdf.spacer(20) pdf.h2("Kostenaufstellung") pdf.hr() pdf.spacer(10) my_list = [] q = db.query(Members).join(Familys).filter_by(f_name=a_family) total = 0 for result in db.execute(q): my_list.append([result[2] + " " + result[3], str(a_cost_per_person) + " €"]) total += a_cost_per_person try: pdf.table(my_list, 220) except Exception: print("No members") pdf.spacer(10) pdf.hr() pdf.spacer(20) pdf.p_markup("Total: " + str(total) + " €", pdf.style.bold) pdf.spacer(20) pdf.p(UBERWEISUNG_FOOTER) pdf.generate() return os.path.abspath(a_title)
def pdf(): results = g.conn.execute('select * from reports') first = results.fetchall()[0] primary_key, data = first data_json = json.loads(data) org_name = data_json['organization'] report_at = data_json['reported_at'] created_at = data_json['created_at'] # returns a file object - that stays in the memory and isn't saved f = BytesIO() # pass file object 'f' to pdf object pdf = PDFDocument(f) #initialise pdf.init_report() # convert dictionary to string and add h1 & p tags to pdf pdf.h1('The Report') pdf.p(f'Organisation: {org_name}') pdf.p(f'Reported at: {report_at}') pdf.p(f'Created at: {created_at}') pdf.generate() return f.getvalue(), 200, {'Content-Type': 'application/pdf', 'Content-Disposition':'attachment; filename=report.pdf'}
def generate_pdf(data): f = BytesIO() pdf = PDFDocument(f) pdf.init_report() pdf.append(data) pdf.generate() return pdf
def say_hello(): f = BytesIO() pdf = PDFDocument(f) pdf.init_report() pdf.h1('Hello World') pdf.p('Creating PDFs made easy.') pdf.generate() return f.getvalue()
def export_to_pdf(hotel_data, request): response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=hotel_data.pdf' pdf = PDFDocument(response) pdf.init_report() description, star_rating, facilities = get_description_from_filter(request) description = str(len(hotel_data)) + " " + description pdf.h1(description) if star_rating: pdf.p(" Star rating:" + star_rating) if facilities: pdf.p("Facilities: " + facilities) from reportlab.lib.styles import getSampleStyleSheet styles = getSampleStyleSheet() styleN = styles["BodyText"] styleN.alignment = TA_LEFT styleBH = styles["Normal"] data = [] # Defile header data.append([ '', 'Hotel Name', 'Location', Paragraph('Lowest Price (USD)', styleN), Paragraph('Star rating', styleN), Paragraph('User rating', styleN) ]) number = 1 # define row in table for hotel in hotel_data: name = Paragraph(hotel.name.encode('ascii', 'ignore'), styleN) address = Paragraph(hotel.address.encode('ascii', 'ignore'), styleN) arr = [ number, name, address, hotel.lowest_price, hotel.star_rating, hotel.user_rating ] data.append(arr) number += 1 t = Table(data, colWidths=[30, 135, 290, 40, 32, 32], style=[ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('BACKGROUND', (0, 0), (5, 0), colors.limegreen), ]) # append table to page pdf.story.append(t) # pdf.table(data, 100) pdf.generate() return response
def generatePDF(title='No title', subtitle='', data=[]): f = BytesIO() pdf = PDFDocument(f) pdf.init_report() pdf.h1('Hello World') pdf.p('Creating PDFs made easy.') pdf.generate() return f.getvalue()
def makemPdf(): pdf = PDFDocument("qa.pdf") pdf.init_report() pdf.h1("Bindu's Jewelery Store") pdf.h2("Sanjaynagar, Bangalore 560094") pdf.h2('9480529032, 8795652460') pdf.h2("Receipt",pdf.style.center) pdf.hr() pdf.generate()
def create_assignment_pdf(name, assignments): pdf = PDFDocument(name) pdf.init_report() addr = {"first_name": "A.I.T", "last_name": "(c) A.I.T 2016"} pdf.h1("Generated by A.I.T (Your A.I Tutor)\n") pdf.h2("Your Assignment (Please solve this)\n") counter = 1 for i in assignments: pdf.p("Q" + str(counter) + ": " + i + "\n") counter += 1 pdf.generate()
def generate_pdf(video_seen_id,user_id): last_video_seen = DUSerVideoSeen.objects.filter(id=video_seen_id).first() latest_video_seen = DUSerVideoSeen.objects.filter(seen_by_id=last_video_seen.asked_by_id).order_by('-seen_at').first() if last_video_seen == latest_video_seen: catalog_question = CatalogQuestion.objects.filter(id=last_video_seen.catalog_question_id).first() question_json = catalog_question.similar_question f = BytesIO() pdf = PDFDocument(f) pdf.init_report() pdf.p(question_json) pdf.generate() return f.getvalue()
def export_to_pdf(hotel_data, request): response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=hotel_data.pdf' pdf = PDFDocument(response) pdf.init_report() description, star_rating, facilities = get_description_from_filter(request) description = str(len(hotel_data)) + " " + description pdf.h1(description) if star_rating: pdf.p(" Star rating:" + star_rating ) if facilities: pdf.p("Facilities: " + facilities) from reportlab.lib.styles import getSampleStyleSheet styles = getSampleStyleSheet() styleN = styles["BodyText"] styleN.alignment = TA_LEFT styleBH = styles["Normal"] data = [] # Defile header data.append(['', 'Hotel Name', 'Location', Paragraph('Lowest Price (USD)', styleN) , Paragraph('Star rating', styleN), Paragraph('User rating', styleN)]) number = 1 # define row in table for hotel in hotel_data: name = Paragraph(hotel.name.encode('ascii', 'ignore'), styleN) address = Paragraph(hotel.address.encode('ascii', 'ignore'), styleN) arr = [number, name, address, hotel.lowest_price, hotel.star_rating, hotel.user_rating] data.append(arr) number += 1 t=Table(data,colWidths=[30, 135, 290, 40, 32, 32], style=[ ('GRID',(0,0),(-1,-1),1,colors.black), ('BACKGROUND',(0,0),(5,0),colors.limegreen), ]) # append table to page pdf.story.append(t) # pdf.table(data, 100) pdf.generate() return response
def createPDF(path): """ Create a simple PDF """ pdf = PDFDocument(path) pdf.init_report() addr = { 'first_name': "John", 'last_name': "Hanes", 'address': "123 Ding Dong Lane", 'zip_code': "75002", 'city': "Dakota" } pdf.address(addr) pdf.p("This is a paragraph!") pdf.generate()
def generate_pdf_files(self, fname, num_of_files,seed_text): """Usage: gnerate_pdf_files""" now = datetime.datetime.now() f = BytesIO() pdf = PDFDocument(f) pdf.init_letter() pdf.h1('{}'.format(seed_text)) pdf.p(str(now)) pdf.generate() try: for x in range(0, num_of_files): with open("data/{}_{}.pdf".format(fname, x), 'w') as pdfout: pdfout.write(f.getvalue()) pdfout.close() except Exception as e: print('There was a problem saving your pdf file: {}'.format(e))
def generate_pdf(self, topic_obj): print 'Generating PDF..' path = "./PDFDocuments/"+topic_obj.topic+".pdf" pdf = PDFDocument(path) pdf.init_report() # pdf.h2("San Jose State University",style=pdf.style.bold) # pdf.h1("College of Science, Department of Computer Science",style=pdf.style.bold) pdf.h2("Topic Recommendation:\n") pdf.h1("\nTopics in "+topic_obj.topic) pdf.h2('\nCourse Description') techs = "" for tech in topic_obj.technologies: techs += tech + ", " pdf.p("\nIntroduction to topics in " + topic_obj.topic + " such as, "+techs) pdf.p(str(topic_obj.listedTech)) pdf.h2("\nCourse Learning Outcomes:\n\n") pdf.p(topic_obj.actionList) pdf.h2("\nSummary from top job descriptions:\n") pdf.p(topic_obj.summary) pdf.generate() print 'PDF generated..' subprocess.Popen(path, shell=True)
def tasks_report(kb): f = BytesIO() pdf = PDFDocument(f) pdf.init_report() d = date.today().strftime("%d.%m.%Y") pdf.style.heading2.textColor = "#FC6600" pdf.style.bullet.bulletText = '□' pdf.h1(f"Tasks Stand {d}") pdf.spacer() for project in kb.get_my_projects(): print(project['name']) pdf.h2(project['name']) l = [] for task in kb.get_all_tasks(project_id=project['id'], status_id=1): l.append(task['title']+" id: " + task['id']) print(" ", task['title']) pdf.ul(l) pdf.generate() return f.getvalue()
def generate_teilnehmerliste(): a_title = DIR_TEILNEHMERLISTE + "Teilnehmer.pdf" pdf = PDFDocument(a_title) pdf.init_report() pdf.p_markup(date.today(), pdf.style.right) pdf.spacer(20) pdf.h1("Teilnehmer Skifahren 2017") pdf.hr_mini() pdf.spacer(20) familys = Familys.query.all() for family in familys: pdf.h3(family.f_name) q = db.query(Members).join(Familys).filter_by(f_name=family.f_name) members = [] for result in db.execute(q): members.append(result[2] + " " + result[3]) pdf.ul(members) pdf.spacer(10) pdf.p("Info:") pdf.p(family.f_info) pdf.spacer(20) pdf.hr() pdf.generate() return os.path.abspath(a_title)
def writeToPDF(self, path, data): pdf = PDFDocument(path) pdf.init_report() pdf.generate_style() pdf.style.heading1.alignment = TA_CENTER pdf.style.heading1.fontSize = 18 heading_style = pdf.style.heading1 pdf.h1('Fahrtenbuch Firma RAC', style=heading_style) pdf.p('\n\n\n') content = [[ 'Name', 'Datum', 'Anfangskilometerstand', 'Endkilometerstand', 'gefahrene Kilometer', 'Art der Fahrt', 'Zweck der Fahrt', 'Fahrtanfang', 'Fahrtziel' ]] for p in data['rides']: row = [] for d in p: if (d != 'Bestaetigt'): row.append(self.adjustStringLength(p.get(d))) content.append(row) # ReportLab formatting table_style = ( ("FONT", (0, 0), (-1, -1), "%s" % pdf.style.fontName, 4), ("TOPPADDING", (0, 0), (-1, -1), 2), ("BOTTOMPADDING", (0, 0), (-1, -1), 2), ("LEFTPADDING", (0, 0), (-1, -1), 2), ("RIGHTPADDING", (0, 0), (-1, -1), 2), ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("ALIGN", (0, 0), (-1, -1), "CENTER"), ('GRID', (0, 0), (-1, -1), 0.5, colors.black), ( "FONT", (0, 0), (-1, 0), "%s-Bold" % pdf.style.fontName, 4.5, ), ) header = [['KFZ-Kennzeichen', 'Anfangsdatum', 'Enddatum'], [ data['header'][0]['KFZ-Kennzeichen'], data['header'][0]['Anfangsdatum'], data['header'][0]['Enddatum'] ]] header2 = [['Anfangskilometerstand', 'Endkilometerstand'], [ data['header'][0]['Anfangskilometerstand'], data['header'][0]['Endkilometerstand'] ]] pdf.table(header, 80, style=table_style) pdf.table(header2, 80, style=table_style) pdf.p('\n\n\n') pdf.table(content, 60, style=table_style) pdf.generate()
#!/usr/bin/python from http_analyzer import http_analyzer from login import search_brute_force from alert import searcher from pdfdocument.document import PDFDocument from dns_analyzer import search_dns from malicious_file_scanner import scan_files from corelation import corelation c = PDFDocument("THREAT_HUNT_REPORT_DON.pdf") c.init_report() c.h1(" THREAT-HUNT-REPORT \n\n") c.p("autogenerated by python\n\nauthor: Nishan Maharjan\n\n") http_analyzer(c) search_brute_force(c) search_dns(c) scan_files(c) corelation(c) L = [] searcher(L, c) c.generate()
def assignment_pdf(request, assignment_id): assignment = get_object_or_404( Assignment.objects.select_related("drudge__user"), pk=assignment_id ) if not request.user.is_staff: if assignment.drudge.user != request.user: return HttpResponseForbidden("<h1>Access forbidden</h1>") result_writer = PdfFileWriter() # Generate the first page ################################################ first_page = BytesIO() pdf = PDFDocument(first_page) pdf.init_report() pdf.generate_style(font_size=10) scope_statement = assignment.specification.scope_statement address = [ scope_statement.company_name or u"Verein Naturnetz", scope_statement.company_address or u"Chlosterstrasse", scope_statement.company_contact_location or u"8109 Kloster Fahr", ] pdf.spacer(25 * mm) pdf.table(list(zip(address, address)), (8.2 * cm, 8.2 * cm), pdf.style.tableBase) pdf.spacer(30 * mm) pdf.p_markup( u""" Lieber Zivi<br /><br /> Vielen Dank fürs Erstellen deiner Einsatzvereinbarung! Du findest hier nun die Einsatzvereinbarung und einige Hinweise zum Einsatz beim Naturnetz. Bitte lies alles nochmals genau durch und überprüfe deine Daten auf Fehler. Wenn alles korrekt ist, unterschreibe die Einsatzvereinbarung und schicke diese ans Naturnetz. Die Naturnetz-Adresse ist oben aufgedruckt (passend für ein Fenstercouvert). Die Blätter mit den Hinweisen solltest du bei dir behalten und für deinen Zivildiensteinsatz aufbewahren. Mit deiner Unterschrift bestätigst du, dass du die Bestimmungen gelesen und akzeptiert hast. Die Adresse unten wird von uns benutzt, um die Einsatzvereinbarung an das Regionalzentrum weiterzuleiten.<br /><br /> Bestätigung: Ich akzeptiere die internen Bestimmungen des Naturnetz (Beilagen zur Einsatzvereinbarung).<br /><br /><br /><br /> _________________________________________<br /> %s, %s<br /><br /> Wir freuen uns auf deinen Einsatz! """ % (date.today().strftime("%d.%m.%Y"), assignment.drudge.user.get_full_name()) ) pdf.spacer(26 * mm) address = u"\n".join( [assignment.regional_office.name, assignment.regional_office.address] ).replace("\r", "") pdf.table([(address, address)], (8.2 * cm, 8.2 * cm), pdf.style.tableBase) pdf.generate() # Add the first page to the output ####################################### first_page_reader = PdfFileReader(first_page) result_writer.addPage(first_page_reader.getPage(0)) # Generate the form ###################################################### overlay = BytesIO() pdf = PDFDocument(overlay) # pdf.show_boundaries = True pdf.init_report(page_fn=create_stationery_fn(AssignmentPDFStationery(assignment))) pdf.pagebreak() pdf.pagebreak() pdf.generate() # Merge the form and the overlay, and add everything to the output ####### eiv_reader = PdfFileReader( os.path.join( os.path.dirname(os.path.dirname(__file__)), "data", "Einsatzvereinbarung.pdf", ) ) overlay_reader = PdfFileReader(overlay) for idx in range(2): page = eiv_reader.getPage(idx) page.mergePage(overlay_reader.getPage(idx)) result_writer.addPage(page) # Add the conditions PDF if it exists #################################### if assignment.specification.conditions: conditions_reader = PdfFileReader( assignment.specification.conditions.open("rb") ) for page in range(conditions_reader.getNumPages()): result_writer.addPage(conditions_reader.getPage(page)) # Response! ############################################################## response = HttpResponse(content_type="application/pdf") result_writer.write(response) response["Content-Disposition"] = "attachment; filename=eiv-%s.pdf" % ( assignment.pk, ) return response
def Run(self, pipeline, result_folder, store_folder): # Data Description data_description_text = " " all_training_result_csv_path = os.path.join(result_folder, 'all_train_result.csv') if not os.path.exists(all_training_result_csv_path): print('There is no result here') return False all_training_result_df = pd.read_csv(all_training_result_csv_path, index_col=0, header=0) sample_number = all_training_result_df.iloc[0, :]['sample_number'] positive_number = all_training_result_df.iloc[0, :]['positive_number'] negative_number = all_training_result_df.iloc[0, :]['negative_number'] data_description_text += "We selected {:d} cases as the training data set ({:d}/{:d} = positive/negative)). ".\ format(sample_number, positive_number, negative_number) testing_result_csv_path = os.path.join(result_folder, 'test_result.csv') if not os.path.exists(testing_result_csv_path): data_description_text += "Since the number of the samples were limited, there was no independent testing data. " else: testing_result_df = pd.read_csv(testing_result_csv_path, index_col=0, header=0) sample_number = testing_result_df.iloc[0, :]['sample_number'] positive_number = testing_result_df.iloc[0, :]['positive_number'] negative_number = testing_result_df.iloc[0, :]['negative_number'] data_description_text += "We also selected another {:d} cases as the independent testing data " \ "set ({:d}/{:d} = positive/negative). \n" \ "".format(sample_number, positive_number, negative_number) # Method Description method_description_text = " " method_description_text += pipeline.GetNormalizer().GetDescription() method_description_text += pipeline.GetDimensionReduction().GetDescription() method_description_text += pipeline.GetFeatureSelector().GetDescription() method_description_text += pipeline.GetClassifier().GetDescription() method_description_text += pipeline.GetCrossValidatiaon().GetDescription() method_description_text += "\n" statistic_description_text = " The performance of the model was evaluated using receiver operating characteristic " \ "(ROC) curve analysis. The area under the ROC curve (AUC) was calculated for quantification. " \ "The accuracy, sensitivity, specificity, positive predictive value (PPV), and negative " \ "predictive value (NPV) were also calculated at a cutoff value that maximized the " \ "value of the Yorden index. We also boosted estimation 1000 times and applied paired " \ "t-test to give the 95% confidence interval. All above processes were implemented with " \ "FeAture Explorer (FAE, v0.2.5, https://github.com/salan668/FAE) on Python (3.6.8, https://www.python.org/). \n" # Result Description result_folder = os.path.join(result_folder, pipeline.GetStoreName()) result = pd.read_csv(os.path.join(result_folder, 'result.csv'), index_col=0) if os.path.exists(testing_result_csv_path): result_description_text = "We found that the model based on {:d} features can get the highest AUC on the " \ "validation data set. The AUC and the accuracy could achieve {:.3f} and {:.3f}, respectively. In this point, " \ "The AUC and the accuracy of the model achieve {:.3f} and {:.3f} on testing data set. " \ "The clinical statistics in the diagonsis and the selected features were shown in Table 1 and Table 2. " \ "The ROC curve was shown in Figure 1. \n" \ "".format(pipeline.GetFeatureSelector().GetSelectedFeatureNumber(), float(result.loc['val_auc'].values), float(result.loc['val_accuracy'].values), float(result.loc['test_auc'].values), float(result.loc['test_accuracy'].values) ) else: result_description_text = "We found that the model based on {:d} features can get the highest AUC on the " \ "validation data set. The AUC and the accuracy could achieve {:.3f} and {:.3f}, respectively. " \ "The clinical statistics in the diagonsis and the selected features were shown in Table 1 and Table 2. " \ "The ROC curve was shown in Figure 1. \n" \ "".format(pipeline.GetFeatureSelector().GetSelectedFeatureNumber(), float(result.loc['val_auc'].values), float(result.loc['val_accuracy'].values)) from reportlab.lib import colors table_stype = ( ('FONT', (0, 0), (-1, -1), '%s' % 'Helvetica', 9), ('LINEABOVE', (0, 0), (-1, 0), 1, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 1, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTER') ) table_1_header = "Table 1. Clinical statistics in the diagnosis. " if not os.path.exists(testing_result_csv_path): table_1 = [['Statistics', 'Value'], ['Accuracy', str(result.loc['val_accuracy'].values[0])], ['AUC', str(result.loc['val_auc'].values[0])], ['AUC 95% CIs', str(result.loc['val_auc 95% CIs'].values[0])], ['NPV', str(result.loc['val_negative predictive value'].values[0])], ['PPV', str(result.loc['val_positive predictive value'].values[0])], ['Sensitivity', str(result.loc['val_sensitivity'].values[0])], ['Specificity', str(result.loc['val_specificity'].values[0])]] else: table_1 = [['Statistics', 'Value'], ['Accuracy', str(result.loc['test_accuracy'].values[0])], ['AUC', str(result.loc['test_auc'].values[0])], ['AUC 95% CIs', str(result.loc['test_auc 95% CIs'].values[0])], ['NPV', str(result.loc['test_negative predictive value'].values[0])], ['PPV', str(result.loc['test_positive predictive value'].values[0])], ['Sensitivity', str(result.loc['test_sensitivity'].values[0])], ['Specificity', str(result.loc['test_specificity'].values[0])]] candidate_file = glob.glob(os.path.join(result_folder, '*coef.csv')) if len(candidate_file) > 0: coef = pd.read_csv(candidate_file[0], index_col=0, header=0) table_2_header = 'Table 2. The coefficients of features in the model. ' table_2 = [['Features', 'Coef in model']] for index in coef.index: table_2.append([str(index), "{:.3f}".format(coef.loc[index].values[0])]) else: with open(os.path.join(result_folder, 'feature_select_info.csv'), 'r', newline='') as file: reader = csv.reader(file) for row in reader: if row[0] == 'selected_feature': features = row[1:] table_2_header = 'Table 2. The selected of features. ' table_2 = [['Features', 'Rank']] for index in range(len(features)): table_2.append([features[index], str(index + 1)]) figure_title = "Figure 1. The ROC curve. " # Build PDF pdf = PDFDocument(os.path.join(store_folder, 'description.pdf')) pdf.init_report() pdf.h1("Materials and Methods") pdf.p(data_description_text) pdf.p(method_description_text) pdf.p(statistic_description_text) pdf.h1("Result") pdf.p(result_description_text) pdf.table_header(table_1_header) pdf.table(table_1, 130, style=table_stype) pdf.table_header(table_2_header) pdf.table(table_2, 200, style=table_stype) pdf.p("\n\n") pdf.image(os.path.join(store_folder, 'ROC.jpg')) pdf.table_header(figure_title) pdf.end_connect("Thanks for using FAE v.0.2.5. If you need a specific description, please connect to Yang Song ([email protected]) or Guang Yang " "([email protected]). Welcome any co-operation and discussion. ") pdf.generate()
import json from io import BytesIO from pdfdocument.document import PDFDocument if __name__ == "__main__": with open('elpais_mvm.json') as json_file: articles = json.load(json_file) f = BytesIO() pdf = PDFDocument(f) pdf.init_report() for article in articles: pdf.h1(article['title']) pdf.smaller(article['date']) pdf.p(article['content']) pdf.h3('Tags') pdf.smaller(', '.join(article['tags'])) pdf.next_frame() pdf.generate() with open('mvm_articles.pdf', 'w') as file: file.write(f.getvalue())
def toPdf(path, text): pdf = PDFDocument(path) pdf.init_report() pdf.p(text) pdf.generate()