コード例 #1
0
def do_xhtml2pdf(input_filepath, output_filepath, output_ext, filter_args):
    from xhtml2pdf import pisa
    with open(input_filepath, 'r') as i_f:
        with open(output_filepath, 'wb') as o_f:
            pisa.CreatePDF(i_f.read(), dest=o_f)
コード例 #2
0
ファイル: chooser.py プロジェクト: huxley/wagtailinvoices
def serve_statement_pdf(date_from, date_to, invoice_list, request):
    # Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources

    def link_callback(uri, rel):
        # use short variable names
        sUrl = settings.STATIC_URL  # Typically /static/
        sRoot = settings.STATIC_ROOT  # Typically /home/userX/project_static/
        mUrl = settings.MEDIA_URL  # Typically /static/media/
        mRoot = settings.MEDIA_ROOT  # Typically /home/userX/project_static/media/

        # convert URIs to absolute system paths
        if uri.startswith(mUrl):
            path = os.path.join(mRoot, uri.replace(mUrl, ""))
        elif uri.startswith(sUrl):
            path = os.path.join(sRoot, uri.replace(sUrl, ""))

        # make sure that file exists
        if not os.path.isfile(path):
            raise Exception(
                    'media URI must start with %s or %s' % \
                    (sUrl, mUrl))
        return path

    def get_total():
        total = 0
        for invoice in invoice_list:
            for service in invoice.service_items.all():
                total = total + service.amount
        return total

    def total_received():
        total = 0
        for invoice in invoice_list:
            if invoice.payment_received:
                for service in invoice.service_items.all():
                    total = total + service.amount
        return total

    def total_outstanding():
        return get_total() - total_received()

    # Render html content through html template with context
    template = get_template(settings.PDF_STATEMENT_TEMPLATE)
    context = {
        'invoice_list': invoice_list,
        'date_from': date_from,
        'date_to': date_to,
        'total': get_total(),
        'total_received': total_received(),
        'total_outstanding': total_outstanding(),
    }
    html = template.render(context)

    # Write PDF to file
    # file = open(os.path.join(settings.MEDIA_ROOT, 'Invoice #' + str(id) + '.pdf'), "w+b")
    file = StringIO.StringIO()
    pisaStatus = pisa.CreatePDF(html, dest=file, link_callback=link_callback)

    # Return PDF document through a Django HTTP response
    file.seek(0)
    # pdf = file.read()
    # file.close()            # Don't forget to close the file handle
    return HttpResponse(file, content_type='application/pdf')
コード例 #3
0
def convert_html_to_pdf(sourceHtml, outputFilename):
    resultFile = open(outputFilename, "w+b")
    pisaStatus = pisa.CreatePDF(sourceHtml, resultFile)
    resultFile.close()
    return pisaStatus.err
コード例 #4
0
ファイル: pdf_report.py プロジェクト: O1Dii/ccm_research
    def convert_html_to_pdf(source_html, output_filename):
        with open(output_filename, "w+b") as result_file:
            pisa_status = pisa.CreatePDF(source_html, dest=result_file)

        return pisa_status.err
コード例 #5
0
    def writeStoryImpl(self, out):

        self.wrap_width = self.getConfig('wrap_width')
        if self.wrap_width == '' or self.wrap_width == '0':
            self.wrap_width = 0
        else:
            self.wrap_width = int(self.wrap_width)

        wrapout = KludgeStringIO()

        if self.hasConfig("file_start"):
            FILE_START = string.Template(self.getConfig("file_start"))
        else:
            FILE_START = self.TEXT_FILE_START

        if self.hasConfig("file_end"):
            FILE_END = string.Template(self.getConfig("file_end"))
        else:
            FILE_END = self.TEXT_FILE_END

        wrapout.write(FILE_START.substitute(self.story.getAllMetadata()))

        self.writeTitlePage(wrapout, self.TEXT_TITLE_PAGE_START,
                            self.TEXT_TITLE_ENTRY, self.TEXT_TITLE_PAGE_END)
        towrap = wrapout.getvalue()

        self.writeTOCPage(wrapout, self.TEXT_TOC_PAGE_START,
                          self.TEXT_TOC_ENTRY, self.TEXT_TOC_PAGE_END)

        towrap = wrapout.getvalue()
        wrapout.close()
        towrap = removeAllEntities(towrap)

        self._write(out, self.lineends(self.wraplines(towrap)))

        if self.hasConfig('chapter_start'):
            CHAPTER_START = string.Template(self.getConfig("chapter_start"))
        else:
            CHAPTER_START = self.TEXT_CHAPTER_START

        if self.hasConfig('chapter_end'):
            CHAPTER_END = string.Template(self.getConfig("chapter_end"))
        else:
            CHAPTER_END = self.TEXT_CHAPTER_END

        storyHTML = ""

        for index, chap in enumerate(self.story.getChapters()):
            if chap.html:
                logging.debug('Writing chapter text for: %s' % chap.title)
                vals = {
                    'url': chap.url,
                    'chapter': chap.title,
                    'index': "%04d" % (index + 1),
                    'number': index + 1
                }

                storyHTML = storyHTML + "<code><pre>" + removeAllEntities(
                    CHAPTER_START.substitute(vals)) + "</pre></code>"
                storyHTML = storyHTML + chap.html
                storyHTML = storyHTML + removeAllEntities(
                    CHAPTER_END.substitute(vals))

        storyHTML = storyHTML + FILE_END.substitute(
            self.story.getAllMetadata())

        header = '<meta charset="utf-8"><style>@page {size: a5;top: 1cm;left: 1cm;right: 1cm;bottom: 1cm;}*{font-size:20px;font-family: "Verdana";}pre{text-align:center;font-weight:bold;page-break-before:always;margin-top:30px;}code{font-size:36px;font-family: "Verdana";}blockquote{margin:0px;}.h1{text-align:center;font-size:48px;margin-top:70px;margin-bottom:20px;padding-top:40px}.h3{margin-top:40px;font-size:24px;text-align:center;}p:nth-of-type(1),p:nth-of-type(2),p:nth-of-type(3){display:none;}</style><p class="h1">' + self.story.getAllMetadata(
        )['title'] + '</p><p class="h3">' + self.story.getAllMetadata(
        )['author'] + '</p><p class="h3">' + self.story.getAllMetadata(
        )['description'] + '</h3>'
        html = header + storyHTML

        with open("my.html", "w") as f:
            f.write(html)

        pisa.showLogging()
        pisa.CreatePDF(StringIO.StringIO(html), out)
コード例 #6
0
ファイル: views.py プロジェクト: code-sonya/usone
def view_extrapay_pdf(request, yearmonth):
    todayYear = int(yearmonth[:4])
    todayMonth = int(yearmonth[5:7])

    # 현재 조직도 변경 후 인원
    extrapayPlatform, sumPlatform = cal_extraPay(
        ['platform Biz', '솔루션팀', 'DB Expert팀'], todayYear, todayMonth)
    extrapayStrategy, sumStrategy = cal_extraPay(
        ['R&D 전략사업부', 'Technical Architecture팀', 'AI Platform Labs'],
        todayYear, todayMonth)

    # 예전 퇴사자들도 표시하기 위해
    extrapayInfra, sumInfra = cal_extraPay(['인프라서비스사업팀'], todayYear,
                                           todayMonth)
    extrapaySolution, sumSolution = cal_extraPay(['솔루션지원팀'], todayYear,
                                                 todayMonth)
    extrapayDB, sumDB = cal_extraPay(['DB지원팀'], todayYear, todayMonth)
    extrapaySupport, sumSupport = cal_extraPay(['경영지원본부'], todayYear,
                                               todayMonth)

    sumEmp = {
        'sumoverHour': 0,
        'sumcompensatedHour': 0,
        'sumoverandfoodCost': 0,
        'sumfoodCost': 0,
        'sumCost': 0
    }
    extrapayList = [
        extrapayPlatform, extrapayStrategy, extrapayInfra, extrapaySolution,
        extrapayDB
    ]
    for sum in [sumPlatform, sumStrategy, sumInfra, sumSolution, sumDB]:
        sumEmp['sumoverHour'] += sum['sumoverHour']
        sumEmp['sumcompensatedHour'] += sum['sumcompensatedHour']
        sumEmp['sumoverandfoodCost'] += sum['sumoverandfoodCost']
        sumEmp['sumfoodCost'] += sum['sumfoodCost']
        sumEmp['sumCost'] += sum['sumCost']

    sumEmp['sumoverHour'] = round(sumEmp['sumoverHour'], 2)
    sumEmp['sumcompensatedHour'] = round(sumEmp['sumcompensatedHour'], 2)
    sumEmp['sumoverandfoodCost'] = round(sumEmp['sumoverandfoodCost'], 2)
    sumEmp['sumfoodCost'] = round(sumEmp['sumfoodCost'], 2)
    sumEmp['sumCost'] = round(sumEmp['sumCost'], 2)

    sumAll = (sumEmp['sumCost'] or 0) + (sumSupport['sumCost'] or 0)
    extrapayList = [
        extrapayPlatform, extrapayStrategy, extrapayInfra, extrapaySolution,
        extrapayDB
    ]
    context = {
        'todayYear': todayYear,
        'todayMonth': todayMonth,
        'extrapayInfra': extrapayInfra,
        'extrapaySolution': extrapaySolution,
        'extrapayDB': extrapayDB,
        'extrapaySupport': extrapaySupport,
        'sumEmp': sumEmp,
        'sumSupport': sumSupport,
        'sumAll': sumAll,
        'extrapayList': extrapayList,
    }

    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename="{}년{}월시간외수당근무내역.pdf"'.format(
            todayYear, todayMonth)

    template = get_template('extrapay/viewextrapaypdf.html')
    html = template.render(context, request)
    # create a pdf
    pisaStatus = pisa.CreatePDF(html,
                                dest=response,
                                link_callback=link_callback)
    # if error then show some funy view
    if pisaStatus.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response
コード例 #7
0
def generate_report(project, run, QC_summary, sample_wells, include_plate):
    '''
    (str | None, str, str, str, bool)
    

    Parameters
    ----------    
        
    - project (str | None): Name of the project
    - run (str): Run ID
    - QC_summary (str): Path to the summary file with QC metrics
    - sample_wells (str): Path to the file with sample plate and well information
    - include_plate (bool): Include metrics plots at the plate level and heatmaps if True
    '''

    # extract QC metrics
    D = read_qc_table(QC_summary)
    # remove samples not in project, but keep controls
    if project:
        D = keep_project_samples(D, project)

    # get the qc table header
    infile = open(QC_summary)
    header = infile.readline().rstrip().split('\t')
    infile.close()

    # get the samples of interest and associated qc metrics
    samples, percent_assigned, read_counts, assigned, percent_discarded, empty, percent_empty = get_samples_qc(
        D)

    # plot qc metrics for the run and project
    metrics_figure = plot_qc_metrics(project, run, '', samples,
                                     percent_assigned, read_counts, assigned,
                                     percent_discarded, empty, percent_empty,
                                     '{0} smMip QC'.format(run))

    # get the samples plate and well location
    samples_plates = get_sample_plate_location(sample_wells)

    # check that all samples have well info
    missing = []
    for i in D:
        if i not in samples_plates:
            print(i)
            missing.append(i)
    assert len(missing) == 0

    #assert sorted([i for i in D]) == sorted([i for i in samples_plates])

    # make a list of plates
    plates = get_plates(samples_plates, D, project)

    # collect the name of the fugure files with heatmaps
    heatmap_names = []
    metric_plots = []

    for current_plate in plates:
        # keep only samples on that plate
        Dprime = {i: D[i] for i in D if samples_plates[i][0] == current_plate}
        # get the samples of interest and associated qc metrics
        s, pa, rc, a, pd, e, pe = get_samples_qc(Dprime)
        metrics_figure_plate = plot_qc_metrics(project, run, current_plate, s,
                                               pa, rc, a, pd, e, pe,
                                               current_plate)
        metric_plots.append(metrics_figure_plate)
        # map samples with qc metrics to each well
        wells = map_samples_to_wells(samples_plates, current_plate)
        # add 0 values to wells without samples
        Dprime[''] = {header[i]: 0 for i in range(1, len(header))}
        # make a 2D list of samples corresponding to each well
        current_samples = samples_on_plate(wells)
        # get 2D array with qc metrics matching samples in each well
        read_counts = qc_metrics_on_plate(Dprime, current_samples, 'reads')
        assigned = qc_metrics_on_plate(Dprime, current_samples, 'assigned')
        percent_assigned = qc_metrics_on_plate(Dprime, current_samples,
                                               'percent_assigned')
        percent_empty = qc_metrics_on_plate(Dprime, current_samples,
                                            'percent_empty_smmips')
        # plot heatmaps for the current plate
        figure_name = plot_heatmaps(read_counts, assigned, percent_assigned,
                                    percent_empty, project, run, current_plate)
        heatmap_names.append(figure_name)

    # get current date (year-month-day)
    current_date = datetime.today().strftime('%Y-%m-%d')

    # make a list to store the text of the report
    L = []

    # add title
    L.append('# smMIP QC Report')

    if project:
        L.append('Project: {0}'.format(project))

    L.append('\n')
    L.append('## Run: {0}'.format(run))
    L.append('Date: {0}'.format(current_date) + '\n')

    L.append('Sample QC metrics are available in the table: {0}'.format(
        os.path.basename(QC_summary)))

    L.append('### Plots of QC metrics per sample\n')

    L.append('![QC_metrics]({0})'.format(metrics_figure))

    L.append('\n')

    if include_plate:
        L.append('Plots of QC metrics per plate\n')
        for i in metric_plots:
            L.append('![qc]({0})'.format(i))
            L.append('\n')
        L.append('Plots of QC metrics per plate and well location\n')
        for i in heatmap_names:
            L.append('![heatmap]({0})'.format(i))
            L.append('\n')
    # convert list to string text
    content = '\n'.join(L)

    # convert markdown to html
    html = markdown.markdown(content)

    if project is None:
        report_file = 'smMIP_QC_Report_{0}.pdf'.format(run)
    else:
        report_file = 'smMIP_QC_Report_{0}_{1}.pdf'.format(project, run)
    # convert html to pdf
    newfile = open(report_file, "wb")
    pisa.CreatePDF(html, newfile)
    newfile.close()
コード例 #8
0
""" save content in Python list """

top10ranking = {}
top10ranking['points'] = df.to_dict('records')

driver.quit()



""" save results in a JSON """

js = json.dumps(top10ranking)

fp = open('ranking.json', 'w')
fp.write(js)
fp.close()



""" export PDF """

source = "<link rel='stylesheet' href='./pdf_style.css'>"
source += "<h1>Top 10 Ranking</h1>" + "<br>"
source += df.to_html()

pdf_file = open("table-players.pdf", "w+b")

pisa_status = pisa.CreatePDF(src=source, dest=pdf_file)

pdf_file.close()
コード例 #9
0
    ret = ''

    def analyze(v):
        ret = None
        for sv in v.subviews():
            if 'textview' in str(sv._get_objc_classname()).lower():
                if 'OMTextEditorView' not in str(sv.superview(
                )._get_objc_classname()):  # not TextView of script
                    return str(sv.text())
            ret = analyze(sv)
            if ret:
                return ret

    ret = analyze(main_view)
    return ret


# Syntax-highlight code
# from omz code at https://forum.omz-software.com/topic/1950/syntax-highlight-python-code-on-screen-while-running
code = editor.get_text() + '\n' + GetConsoleText()
html_formatter = HtmlFormatter(style='colorful')
highlighted_code = highlight(code, PythonLexer(), html_formatter)
styles = html_formatter.get_style_defs()
html = '<html><head><style>%s</style></head><body>%s</body></html>' % (
    styles, highlighted_code)

# html -> pdf
file_name = os.path.splitext(editor.get_path())[0] + '.pdf'
with open(file_name, 'wb') as fil:
    pisa.CreatePDF(html, fil)
コード例 #10
0
    def get(self, request, what=None):

        if not request.user.is_authenticated():
            return redirect('login_user')

        if not what:
            raise Resolver404('Not Found')

        if what == 'admin_dashboard':
            if not request.user.user_type == "admin":
                raise PermissionDenied('permission denied')
            # preparing report data
            loan_rate = Decimal(0)
            ir = Interest.objects.all()
            if ir and ir.count() > 0:
                ir = ir[0]
                loan_rate = ir.interest
            monthly_rate, today, start_date, months_in_operation, form = monthly_rate_today(
            )
            total_membership, expected_total_contributions = expected_contributions(
                monthly_rate)
            banked_cash_at_hand, un_banked_cash_at_hand, expected_total_cash_at_hand, variance = cash_at_hand(
            )
            expenses = Expenses.objects.all().order_by('-date')

            temp_vars = {
                'logo':
                os.path.join(MEDIA_URL, 'logo-web.png'),
                'user':
                request.user,
                'title':
                COMPANY_NAME,
                'loan_rate':
                loan_rate,
                'today':
                today,
                'start_date':
                start_date,
                'months_in_operation':
                months_in_operation,
                'total_membership':
                total_membership,
                'monthly_rate':
                monthly_rate,
                'expected_total_contributions':
                expected_total_contributions,
                'expected_total_cash_at_hand':
                expected_total_cash_at_hand,
                'banked_cash_at_hand':
                banked_cash_at_hand,
                'unbanked_cash_at_hand':
                un_banked_cash_at_hand,
                'variance':
                variance,
                'expenses':
                expenses,
                'all_contributions':
                all_contributions(monthly=monthly_rate, today=today),
                'all_loans':
                all_loans(),
                'all_investments':
                all_investments(),
                'income_statements':
                calculate_income_statement(),
            }
            try:
                template = get_template('print/dashboard.html')
                out_put = template.render(temp_vars)

                # using xhtml2pdf and not weasyprint to generate admin summary PDF file
                name = '{0}.pdf'.format(generate_report_filename())
                response = HttpResponse(content_type='application/pdf')
                response[
                    'Content-Disposition'] = 'inline; filename="{0}.pdf"'.format(
                        name)

                pisaStatus = pisa.CreatePDF(out_put,
                                            dest=response,
                                            link_callback=link_callback,
                                            default_css=my_css)
                # if error then show some funy view
                if pisaStatus.err:
                    return HttpResponse('We had some errors <pre>' + out_put +
                                        '</pre>')
                return response

            except Exception as ex:
                raise Resolver404(
                    'Error Occurered while creating Admin PDF Template: ' +
                    str(ex.message))

        elif what == 'user_profile':

            # preparing report data
            today = date.today()
            contribution = get_user_contributions(request.user, today)
            investment = get_user_investments(request)
            loan = get_user_loans(request)

            temp_vars = {
                'logo': os.path.join(MEDIA_URL, 'logo-web.png'),
                'MEDIA_URL': MEDIA_URL,
                'user': request.user,
                'title': COMPANY_NAME,
                'today': today,
                'contributions': contribution['contributions'],
                'summary': contribution['summary'],
                'i_manage': investment['i_manage'],
                'a_member': investment['a_member'],
                'others': investment['other'],
                'on_loan': loan['on_loan'],
                'on_pay': loan['on_pay'],
                'credit': loan['credit'],
            }
            try:
                template = get_template('print/user_profile.html')
                out_put = template.render(temp_vars)

                # using weasyprint to print the user profile PDF page
                try:
                    name = '{0}.pdf'.format(generate_report_filename())
                    HTML(string=out_put,
                         base_url=request.build_absolute_uri()).write_pdf(
                             os.path.join(REPORT_ROOT, name))

                    fs = FileSystemStorage(REPORT_ROOT)

                    with fs.open(name) as pdf:
                        response = HttpResponse(pdf,
                                                content_type='application/pdf')
                        response[
                            'Content-Disposition'] = 'inline; filename={0}.pdf'.format(
                                name)
                        return response

                except Exception as e:
                    raise Resolver404(
                        'An Error Occurred... While processing the file' +
                        str(e.message))

            except TemplateDoesNotExist:
                raise Resolver404('User Template Not Found')

        else:
            raise Resolver404('URL Not Understood')
コード例 #11
0
def get_obs_pdf(pi, username):

    import xhtml2pdf.pisa as pisa
    import cStringIO as StringIO

    DEFAULT_ZOOM = 12
    OVERVIEW_ZOOM = 8
    MAX_ZOOM = 15
    DEFAULT_WIDTH = 400
    DEFAULT_HEIGHT = 300

    points = {
        'lat': pi.lat,  #TODO get observation point if available
        'lng': pi.lng,
        'start_lat': None,
        'start_lng': None,
        'end_lat': None,
        'end_lng': None
    }

    photo_file = None
    photo_location = None

    comment = ''

    pi_dict = pi.to_dict()
    data_dict = pi.data_dictionary

    rows = ""
    for key in sorted(pi_dict.keys()):
        if key in settings.IGNORED_OUTPUT_FIELDS:
            continue
        val = pi_dict[key]
        if key == settings.FRP_LOCATION_KEY:
            val_lst = val.split()
            points['lat'] = float(val_lst[0])
            points['lng'] = float(val_lst[1])
        if key == settings.AWC_START_POINT_KEY:
            val_lst = val.split()
            points['start_lat'] = float(val_lst[0])
            points['start_lng'] = float(val_lst[1])
        if key == settings.AWC_END_POINT_KEY:
            val_lst = val.split()
            points['end_lat'] = float(val_lst[0])
            points['end_lng'] = float(val_lst[1])
        label = data_dict.get_label(key)
        rows += """
                <tr>
                   <th>%s</th>
                   <td align="left">%s</td>
                </tr>
        """ % (label, val)
        if key == settings.PHOTO_KEY:
            photo_file = str(val)
            photo_location = 'file://127.0.0.1/usr/local/apps/formhub/media/' + username + '/attachments/' + photo_file
        if key == settings.COMMENT_KEY:
            comment = val

    bbox = get_bounding_box([[points['lat'], points['lng']],
                             [points['start_lat'], points['start_lng']],
                             [points['end_lat'], points['end_lng']]])

    if bbox:
        zoom, center = get_zoom_center(bbox, DEFAULT_WIDTH, DEFAULT_HEIGHT)
        if zoom == False:
            zoom = MAX_ZOOM
        if zoom > 2:
            if zoom > MAX_ZOOM:
                zoom = MAX_ZOOM
            else:
                zoom = int(zoom - 1)
        else:
            zoom = 2
    else:
        zoom = DEFAULT_ZOOM
        center = {'lat': point('lat'), 'lng': point('lng')}

    # According to https://developers.google.com/maps/documentation/staticmaps/#api_key
    # "Note that the use of a key is not required, though it is recommended."
    # ... so we go without a key for simplicity
    map_template = "http://maps.googleapis.com/maps/api/staticmap?center=" + str(center['lat']) + "," + str(center['lng']) + "&" \
              "maptype=terrain" \
              "&markers=color:red%%7C%(start_lat)f,%(start_lng)f%%7C%(end_lat)f,%(end_lng)f&sensor=false"
    detail_map = map_template % points + "&zoom=" + str(zoom) + "&size=" + str(
        DEFAULT_WIDTH) + "x" + str(DEFAULT_HEIGHT)  #+ "&scale=2"
    if zoom - 2 <= OVERVIEW_ZOOM:
        if zoom > 4:
            overzoom = zoom - 3
        else:
            overzoom = 2
    else:
        overzoom = OVERVIEW_ZOOM
    overview_map = map_template % points + "&zoom=" + str(
        overzoom) + "&size=" + str(DEFAULT_WIDTH) + "x" + str(
            DEFAULT_HEIGHT)  #+ "&scale=2"

    if photo_file and photo_location:
        photo_html = """
        <br>
        <p> %s </p>
        <img src='%s' style='height:200px;'/>

        """ % (photo_file, photo_location)
    else:
        photo_html = ""

    html = """
    <!-- EWWW table based layout (plays nicer with pisa) -->
    <style>
      td {text-align: left; vertical-align:top}
      th {text-align: right; margin-right:20px}
    </style>

    <table>
      <tr>
        <td align="center" colspan="2">
           <h2> Observation Summary </h2>
           <br>
        </td>
      </tr>
      <tr>
        <td>
            <p> Observation Detail </p>
            <table>
            %s
            </table>
        </td>
        <td>
            <p> Detail Map </p>
            <img src="%s">  
            <br>
            <p> Overview Map </p>
            <img src="%s">  
            %s
        </td>
      </tr>
    </table>

    """ % (rows, detail_map, overview_map, photo_html)

    result = StringIO.StringIO()
    pdf = pisa.CreatePDF(html, result)

    if pdf.err:
        raise Exception("Pisa failed to create a pdf for observation")
    else:
        obs_pdf = PdfFileReader(result)
        obs_page = obs_pdf.getPage(0)
        return obs_page, comment
コード例 #12
0
ファイル: base.py プロジェクト: cryu/camper
 def wrapper(self, *args, **kwargs):
     html = method(self, *args, **kwargs)
     pdf = pisa.CreatePDF(html)
     self.response.headers['Content-Type'] = "application/pdf"
     #self.response.headers['Content-Disposition']="attachment; filename=\"test.pdf\""
     self.response.data = pdf.dest.getvalue()
コード例 #13
0
def create_pdf(pdf_data):
    pdf = StringIO()
    pisa.CreatePDF(StringIO(pdf_data), pdf)
    return pdf
コード例 #14
0
ファイル: api_views.py プロジェクト: wearetherobots/acs40
def pdf_calculator(request):
    request_data = json.loads(request.body)
    result = BytesIO()
    name = 'Commissions_Calculation'
    template = get_template('finances/pdf/calculator.html')
    category_ids = []
    program_ids = []
    pdf_data = []

    for category in request_data['categories']:
        category_ids.append(category['id'])
        for program in category['programs']:
            program_ids.append(program['id'])

    categories = Category.objects.filter(pk__in=category_ids)
    programs = ProgramBase.objects.filter(pk__in=program_ids)

    for i_category in request_data['categories']:
        data = {'model': None, 'programs': [], 'total': i_category['total']}
        for category in categories:
            if category.id == i_category['id']:
                data['model'] = category
                break

        for i_program in i_category['programs']:
            for program in programs:
                if program.id == i_program['id']:
                    data['programs'].append({
                        'model': program,
                        'periods': i_program['periods'],
                        'total': i_program['total']
                    })
                    break

        pdf_data.append(data)

    academic_period = AcademicPeriod.objects.get(
        pk=request_data['academic_period_id'])

    context = {
        'academic_period': academic_period,
        'user': request.user,
        'percentage': request_data['percentage'],
        'total': request_data['total'],
        'categories': pdf_data
    }
    html = template.render(context)

    try:
        with transaction.atomic():
            names = ProfileAttachment.objects.select_for_update().filter(
                profile=request.user.person.profile,
                name__startswith=name).values_list('name', flat=True)

            unique_name = get_unique_name(name, 'pdf', names)

            attachment = ProfileAttachment.objects.create(
                profile=request.user.person.profile, name=unique_name)

            pisa.CreatePDF(html, dest=result, link_callback=fetch_resources)

            attachment.document.save(unique_name, File(result))
    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        log.error('{} at line: {}.'.format(e, exc_tb.tb_lineno))
        return JsonResponse({}, status=400)

    return JsonResponse({})
コード例 #15
0
def render_to_pdf(data, template_name, output_name):
    "Render data in template_name to PDF at output_name"
    template = templates.get_template(template_name)
    html = template.render(data)
    pisa.CreatePDF(html, file(output_name, 'wb'))
コード例 #16
0
ファイル: genpdf.py プロジェクト: patrickgmail/pySequence
def genererFicheValidationHTML(nomFichierPDF, nomFichierHTML, projet):
#    print "genererFicheValidationHTML"
    with open(nomFichierHTML,'r') as f:
        sourceHtml = f.read()


    # Equipe pédagogique
    le = []
    for p in projet.equipe:
        np = p.GetNomPrenom()
        if p.referent:
            np = gras(np)  
        if p.discipline != 'Tec':
            np = italic(np)
        le.append(np)
    NP = liste(le) 
    
    # Elèves
    le = []
    for p in projet.eleves:
        np = p.GetNomPrenom()
        le.append(np)
    NE = liste(le) 
    
    # Typologie
    typo = projet.GetProjetRef().attributs['TYP'][2].split(u"\n")
    TY = "<br>".join([checkbox(i in projet.typologie) + t for i, t in enumerate(typo)])

    
    etab = projet.classe.etablissement+"<br>("+italic(projet.classe.ville)+u")"
    
    champs = {'ACA' : projet.classe.academie,
              'SES' : str(projet.annee+1),
              'TIT' : remplaceCR(projet.intitule),
              'ETA' : etab,
              'PAR' : remplaceCR(projet.partenariat),
              'NBE' : str(len(projet.eleves)),
              'PRX' : projet.montant,
              'SRC' : remplaceCR(projet.src_finance),
              'TYP' : TY,
              'PRE' : remplaceCR(projet.problematique),
              'EQU' : NP,
              'ELE' : NE,
              'OBJ' : remplaceCR(projet.production),
              'SYN' : remplaceCR(projet.synoptique),
              'ORI' : remplaceCR(projet.origine),
              'CCF' : remplaceCR(projet.contraintes),
              'TCH' : table_taches(projet.GetProjetRef().taches, projet.eleves, projet.GetProjetRef())}
    
#    print champs['TCH']
    
    for code, val in champs.items():
        sourceHtml = sourceHtml.replace(u"[["+code+u"]]", val)
    
    sourceHtml = sourceHtml.replace("{{MEDIA_URL}}", os.path.join(util_path.PATH, r"..", DOSSIER_REF))
    
    resultFile = open(nomFichierPDF, "w+b")

    # convert HTML to PDF
    pisaStatus = pisa.CreatePDF(
                                sourceHtml,                # the HTML to convert
                                dest=resultFile,show_error_as_pdf = True)           # file handle to recieve result

    # close output file
    resultFile.close()                 # close output file

#    print pisaStatus.err
    # return True on success and False on errors
    return pisaStatus.err == 0
コード例 #17
0
ファイル: views.py プロジェクト: code-sonya/usone
def view_overhour_pdf(request, extraPayId):
    extrapay = ExtraPay.objects.filter(Q(extraPayId=extraPayId)) \
        .values('overHourDate__year', 'overHourDate__month', 'empId__empName', 'empId__empSalary', 'empId__empDeptName', 'empId__empCode', 'extraPayId', 'empId__empPosition_id__positionName',
                'compensatedComment', 'compensatedHour', 'payStatus', 'empSalary').first()
    overhours = OverHour.objects.filter(
        Q(extraPayId=extraPayId) & ~Q(overHour=0) & Q(overHourStatus='Y'))
    sum_overhours = overhours.aggregate(
        sumOverhour=Sum('overHour'),
        sumOverhourWeekDay=Sum('overHourWeekDay'),
        sumServicehour=Round(Sum('serviceId__serviceHour')),
        sumOverhourCost=Sum('overHourCost'),
        sumOverhourCostWeekDay=Sum('overHourCostWeekDay'),
        sumFoodCost=Sum('foodCost'))
    foodcosts = OverHour.objects.filter(
        Q(extraPayId=extraPayId) & Q(overHour=0) & Q(overHourStatus='Y'))
    sum_foodcosts = foodcosts.aggregate(
        sumServicehour=Sum('serviceId__serviceHour'),
        sumFoodCost=Sum('foodCost'))

    if extrapay['payStatus'] == 'N':
        real_extraPay = int(
            ((sum_overhours['sumOverhour'] or 0) -
             (extrapay['compensatedHour'] or 0)) * 1.5 * extrapay['empSalary'])
        if real_extraPay > 200000:
            real_extraPay = 200000

        sum_costs = {
            'extraPayDate':
            '{}.{}'.format(extrapay['overHourDate__year'],
                           extrapay['overHourDate__month']),
            'overHour':
            sum_overhours['sumOverhour'],
            'compensatedHour':
            extrapay['compensatedHour'],
            'extraPayHour': (sum_overhours['sumOverhour'] or 0) -
            (extrapay['compensatedHour'] or 0),
            'extraPay':
            real_extraPay,
            'foodCost':
            int((sum_overhours['sumFoodCost'] or 0) +
                (sum_foodcosts['sumFoodCost'] or 0)),
            'sumPay':
            int(real_extraPay + (sum_overhours['sumFoodCost'] or 0) +
                (sum_foodcosts['sumFoodCost'] or 0))
        }
    else:
        sum_costs = {
            'extraPayDate':
            '{}.{}'.format(extrapay['overHourDate__year'],
                           extrapay['overHourDate__month']),
            'overHour':
            sum_overhours['sumOverhour'] + sum_overhours['sumOverhourWeekDay'],
            'compensatedHour':
            extrapay['compensatedHour'],
            'extraPayHour':
            sum_overhours['sumOverhour'] +
            sum_overhours['sumOverhourWeekDay'] -
            (extrapay['compensatedHour'] or 0),
            'extraPay':
            int(sum_overhours['sumOverhourCost'] +
                sum_overhours['sumOverhourCostWeekDay']),
            'foodCost':
            0,
            'sumPay':
            int(sum_overhours['sumOverhourCost'] +
                sum_overhours['sumOverhourCostWeekDay']),
        }
    context = {
        'overhour': overhours,
        'extrapay': extrapay,
        'foodcosts': foodcosts,
        'sum_overhours': sum_overhours,
        'sum_foodcosts': sum_foodcosts,
        'sum_costs': sum_costs,
    }

    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename="{}님시간외수당근무내역.pdf"'.format(
            extrapay['empId__empName'])

    template = get_template('extrapay/viewoverhourpdf.html')
    html = template.render(context, request)
    # create a pdf
    pisaStatus = pisa.CreatePDF(html,
                                dest=response,
                                link_callback=link_callback)
    # if error then show some funy view
    if pisaStatus.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response
コード例 #18
0
ファイル: views.py プロジェクト: sm1990/request-management
    def get(self, request, format=None):
        """
            Get incident by incident id
        """
        param_report = self.request.query_params.get('report', None)
        start_date = self.request.query_params.get('start_date', '')
        end_date = self.request.query_params.get('end_date', '')
        detailed_report = True if self.request.query_params.get(
            'detailed_report', 'false') == 'true' else False
        complain = True if self.request.query_params.get(
            'complain', 'false') == 'true' else False
        inquiry = True if self.request.query_params.get(
            'inquiry', 'false') == 'true' else False

        if start_date == '':
            start_date = datetime.date.today().strftime("%Y-%m-%d 16:00:00")
        else:
            start_date = start_date.replace("T", " ", 1)
        if end_date == '':
            end_date = datetime.date.today().strftime("%Y-%m-%d 16:00:00")
        else:
            end_date = end_date.replace("T", " ", 1)

        if param_report is None or param_report == "":
            return Response("No report specified",
                            status=status.HTTP_400_BAD_REQUEST)

        table_html = None
        table_title = None
        incident_type_string = incident_type_title(complain, inquiry)

        # if param_report == "police_division_summary_report":
        #     table_html = get_police_division_summary()
        #     table_title = "Police Division Summary Report"

        layout = "A4 portrait"
        title = """from %s to %s by """ % (start_date, end_date)
        if param_report == "category_wise_summary_report":
            table_html = get_category_summary(start_date, end_date,
                                              detailed_report, complain,
                                              inquiry)
            if detailed_report:
                table_title = title + "District and Category"
            else:
                table_title = title + "Category"

        elif param_report == "mode_wise_summary_report":
            table_html = get_mode_summary(start_date, end_date,
                                          detailed_report, complain, inquiry)
            if detailed_report:
                layout = "A4 landscape"
                table_title = title + "District and Mode"
            else:
                table_title = title + "Mode"

        elif param_report == "district_wise_summary_report":
            table_html = get_district_summary(start_date, end_date,
                                              detailed_report, complain,
                                              inquiry)
            table_title = title + "District"

        elif param_report == "severity_wise_summary_report":
            table_html = get_severity_summary(start_date, end_date,
                                              detailed_report, complain,
                                              inquiry)
            if detailed_report:
                table_title = title + "District and Severity"
            else:
                table_title = title + "Severity"

        elif param_report == "subcategory_wise_summary_report":
            table_html = get_subcategory_summary(start_date, end_date,
                                                 detailed_report, complain,
                                                 inquiry)
            if detailed_report:
                layout = "A3 landscape"
                table_title = title + "District and Subcategory"
            else:
                table_title = title + "Subcategory"

        elif param_report == "incident_date_wise_summary_report":
            table_html = get_incident_date_summary(start_date, end_date,
                                                   detailed_report, complain,
                                                   inquiry)
            table_title = title + "Incident Date"

        elif param_report == "status_wise_summary_report":
            table_html = get_status_summary(start_date, end_date,
                                            detailed_report, complain, inquiry)
            if detailed_report:
                table_title = title + "District and Status"
            else:
                table_title = title + "Status"

        if table_html is None:
            return Response("Report not found",
                            status=status.HTTP_400_BAD_REQUEST)

        # Prepare report header
        sql3 = incident_type_query(complain, inquiry)
        sql = """SELECT
                     Count(id) as TotalCount
                 FROM   incidents_incident WHERE %s""" % sql3
        dataframe = pd.read_sql_query(sql, connection)
        total_count = dataframe['TotalCount'][0]

        table_html = apply_style(
            decode_column_names(table_html).replace(".0", "", -1).replace(
                "(Total No. of Incidents)",
                """<strong>(Total No. of Incidents from %s to %s)</strong>""" %
                (start_date, end_date),
                -1).replace("(Unassigned)", "<strong>(Unassigned)</strong>",
                            -1), table_title, incident_type_string, layout,
            total_count)

        response = HttpResponse(content_type='application/pdf')
        response['Access-Control-Expose-Headers'] = 'Title'
        response[
            'Title'] = """Incidents reported within the period %s %s %s.pdf""" % (
                table_title, incident_type_string,
                datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        pisa.CreatePDF(table_html, dest=response)
        return response
コード例 #19
0
    def publipostage(self, fichier, template, texte, num_etu, objects):
        wb = xlrd.open_workbook(os.path.join(BASE_DIR, fichier))
        sh = wb.sheet_by_index(0)
        translation.activate(settings.LANGUAGE_CODE)
        i = 0
        for rownum in range(sh.nrows):
            i += 1
            if rownum == 0:
                continue

            if sh.cell(rownum, 0).value == "":
                break
            values = sh.row_values(rownum)
            cod_etu = int(values[num_etu])
            context = {
                'static':
                os.path.join(BASE_DIR,
                             'documents/static/images/').replace('\\', '/')
            }

            context['num_group'] = int(values[1])

            context['date_1'] = self.date(values[3])
            context['salle_1'] = int(values[2])
            context['date_2'] = self.date(values[5])
            context['salle_2'] = int(values[4])

            individu = Individu.objects.get(cod_etu=cod_etu)
            f = open('convocation.pdf', 'wb')

            context['individu'] = individu
            pdf = pisapdf.pisaPDF()
            pdf.addDocument(pisa.CreatePDF(render_to_string(
                template, context)))  # on construit le pdf
            if self.deroulement:
                pdf.addFromFile(self.deroulement)

            pdf.join(f)
            liste_email = [
                individu.get_email(2014),
                email_ied(individu), '*****@*****.**'
            ] if not settings.DEBUG else ['*****@*****.**']
            email = EmailMessage(subject=objects,
                                 body=texte,
                                 from_email='*****@*****.**',
                                 to=liste_email)

            f.close()

            f = open('convocation.pdf', 'r')
            email.attach(filename='convocation_regoupement.pdf',
                         content=f.read())
            email.send()
            print "email envoyé à %s" % individu.cod_etu
            if i == 100:
                time.sleep(5)
                i = 0

            f.close()
            if settings.DEBUG:
                if rownum == 1:
                    break
        print "fini"
コード例 #20
0
    def form_valid(self, form, detalle_compra_form_set):

        #obtenemos la ultima de su  serie prara generar un nuevo numero
        qsComp_last = Compra.objects.filter(
            lfact=form.instance.titular.letra).order_by('nfact').last()

        if qsComp_last:
            form.instance.nfact = qsComp_last.nfact + 1
        else:
            form.instance.nfact = 1
        form.instance.lfact = form.instance.titular.letra

        self.object = form.save()
        detalle_compra_form_set.instance = self.object
        detalle_compra_form_set.save()
        total_base = 0

        detalles = DetalleCompra.objects.filter(
            compra=self.object).order_by('pk')
        for detalle in detalles:
            d = {
                'producto': detalle.producto,
                'cantidad': detalle.cantidad,
                'precio_compra': detalle.precio_compra
            }

            #sumamos los kilos de cada detalle en su almacen(silo)
            #p = Producto.objects.get(descripcion=detalle.producto)
            #p.kilos = p.kilos + detalle.cantidad
            #p.save()

            detalle.producto.kilos += detalle.cantidad
            detalle.producto.save()

            # si el producto entra a un silo con lote
            if detalle.producto.lote:
                detalle.lote_heredado = detalle.producto.lote
                print("detalle lote", detalle.lote_heredado)
                detalle.save()
                #detalle.save(update_fields=["lote_heredado"])
                #DetalleVenta.objects.get(pk=detalle.pk).save(update_fields=["lote_heredado"])

            #qs = DetalleVenta.objects.get(pk =detalle.pk)
            #print("guardado en historico ", qs.producto, qs.cantidad, qs.precio_venta, qs.lote_heredado)
            Historico.objects.create(compra=detalle.compra,
                                     producto=detalle.producto,
                                     cantidad=detalle.cantidad,
                                     precio_compra=detalle.precio_compra,
                                     fecha=detalle.fecha,
                                     lote_heredado=detalle.lote_heredado,
                                     kilos_actuales=detalle.producto.kilos)

            #calculamos su precio base
            total_detalle = detalle.cantidad * detalle.precio_compra
            print("valores en €")
            print(detalle.producto, total_detalle)
            total_base = total_base + total_detalle

        print("base ", total_base)
        #aplicamos impuestos
        form.instance.base = total_base
        form.instance.imp_aplicado = total_base * form.instance.impuestos.impuesto1 / 100
        print("valor de impuestto 1 ", form.instance.imp_aplicado)
        #Comprobamos si hay un segundo impuesto a aplicar
        if form.instance.impuestos.impuesto2:
            if form.instance.impuestos.se_calcula_con == "BASE":
                form.instance.imp_aplicado = form.instance.imp_aplicado + total_base * form.instance.impuestos.impuesto2 / 100
                print("calculando impuesto 2 BASE ",
                      form.instance.imp_aplicado)
            if form.instance.impuestos.se_calcula_con == "TOTAL":
                form.instance.imp_aplicado = form.instance.imp_aplicado + (
                    form.instance.imp_aplicado +
                    total_base) * form.instance.impuestos.impuesto2 / 100
                print("calculando impuesto 2 TOTAL",
                      form.instance.imp_aplicado)
        form.instance.total = total_base + form.instance.imp_aplicado

        print("impuestos ", form.instance.imp_aplicado)
        print("total", form.instance.total)

        form.instance.save()

        ############# PDF ###################

        # obtenemos los detalles de esta facuta para crear un nested dict
        detalles = DetalleCompra.objects.filter(compra=form.instance.pk)
        lineas = {}
        i = 1
        for d in detalles:
            detalle_total = d.precio_compra * d.cantidad
            lineas['linea' + str(i)] = {
                'producto': d.producto.variedad,
                'cantidad': d.cantidad,
                'precio': d.precio_compra,
                'total': detalle_total,
                'lote_heredado': d.lote_heredado
            }
            i = i + 1

        compra = Compra.objects.get(pk=form.instance.pk)
        context = {
            'numero': compra.nfact,
            'fecha': compra.fecha,
            'forma_pago': compra.forma_pago,
            'titular_nombre': compra.titular.nombre,
            'titular_cif': compra.titular.cif,
            'titular_direccion': compra.titular.direccion,
            'proveedor_nombre': compra.proveedor.razon_social,
            'proveedor_ruc': compra.proveedor.ruc,
            'proveedor_direccion': compra.proveedor.direccion,
            'proveedor_certificado': compra.proveedor.entidad_certificadora,
            'base': compra.base,
            'impuestos': compra.impuestos,
            'imp_aplicado': compra.imp_aplicado,
            'total': compra.total,
            'lineas': lineas
        }
        print(context)
        '''context = {
            'acta': qsacta,
            'laboratorio': qslaboratorio,
            'muestreo': qsmuestreo,
            'pk': pk,
            'tipo': tipo
        }'''

        template_path = 'plantilla_email.html'
        template = get_template(template_path)
        # html = template.render(form.instance.__dict__)
        html = template.render(context)
        # print(form.instance.__dict__)

        ## definir los datos del diccionario, este no sirve
        ## hacer bien los estilos, los de boostrap no funcionan
        ## los estilos que soporta estan bastante limitados
        ## https://xhtml2pdf.readthedocs.io/en/latest/reference.html#supported-css-properties

        ndocumento1 = "factura" + str(form.instance.nfact) + ".pdf"
        #ddocumento = os.path.join(settings.MEDIA_ROOT, ndocumento1)
        ddocumento = ndocumento1
        outFilename = ddocumento
        outFile = open(outFilename.encode("utf-8"), "w+b")
        pisaStatus = pisa.CreatePDF(html.encode('utf-8'),
                                    dest=outFile,
                                    encoding='utf-8')
        outFile.close()
        ndocumento = ddocumento
        # ddocumento = os.path.join(settings.MEDIA_ROOT, ndocumento)
        leerdocumento = open(ddocumento.encode("utf-8"), "rb").read()

        ############### EMAIL ##################33

        b = base64.b64encode(leerdocumento).decode("utf-8", "ignore")

        nombredocumento = "factura" + str(form.instance.nfact) + ".pdf"
        email = "*****@*****.**"
        asunto = "Factura de compra"
        cuerpo = "Buenos dias, adjuntamos factura de compra"
        body = cuerpo
        # Replace this texto in plantilla cuerpo
        body_content = mark_safe(body)
        html_content = mark_safe(body_content)
        remitente = settings.EMAIL_HOST_USER
        destinatario = email
        try:
            msg = EmailMessage(asunto, html_content, remitente, [destinatario])
            msg.attach(nombredocumento, leerdocumento, "application/pdf")
            msg.content_subtype = "pdf"  # Main content is now text/html
            msg.encoding = 'utf-8'
            msg.send()
            print("mensaje enviado ")
        except Exception as e:
            print("no se ha podido enviar ", e)

        return HttpResponseRedirect(self.success_url)
コード例 #21
0
def create_pdf(pdf_data):
    pdf = StringIO()
    pisa.CreatePDF(StringIO(pdf_data.encode('utf-8')), pdf)
    return pdf
コード例 #22
0
def finalize(request, pk, version=0):
    """
    Finalize the grades and print. Only for assessors.

    :param request:
    :param pk: pk of Distribution to grade
    :param version: 0 for summary page, 1 for printable page, 2 for pdf export
    :return:
    """
    ts = get_timeslot()
    if not hasattr(ts, 'resultoptions'):
        raise PermissionDenied("Results menu is not yet visible.")
    else:
        if not get_timeslot().resultoptions.Visible:
            raise PermissionDenied("Results menu is not yet visible.")

    dstr = get_object_or_404(Distribution, pk=pk)

    if not hasattr(dstr, 'presentationtimeslot'):
        raise PermissionDenied('This student does not have a presentation planned. Please plan it first.')

    if not request.user.is_superuser and \
            request.user not in dstr.presentationtimeslot.Presentations.Assessors.all() and \
            request.user != dstr.Proposal.Track.Head:
        raise PermissionDenied("You are not the correct owner of this distribution. "
                               " Grades can only be finalized by assessors or track heads. "
                               " To get a preview of the print view, use the 'Print Preview' button.")
    version = int(version)
    # check if grade is valid
    error_list = ''
    for cat in GradeCategory.objects.filter(TimeSlot=get_timeslot()):
        try:
            cat_res = cat.results.get(Distribution=dstr)
            if not cat_res.is_valid():
                error_list += ('<li>Category {} is not completed.</li>'.format(cat))
        except CategoryResult.DoesNotExist:
            error_list += ('<li>Category {} is missing</li>'.format(cat))
    if error_list:
        return render(request, "base.html", context={
            'Message': '<h1>The results of this student are not yet finished</h1><p>The following error(s) occurred:</p><ul>{}</ul>'.format(error_list),
            "return": "results:gradeformstaff",
            "returnget": str(pk),
        })

    if version == 0:  # The normal page summarizing the grades of the student
        return render(request, "results/finalize_grades.html", {
            "dstr": dstr,
            "catresults": dstr.results.all(),
            "final": all(f.Final is True for f in dstr.results.all()),
            "finalgrade": dstr.TotalGradeRounded(),
            "preview": False,
        })
    else:  # type 1 and 2, finalize grades.
        if get_timephase_number() != 7:
            raise PermissionDenied("Finalize grades is only possible in the time phase 'Presentation of results'")
        for cat in dstr.results.all():  # set final to True, disable editing from here onward.
            cat.Final = True
            cat.save()
        if version == 1:  # printable page with grades
            return render(request, "results/print_grades_pdf.html", {
                "dstr": dstr,
                "catresults": dstr.results.all(),
                "finalgrade": dstr.TotalGradeRounded(),
            })
        elif version == 2:  # pdf with grades
            html = get_template('results/print_grades_pdf.html').render({
                "dstr": dstr,
                "catresults": dstr.results.all(),
                "finalgrade": dstr.TotalGradeRounded(),
            })
            buffer = BytesIO()
            pisa_status = pisa.CreatePDF(html.encode('utf-8'), dest=buffer, encoding='utf-8')
            if pisa_status.err:
                raise Exception("Pisa Failed PDF creation in print final grade for distribution {}.".format(dstr))
            buffer.seek(0)
            response = HttpResponse(buffer, 'application/pdf')
            response['Content-Disposition'] = 'attachment; filename="bepresult_{}.pdf"'.format(dstr.Student.usermeta.get_nice_name())
            return response
    raise PermissionDenied('Invalid type.')
コード例 #23
0
ファイル: admin.py プロジェクト: Maxwell-Icharia/poptraq
def create_pdf(pdf_data):
    pdf = BytesIO()
    pisa.CreatePDF(BytesIO(pdf_data.encode('utf-8')), pdf)
    return pdf
コード例 #24
0
ファイル: core_tools.py プロジェクト: cyrildzumts/lyshop
def generate_sold_products_reports(seller=None, debug=False):
    template_name = "reports/sold_products.html"
    now = datetime.datetime.now()
    start_date = now - datetime.timedelta(days=now.day - 1,
                                          hours=now.hour,
                                          minutes=now.minute,
                                          seconds=now.second)
    end_delta = datetime.timedelta(days=1, hours=-23, minutes=-59, seconds=-59)
    end_date = datetime.datetime(now.year, now.month + 1, 1) - end_delta
    user_seller = None
    if isinstance(seller, str):
        try:
            user_seller = User.objects.get(username=seller)
            #entry_list = OrderItem.objects.filter(product__product__sold_by=user_seller, order__is_paid=True, order__is_closed=True ,order__created_at__year=now.year, order__created_at__month=now.month)
            entry_list = SoldProduct.objects.filter(
                seller=user_seller,
                created_at__year=now.year,
                created_at__month=now.month)
        except User.DoesNotExist:
            logger.warn(
                "report generator generate_sold_products_reports : no seller {seller} found"
            )
            return None
        #total = Recharge.objects.filter(created_at__year=now.year, created_at__month=now.month).aggregate(total=Sum('amount')).get('total') or 0
    elif isinstance(seller, User):
        user_seller = seller
        entry_list = SoldProduct.objects.filter(seller=user_seller,
                                                created_at__year=now.year,
                                                created_at__month=now.month)
    else:
        entry_list = SoldProduct.objects.filter(created_at__year=now.year,
                                                created_at__month=now.month)

    total_aggregrate = entry_list.aggregate(total=Sum('total_price'),
                                            count=Sum('quantity'))
    total = total_aggregrate.get('total') or 0
    count = total_aggregrate.get('count') or 0

    context = {
        'SITE_NAME': settings.SITE_NAME,
        'SITE_HOST': settings.SITE_HOST,
        'CONTACT_MAIL': settings.CONTACT_MAIL,
        'DATE': now,
        'orientation': 'portrait',
        'FRAME_NUMBER': 2,
        'page_size': 'letter portrait',
        'border': debug,
        'entry_list': entry_list,
        'TOTAL': total,
        'COUNT': count,
        'CURRENCY': settings.CURRENCY,
        'REPORT_TITLE': _('Sold Product Card Sumary'),
        'start_date': start_date,
        'end_date': end_date
    }
    report_html = render_to_string(template_name, context)
    report_file = io.BytesIO()
    pdf_status = pisa.CreatePDF(report_html, dest=report_file, debug=False)
    if pdf_status.err:
        logger.error("error when creating the report pdf")
        return None
    else:
        logger.info("sold voucher report pdf created")
    return report_file
コード例 #25
0
def home(request):
    
    if request.session['last_name']:

        if request.method == 'POST':

            form = newForm(request.POST)

            if form.is_valid():
                age = float(form.cleaned_data['age'])
                height = float(form.cleaned_data['height'])
                weight = float(form.cleaned_data['weight'])
                fcvc = float(form.cleaned_data['fcvc'])
                algo = form.cleaned_data['algo']
                download = form.cleaned_data['download']
                
                x_new = np.array([age, height, weight, fcvc]).reshape(1, -1)
                
                mean_age = 24.31259990857412
                std_age = 6.345968273732241
                
                mean_height = 1.7016773533870182
                std_height = 0.09330481986792002

                mean_weight = 86.58605812648037
                std_weight = 26.19117174520469

                mean_fcvc = 2.4190430615821916
                std_fcvc = 0.5339265785033023
                x_new[0][0] = (x_new[0][0] - mean_age) / std_age
                x_new[0][1] = (x_new[0][1] - mean_height) / std_height
                x_new[0][2] = (x_new[0][2] - mean_weight) / std_weight
                x_new[0][3] = (x_new[0][3] - mean_fcvc) / std_fcvc
                classes = ['Insufficient Weight', 'Normal Weight', 'Obesity Type I', 'Obesity Type II',
                            'Obesity Type III', 'Overweight Level I', 'Overweight Level II']
            
                if algo == 'knn':
                    KNN = load('prediction/KNN.joblib')
                    predicted_class = classes[KNN.predict(x_new)[0]]
                    classes_index = np.argsort(KNN.predict_proba(x_new), axis=1)[0][::-1]
                    probabilities = np.around(np.sort(KNN.predict_proba(x_new), axis=1)[0][::-1], decimals=4)
                    classes_prob = []

                    for i in classes_index:
                        classes_prob.append(classes[i])
        
                if algo == 'randomforest':
                    RandomForest = load('prediction/RandomForest.joblib')
                    predicted_class = classes[RandomForest.predict(x_new)[0]]
                    classes_index = np.argsort(RandomForest.predict_proba(x_new), axis=1)[0][::-1]
                    probabilities = np.around(np.sort(RandomForest.predict_proba(x_new), axis=1)[0][::-1], decimals=4)
                    classes_prob = []

                    for i in classes_index:
                        classes_prob.append(classes[i])

                if algo == 'smv':
                    SVM = load('prediction/SVM.joblib')
                    predicted_class = classes[SVM.predict(x_new)[0]]
                    classes_index = np.argsort(SVM.predict_proba(x_new), axis=1)[0][::-1]
                    probabilities = np.around(np.sort(SVM.predict_proba(x_new), axis=1)[0][::-1], decimals=4)
                    classes_prob = []

                    for i in classes_index:
                        classes_prob.append(classes[i])
                
                classes_prob = zip(classes_prob, probabilities * 100)
                
                if download == 'yes':

                    template_path = 'download.php'
                
                    context = {'age': age, 'height':height, 'weight': weight, 'fcvc':fcvc,'predicted_class': predicted_class, 
                        'classes_prob':classes_prob,'last_name': request.session['last_name'], 'first_name': request.session['first_name']}
                    
                    # Create a Django response object, and specify content_type as pdf
                    response = HttpResponse(content_type='application/pdf')
                    
                    #if download:
                    response['Content-Disposition'] = 'attachment; filename="obesity level test.pdf"'
                    
                    # find the template and render it.
                    template = get_template(template_path)
                    html = template.render(context)

                    # create a pdf
                    pisa_status = pisa.CreatePDF(html, dest=response)
                    
                    form.download = 'no'
                    print(form.download)

                    # if error then show some funy view
                    if pisa_status.err:
                        return HttpResponse('We had some errors <pre>' + html + '</pre>')
                    return response

                return render(request, 'home.php', {'form': form, 'predicted_class': predicted_class, 
                            'classes_prob':classes_prob,})
            else:
                return render(request, 'home.php', {'form': form})
        else:
            
            form = newForm()
            return render(request, 'home.php', {'form': form})

    else:
        return redirect('name')
コード例 #26
0
ファイル: pdf_creator.py プロジェクト: Dialjini/bankDocs
from xhtml2pdf import pisa
import os
from flask import render_template, Flask
import codecs

html = codecs.open(os.path.dirname(__file__) + '/files/AlphaBank/index.html',
                   'r',
                   encoding='utf-8')
test = html.read().replace('{{ path }}',
                           os.path.dirname(__file__) + '/files/AlphaBank/')
# print(test)
print(os.path.dirname(__file__))
with open(os.path.dirname(__file__) + '/files/downloaded.pdf', 'wb') as out:
    pisa.CreatePDF(src=test, dest=out, encoding='utf-8')

html.close()
コード例 #27
0
def convert_html_to_pdf(source_html, output_filename):
    result_file = open(output_filename, "w+b")
    pisa_status = pisa.CreatePDF(source_html, dest=result_file)
    result_file.close()
    return pisa_status.err
コード例 #28
0
ファイル: functions.py プロジェクト: tayste5000/seqrep_py
def gen_reports(sequencing_dir, wb, line_length=100):
    '''
    Take an excel spreadsheet containing alignment inputs, generate the alignments, 
    and produce a .pdf file for each alignment

    parameters
    ----------

    sequencing_dir : str
        The path to the directory which contains all of the sequencing files
    wb : ??? (openpyxl workbook object)
        openpyxl object of the spreadsheet which contains the alignment input data
    line_length : int
        The number of characters per each line in the formatted alignment
    '''

    # Make the reports directory
    report_dirname = os.path.join(sequencing_dir, 'reports')

    print('Generating {}.'.format(report_dirname))
    os.mkdir(report_dirname)

    # Get rows and column labels from the spreadsheet
    ws = wb.get_active_sheet()

    rows = list(ws.rows)
    header = list(map(lambda x: x.value, rows.pop(0)))

    # Make a custom substition matrix to allow alignments of sequences with 'N' nucleotides
    mtrx = skbio.alignment.make_identity_substitution_matrix(1,
                                                             -2,
                                                             alphabet='ACGTN')

    # Iterate through the rows
    for row in rows:

        # Make row into a dict with column name as the index
        row_vals = map(lambda x: x.value, row)
        row_dict = dict(zip(header, row_vals))

        # Convert to reverse complement if reverse sequence
        if row_dict['Rev?']:
            sequence = skbio.sequence.DNA(row_dict['Sequence'].strip(),
                                          lowercase=True).reverse_complement()
            row_dict['Sequence'] = str(sequence)

        # Generate alignment
        print("Aligning {} to {}\r".format(row_dict['Filename'],
                                           row_dict['Construct']))
        a = skbio.alignment.StripedSmithWaterman(row_dict['Sequence'].lower())(
            row_dict['Template Sequence'].lower())

        # Get the sequence position where the alignment starts
        query_begin = a.query_begin
        target_begin = a.target_begin

        # format alignment
        query_sequence, target_sequence, match_str = gen_aligned_seqs(a)

        # Initialize formatted alignment string
        seq = ''

        # Split the alignment up into fragments according to line_length and format
        for i in range(len(query_sequence) // line_length + 1):
            a = query_sequence[0 + i * line_length:line_length +
                               i * line_length]
            b = target_sequence[0 + i * line_length:line_length +
                                i * line_length]
            match = match_str[0 + i * line_length:line_length +
                              i * line_length]

            # Determine the actually sequence length covered by the line
            a_length = len(a) - a.count('-')
            b_length = len(b) - b.count('-')

            # Format
            seq += format_seq_line(a, b, match,
                                   (query_begin, query_begin + a_length - 1),
                                   (target_begin, target_begin + b_length - 1))

            # Increment length
            query_begin += a_length
            target_begin += b_length

        # Prepare into html file
        html = format_html(row_dict['Filename'], row_dict['Construct'], seq)

        # Generate .pdf file
        basename = row_dict['Filename'].split('.')[0]
        report_filename = os.path.join(report_dirname,
                                       '{}.pdf'.format(basename))

        with open(report_filename, "w+b") as reportFile:
            # convert HTML to PDF
            pisaStatus = pisa.CreatePDF(html, dest=reportFile)
コード例 #29
0
def addproforma(request,id):
    idprefix=request.POST['idprefix']
    print(idprefix,'kkkkkkkkkk')
    fc=TAapplicationmodel.objects.filter(user_id=id,idprefix=idprefix).first()
    print(fc.idprefix,'kkk')
    # tafil=TAapplicationfiles.objects.filter(user_id=fc.user_id,filecategory="TAapplication",refid=fc.idprefix).first()

    curr_path = "/"+str(fc.user_id)+ fc.idprefix+"Annexure 3/Proforma_A/"
    curr_path=curr_path.replace('/','\\')
    new_path = os.path.join(settings.MEDIA_ROOT + curr_path)
    if os.path.isdir(new_path):
        with open(new_path+'Proforma_A.pdf', 'rb') as pdf:
            response = HttpResponse(pdf.read(),content_type='application/pdf')
            response['Content-Disposition'] = 'filename=some_file.pdf'
        return response
    else:
        print('sai',fc.user_id,fc.idprefix)
        form = proforma_A_form(request=fc.user_id,idpre=fc.idprefix)
        pro=proforma_A_model.objects.filter(user_id=fc.user_id,idprefix=idprefix).first()
        taa=TAapplicationmodel.objects.filter(user_id=fc.user_id,idprefix=idprefix).first()
        if pro:
            template = get_template('dealing officer/proformapdf.html')
            date_joined = datetime.now()
            formatted_datetime = date_joined.strftime("%Y-%m-%d")
            print(formatted_datetime,'dte')
            taf=TAapplicationfiles.objects.filter(user_id=fc.user_id,filecategory='DAL_MDI',refid=fc.idprefix).first()
            dalurl=''
            if taf:
                aesurl=taf.filepath
                if taf.ext=='.pdf':
                    pdfurl = aesurl[:-4]
                    print('aesview',aesurl)
                    print('pdfview',pdfurl)
                    bufferSize = 64 * 1024
                    passw = "#EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e"
                    encFileSize = stat(aesurl).st_size
                    with open(aesurl, "rb") as fIn:
                        with open(pdfurl, "wb") as fOut:
                            pyAesCrypt.decryptStream(fIn, fOut, passw, bufferSize, encFileSize)
                    pdfpath = pdfurl[25:]
                    print(pdfpath,'pppppppppp')
                    curr_path=pdfpath
                    dalurl='http://127.0.0.1:8000/media'+curr_path
                    print(dalurl,'pppp11111pppppp')
            taf=TAapplicationfiles.objects.filter(user_id=fc.user_id,filecategory='BOM',refid=fc.idprefix).first()
            bomurl=''
            if taf:
                aesurl=taf.filepath
                if taf.ext=='.pdf':
                    pdfurl = aesurl[:-4]
                    print('aesview',aesurl)
                    print('pdfview',pdfurl)
                    bufferSize = 64 * 1024
                    passw = "#EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e"
                    encFileSize = stat(aesurl).st_size
                    with open(aesurl, "rb") as fIn:
                        with open(pdfurl, "wb") as fOut:
                            pyAesCrypt.decryptStream(fIn, fOut, passw, bufferSize, encFileSize)
                    pdfpath = pdfurl[25:]
                    print(pdfpath,'pppppppppp')
                    curr_path=pdfpath
                    bomurl='http://127.0.0.1:8000/media'+curr_path
                    print(bomurl,'pppp11111pppppp')
            taf=TAapplicationfiles.objects.filter(user_id=fc.user_id,filecategory='Tech_Spec',refid=fc.idprefix).first()
            techspecurl=''
            if taf:
                aesurl=taf.filepath
                if taf.ext=='.pdf':
                    pdfurl = aesurl[:-4]
                    print('aesview',aesurl)
                    print('pdfview',pdfurl)
                    bufferSize = 64 * 1024
                    passw = "#EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e"
                    encFileSize = stat(aesurl).st_size
                    with open(aesurl, "rb") as fIn:
                        with open(pdfurl, "wb") as fOut:
                            pyAesCrypt.decryptStream(fIn, fOut, passw, bufferSize, encFileSize)
                    pdfpath = pdfurl[25:]
                    print(pdfpath,'pppppppppp')
                    curr_path=pdfpath
                    techspecurl='http://127.0.0.1:8000/media'+curr_path
                    print(techspecurl,'pppp11111pppppp')
                    
            context= {
                'firmname':taa.firmname,
                'addr1':taa.addr1,
                'addr2':taa.addr2,
                'item_name':taa.item_name,
                'part_no':taa.part_no,
                'desc':taa.desc,
                'dal_mdi':taa.dal_mdi,
                'bom':taa.bom,
                'sop_acbs':taa.sop_acbs,
                'pc': taa.pc,
                'tre':taa.tre,
                'otheritems':taa.otheritems,
                'dalurl':dalurl,
                'bomurl':bomurl,
                'techspecurl':techspecurl,

                
                'ta': pro.ta,
                'techspec': pro.techspec,
                'qts': pro.qts,
                'qtr': pro.qtr,
                'cd': pro.cd,
                'photo': pro.photo,
                'feedback': pro.feedback,
                'req': pro.req,
                'cost': pro.cost,
                'quantity': pro.quantity,
                'pc': pro.pc,
                'tacomments':pro.tacomments,
                'datenow':formatted_datetime
                
            }

            response = HttpResponse(content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename="report.pdf"'
            html = template.render(context)

            pisaStatus = pisa.CreatePDF(
            html,dest=response,link_callback=link_callback)
            if pisaStatus:
                return HttpResponse(response,content_type='application/pdf')
        # if error then show some funy view
            if pisaStatus.err:
                return HttpResponse('We had some errors <pre>' + html + '</pre>')
            return response
        else:
            print(form.errors)
            return render(request, 'dealing officer/proforma.html', {'form': form,'id':id,'idprefix':idprefix})
コード例 #30
0
def history_download(request, timeslot, download):
    ts = get_object_or_404(TimeSlot, pk=timeslot)
    if ts == get_timeslot() or ts.Begin > timezone.now().date():
        raise PermissionDenied(
            "Downloads of the current and future timeslots are not allowed. Please use the regular menu entries."
        )
    if download == 'distributions':
        projects = Proposal.objects.filter(TimeSlot=ts, Status=4).distinct()
        file = get_list_distributions_xlsx(projects)
        response = HttpResponse(content=file)
        response[
            'Content-Disposition'] = 'attachment; filename=marketplace-projects-distributions.xlsx'
        response[
            'Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

    elif download == 'presentations':
        sets = PresentationSet.objects.filter(PresentationOptions__TimeSlot=ts)
        if not sets:
            return render(
                request, "base.html", {
                    "Message":
                    "There is nothing planned yet. Please plan the presentations first."
                })
        file = get_list_presentations_xlsx(sets)
        response = HttpResponse(content=file)
        response[
            'Content-Disposition'] = 'attachment; filename=presentations-planning.xlsx'
        response[
            'Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

    elif download == 'nonfull':
        projects = Proposal.objects.annotate(
            num_distr=Count('distributions')).filter(
                TimeSlot=ts, Status=4,
                num_distr__lt=F('NumStudentsMax')).order_by('Title')
        file = get_list_projects_xlsx(projects)
        response = HttpResponse(content=file)
        response[
            'Content-Disposition'] = 'attachment; filename=non-full-proposals-{}.xlsx'.format(
                ts.Name)
        response[
            'Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

    elif download == 'projects':
        projects = Proposal.objects.filter(TimeSlot=ts,
                                           Status=4).order_by('Title')
        file = get_list_projects_xlsx(projects)
        response = HttpResponse(content=file)
        response[
            'Content-Disposition'] = 'attachment; filename=non-full-proposals-{}.xlsx'.format(
                ts.Name)
        response[
            'Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

    elif download == 'publicfiles':
        in_memory = BytesIO()
        with zipfile.ZipFile(in_memory, 'w') as archive:
            files = PublicFile.objects.filter(TimeSlot=ts)
            if not files:
                return render(
                    request, 'base.html',
                    {'Message': 'This time slot has no public files.'})
            for file in files:
                fname = file.OriginalName
                try:
                    with open(file.File.path, 'rb') as fstream:
                        archive.writestr(
                            '{}.{}'.format(fname,
                                           file.File.name.split('.')[-1]),
                            fstream.read())
                except (
                        IOError, ValueError
                ):  # happens if a file is referenced from database but does not exist on disk.
                    return render(
                        request, 'base.html', {
                            'Message':
                            'These files cannot be downloaded, please contact support staff. (Error on file: "{}")'
                            .format(file)
                        })
        in_memory.seek(0)
        response = HttpResponse(content_type="application/zip")
        response[
            'Content-Disposition'] = 'attachment; filename="publicfiles-{}.zip"'.format(
                ts.Name)
        response.write(in_memory.read())
    elif download == 'results':
        # first get all results as in memory pdf files.
        files = []
        for dstr in ts.distributions.all():
            html = get_template('results/print_grades_pdf.html').render({
                "dstr":
                dstr,
                "catresults":
                dstr.results.all(),
                "finalgrade":
                dstr.TotalGradeRounded(),
                'final':
                True,
            })
            buffer = BytesIO()
            pisa_status = pisa.CreatePDF(html.encode('utf-8'),
                                         dest=buffer,
                                         encoding='utf-8')
            if pisa_status.err:
                raise Exception(
                    "Pisa Failed PDF creation in print final grade for distribution {}."
                    .format(dstr))
            buffer.seek(0)
            files.append([dstr, buffer])
        if not files:
            return render(
                request, 'base.html',
                {'Message': 'There are no results available for download.'})
        # now export all pdfs to zip file
        in_memory = BytesIO()
        with zipfile.ZipFile(in_memory, 'w') as archive:
            for dstr, file in files:
                fname = "bepresult_{}.pdf".format(
                    dstr.Student.usermeta.get_nice_name())
                try:
                    archive.writestr(fname, file.getbuffer())
                except (
                        IOError, ValueError
                ):  # happens if a file is referenced from database but does not exist on disk.
                    return render(
                        request, 'base.html', {
                            'Message':
                            'These files cannot be downloaded, please contact support staff. (Error on file: "{}")'
                            .format(file)
                        })
        in_memory.seek(0)
        # and serve the zip.
        response = HttpResponse(content_type="application/zip")
        response[
            'Content-Disposition'] = 'attachment; filename="results-pdf-{}.zip"'.format(
                ts.Name)
        response.write(in_memory.read())
    else:
        raise PermissionDenied("Invalid options.")
    return response