Exemplo n.º 1
0
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)
Exemplo n.º 2
0
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'}
Exemplo n.º 3
0
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()
Exemplo n.º 4
0
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()
Exemplo n.º 5
0
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
Exemplo n.º 6
0
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()
Exemplo n.º 7
0
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()
Exemplo n.º 8
0
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
Exemplo n.º 10
0
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()
Exemplo n.º 11
0
	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))
Exemplo n.º 12
0
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 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)
Exemplo n.º 14
0
def toPdf(path, text):

    pdf = PDFDocument(path)
    pdf.init_report()
    pdf.p(text)
    pdf.generate()
Exemplo n.º 15
0
    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()
Exemplo n.º 16
0
#!/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()
Exemplo n.º 17
0
    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()
Exemplo n.º 18
0
# 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()

displayValue = locale.currency(cardValue, grouping=True)

for cardNumber in sample(range(100000000), numberOfCards):

    importFile.write(
        f'"{batchID}-{cardNumber:09d}","{batchID}","{cardValue}","{displayValue}","{isoExpDate}","{displayExpDate}"\n'
    )

    pdf.start_keeptogether()
    # Make sure cards are not split across page boundaries
    pdf.h1("PaperCut NG Top Up Card")
    pdf.p(template.format(displayValue, displayExpDate, batchID, cardNumber))
    pdf.end_keeptogether()

pdf.generate()
importFile.close()
Exemplo n.º 19
0
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())