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 packing_slip_pdf(self, order): from pdfdocument.document import PDFDocument from plata.reporting.order import packing_slip_pdf with contextlib.closing(StringIO.StringIO()) as content: pdf = PDFDocument(content) packing_slip_pdf(pdf, order) return content.getvalue()
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 invoice_pdf(self, order): from pdfdocument.document import PDFDocument from plata.reporting.order import invoice_pdf with contextlib.closing(BytesIO()) as content: pdf = PDFDocument(content) invoice_pdf(pdf, order) return content.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 creaPdf(ruta): """ Crea un PDF simple en la ruta indicada """ global pdf pdf = PDFDocument(ruta) pdf.init_report() pdf.h1("Reporte de Test") pdf.hr() print "Guardando en " + ruta
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 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 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_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 test_24_uninitialized_order(self): # This should not crash; generating a PDF exercises the methods # and properties of the order plata.reporting.order.invoice_pdf(PDFDocument(StringIO.StringIO()), Order.objects.create())
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 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()
""" # Initialise the random number generator seed() batchID = input("Please enter the batch ID ") cardValue = float(input(f'Please enter value to appear on each card ')) numberOfCards = int( input(f'Please enter number of cards to created in batch "{batchID}" ')) expiryDays = int( input( "How many days are these cards valid (PaperCut NG will not except these cards after this period)" )) pdf = PDFDocument("printFile.pdf") pdf.init_report() # Must be UTF-16 with correct BOM and MD-DOS line endings importFile = open("importFile", mode="w", newline="\r\n", encoding='utf-16') # PaperCut needs this header line in this format importFile.write( "CardNumber,BatchID,ValueNumber,Value,ExpDate,ExpDateDisplay\n") # Modify to as needed expDate = date.today() + timedelta( days=14) # expire all the cards -- default to 14 days displayExpDate = expDate.strftime("%x") isoExpDate = expDate.isoformat()
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()