Python reportlab.lib.pagesizes 模块,letter() 实例源码

我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用reportlab.lib.pagesizes.letter()

项目:king-phisher-plugins    作者:securestate    | 项目源码 | 文件源码
def process_attachment_file(self, input_path, output_path, target=None):
        output_path, _ = os.path.splitext(output_path)
        output_path += '.pdf'

        pdf_file = platypus.SimpleDocTemplate(
            output_path,
            pagesize=letter,
            rightMargin=72,
            leftMargin=72,
            topMargin=72,
            bottomMargin=18
        )

        url = self.application.config['mailer.webserver_url']
        if target is not None:
            url += '?uid=' + target.uid

        try:
            pdf_template = self.get_template(input_path, url)
            pdf_file.multiBuild(pdf_template)
        except Exception as err:
            self.logger.error('failed to build the pdf document', exc_info=True)
            return
        self.logger.info('wrote pdf file to: ' + output_path + ('' if target is None else ' with uid: ' + target.uid))
        return output_path
项目:Marisol    作者:wikkiewikkie    | 项目源码 | 文件源码
def __init__(self, pages, size=pagesizes.letter):
        """
        Init

        Args:
            pages (int): Number of pages to mock.
        """
        self.pages = pages
        self.size = size

        self.file = io.BytesIO()

        canvas = Canvas(self.file, pagesize=self.size)

        for page_num in range(pages):
            canvas.drawString(30, self.size[1]-30, "MockPDF Created By Marisol")
            canvas.drawString(30, self.size[1]-60, "Page {} of {}".format(page_num+1, pages))
            canvas.drawString(30, self.size[1]-90, "Dimensions: {}".format(size))
            canvas.showPage()

        canvas.save()
项目:callisto-core    作者:project-callisto    | 项目源码 | 文件源码
def generate_pdf_report(self, report_id, recipient):
        # PREPARE PDF
        report_buffer = BytesIO()
        doc = SimpleDocTemplate(
            report_buffer,
            pagesize=letter,
            rightMargin=72, leftMargin=72,
            topMargin=72, bottomMargin=72,
        )

        # COVER PAGE
        self.pdf_elements.extend(
            api.NotificationApi.get_cover_page(
                report_id=report_id,
                recipient=recipient,
            ),
        )

        # METADATA PAGE
        self.pdf_elements.extend(self.get_metadata_page(recipient))

        # REPORT
        self.pdf_elements.extend(
            [Paragraph("Report Questions", self.section_title_style)],
        )
        for item in self.report_data:
            question, answers = item.popitem()
            self.render_question(question, answers)

        doc.build(
            self.pdf_elements,
            onFirstPage=self.get_header_footer(recipient),
            onLaterPages=self.get_header_footer(recipient),
            canvasmaker=NumberedCanvas,
        )
        result = report_buffer.getvalue()
        report_buffer.close()
        return result
项目:intake    作者:codeforamerica    | 项目源码 | 文件源码
def __init__(self, display_form, letter_display=None, canvas=None):
        self.file = io.BytesIO()
        self.width, self.height = letter
        self.canvas = canvas
        if not canvas:
            self.canvas = Canvas(
                self.file,
                pagesize=letter)
            self.canvas.setAuthor('Clear My Record, Code for America')
        self.frame = Margin(
            u('1in'),
            u('.75in'),
            u('1in'),
            u('.75in'))
        self.form = display_form
        self.letter = letter_display
        self.cursor = Position(
            self.frame.left,
            self.height - self.frame.top
        )
        self.nice_date = \
            self.form.date_received.get_current_value().strftime("%B %-d, %Y")
项目:intake    作者:codeforamerica    | 项目源码 | 文件源码
def draw_letter(self):
        max_width = u('6.5in')
        max_height = self.height - (
            self.frame.top + self.frame.bottom)
        self.set_cursor(u('1in'), self.height - self.frame.top)
        dx, dy = self.draw_paragraph(
            self.nice_date, max_width, max_height, BODY_STYLE)
        self.move_cursor(0, -(dy + self.field_bottom_margin))
        dx, dy = self.draw_paragraph(
            "To Whom It May Concern,", max_width, max_height, BODY_STYLE)
        self.move_cursor(0, -(dy + self.field_bottom_margin))
        for field in self.keys_to_fields(self.letter_display_fields, 'letter'):
            dx, dy = self.draw_paragraph(
                field.get_display_value(), max_width, max_height, BODY_STYLE)
            self.move_cursor(0, -(dy + self.field_bottom_margin))
        dx, dy = self.draw_paragraph(
            "Sincerely,", max_width, max_height, BODY_STYLE)
        self.move_cursor(0, -(dy + self.field_bottom_margin))
        full_name = " ".join([
            self.form.first_name.get_display_value(),
            self.form.last_name.get_display_value()
        ])
        dx, dy = self.draw_paragraph(
            full_name, max_width, max_height, BODY_STYLE)
项目:infonex_crm    作者:asterix135    | 项目源码 | 文件源码
def get_reg_note(request):
    reg_details = get_object_or_404(RegDetails, pk=request.GET.get('reg', ''))
    try:
        invoice = Invoice.objects.get(reg_details=reg_details)
    except Invoice.DoesNotExist:
        invoice = None
    inv_num = str(invoice.pk) if invoice else 'free'
    file_details = 'inline; filename="reg_note_' + inv_num + '"'
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = file_details
    buffr = BytesIO()
    note_pdf = canvas.Canvas(buffr, pagesize=letter)
    generate_reg_note(note_pdf, reg_details, invoice)
    note_pdf.showPage()
    note_pdf.save()
    pdf = buffr.getvalue()
    buffr.close()
    response.write(pdf)
    return response
项目:callisto-core    作者:project-callisto    | 项目源码 | 文件源码
def draw_page_number(self, page_count):
        width, height = letter
        margin = 0.66 * 72
        self.setFillColor('gray')
        self.drawRightString(
            width - margin, margin, "Page %d of %d" %
            (self._pageNumber, page_count))
项目:callisto-core    作者:project-callisto    | 项目源码 | 文件源码
def get_header_footer(self, recipient):
        def func(canvas, doc):
            width, height = letter
            margin = 0.66 * 72
            canvas.saveState()
            canvas.setFillColor('gray')
            canvas.drawString(margin, height - margin, "CONFIDENTIAL")
            canvas.drawRightString(
                width - margin, height - margin, str(timezone.now()))
            canvas.drawString(
                margin, margin,
                f"Intended for: Title IX Coordinator {recipient}",
            )
            canvas.restoreState()
        return func
项目:intake    作者:codeforamerica    | 项目源码 | 文件源码
def render(self, save=True, title=None):
        self.draw_header()
        self.draw_main_fields()
        self.draw_case_status_fields()
        self.canvas.showPage()
        if self.letter:
            self.draw_letter()
            self.canvas.showPage()
        if title:
            self.canvas.setTitle(title)
        if save:
            self.canvas.save()
        return self.canvas, self.file
项目:chxanalys    作者:yugangzhang    | 项目源码 | 文件源码
def __init__( self, data_dir, uid,  out_dir=None, filename=None, load=True, user=None,
                 report_type='saxs',md=None ):
        self.data_dir = data_dir
        self.uid = uid
        self.md = md        
        #print(md)
        if user is None:
            user = 'chx'
        self.user = user
        if out_dir is None:
            out_dir = data_dir 
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        self.out_dir=out_dir

        self.styles = getSampleStyleSheet()
        self.width, self.height = letter

        self.report_type = report_type        
        dt =datetime.now()
        CurTime = '%02d/%02d/%s/-%02d/%02d/' % ( dt.month, dt.day, dt.year,dt.hour,dt.minute)
        self.CurTime = CurTime
        if filename is None:
            filename="XPCS_Analysis_Report_for_uid=%s.pdf"%uid
        filename=out_dir + filename
        c = canvas.Canvas( filename, pagesize=letter)
        self.filename= filename
        #c.setTitle("XPCS Analysis Report for uid=%s"%uid)
        c.setTitle(filename)
        self.c = c
        if load:
            self.load_metadata()
项目:gamereporter    作者:gamesbook    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        __version_info__ = ('1', '0', '0')
        self.__version__ = __version_info__
        self.games = kwargs.get('games', [])  # list of 'game' objects
        self.user = kwargs.get('user', '')
        self.time = kwargs.get('time', 'UK')
        self.filename = kwargs.get('filename')
        self.progress = kwargs.get('progress', False)
        self.family_names = kwargs.get('familys', [])
        self.font_names = kwargs.get('fonts', [])
        self.page_footer = kwargs.get(
            'page_footer', '')
        self.page_header = kwargs.get(
            'page_header', 'Board Game Geek Collection Printer (v0.1)')
        header = kwargs.get('header')
        body = kwargs.get('left')
        margin = kwargs.get('margin', 72)
        page_size = kwargs.get('page', 'A4')
        if page_size == 'A4':
            size = A4
        elif page_size == 'letter':
            size = Letter
        else:
            raise NotImplementedError('Page size "%" is not available' % page_size)
        self.set_doc(filename=self.filename, margin=margin, page=size)
        # fonts & styles
        for fname in self.family_names:
            self.ttf_register(fname, family=True)
        for fname in self.font_names:
            self.ttf_register(fname, family=False)
        self.styles = getSampleStyleSheet()
        self.set_styles(body, header)  # style sheets pre-made
项目:tambox    作者:joseamaya    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs): 
        response = HttpResponse(content_type='application/pdf')
        pdf_name = "clientes.pdf"  # llamado clientes
        # la linea 26 es por si deseas descargar el pdf a tu computadora
        # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
        buff = BytesIO()
        doc = SimpleDocTemplate(buff,
                                pagesize=letter,
                                rightMargin=40,
                                leftMargin=40,
                                topMargin=60,
                                bottomMargin=18,
                                )
        clientes = []
        styles = getSampleStyleSheet()
        header = Paragraph("Listado de Clientes", styles['Heading1'])
        clientes.append(header)
        headings = ('Nombre', 'Email', 'Edad', 'Direccion')
        allclientes = [(p.codigo, p.descripcion, p.precio_mercado, p.grupo_suministros) for p in Producto.objects.all()]

        t = Table([headings] + allclientes)
        t.setStyle(TableStyle(
            [
                ('GRID', (0, 0), (3, -1), 1, colors.dodgerblue),
                ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
                ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
            ]
        ))
        clientes.append(t)
        doc.build(clientes)
        response.write(buff.getvalue())
        buff.close()
        return response
项目:infonex_crm    作者:asterix135    | 项目源码 | 文件源码
def generate_report(self):
        report_name = 'Conference Registration Form'
        buffr = BytesIO()
        styles = getSampleStyleSheet()
        report = canvas.Canvas(buffr, pagesize=letter)
        self._draw_stuff(report)
        report.showPage()
        report.save()
        pdf = buffr.getvalue()
        buffr.close()
        return pdf
项目:infonex_crm    作者:asterix135    | 项目源码 | 文件源码
def get_invoice(request):
    reg_details = get_object_or_404(RegDetails, pk=request.GET.get('reg', ''))
    invoice = get_object_or_404(Invoice, reg_details=reg_details)
    file_details = 'inline; filename="invoice_' + str(invoice.pk) + '"'
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = file_details
    buffr = BytesIO()
    invoice_pdf = canvas.Canvas(buffr, pagesize=letter)
    generate_invoice(invoice_pdf, reg_details, invoice)
    invoice_pdf.showPage()
    invoice_pdf.save()
    pdf = buffr.getvalue()
    buffr.close()
    response.write(pdf)
    return response
项目:infonex_crm    作者:asterix135    | 项目源码 | 文件源码
def send_conf_email(request):
    if request.method != 'POST':
        return HttpResponse('')
    reg_details = get_object_or_404(RegDetails,
                                    pk=request.POST['reg_id'])
    try:
        invoice = Invoice.objects.get(reg_details=reg_details)
    except Invoice.DoesNotExist:
        invoice = None
    if invoice:
        buffr = BytesIO()
        invoice_pdf = canvas.Canvas(buffr, pagesize=letter)
        generate_invoice(invoice_pdf, reg_details, invoice)
        invoice_pdf.showPage()
        invoice_pdf.save()
        pdf = buffr.getvalue()
        buffr.close()
    else:
        pdf = None

    email_body = request.POST['email_message']
    email_body = email_body.replace('\n', '<br/>')
    email_subject = request.POST['email_subject']
    to_list = list(set(request.POST.getlist('to_list[]')))
    cc_list = list(set(request.POST.getlist('cc_list[]')))
    bcc_list = list(set(request.POST.getlist('bcc_list[]')))
    email = EmailMessage(
        subject=email_subject,
        body=email_body,
        to=to_list,
        cc=cc_list,
        bcc=bcc_list,
    )
    if pdf:
        filename = 'invoice-' + str(invoice.pk) + '.pdf'
        email.attach(filename, pdf, 'application/pdf')
    email.content_subtype = 'html'
    email.send()
    return HttpResponse(status=204)
项目:infonex_crm    作者:asterix135    | 项目源码 | 文件源码
def format_sales_report_header_row(ws, row_num=1):
    """
    Sets first 26 columns of specified row in worksheet to bold
    """
    for letter in ascii_uppercase:
        cell = ws[letter + str(row_num)]
        cell.font = Font(bold=True)
项目:geo-hpc    作者:itpir    | 项目源码 | 文件源码
def build_doc(self):

        rid = self.request_id
        print 'build_doc: ' + rid

        # try:

        self.doc = SimpleDocTemplate(self.output, pagesize=letter)

        # build doc call all functions

        self.add_header()
        self.Story.append(Spacer(1, 0.5*inch))
        self.add_info()
        self.Story.append(Spacer(1, 0.3*inch))
        self.add_timeline()
        self.Story.append(Spacer(1, 0.3*inch))
        self.add_cite_and_contents()
        self.Story.append(PageBreak())

        self.add_meta()
        self.Story.append(PageBreak())

        self.add_notes()
        self.Story.append(PageBreak())

        self.add_additional()

        self.output_doc()

        return True
        # except:
        #     return False


    # documentation header
项目:infonex_crm    作者:asterix135    | 项目源码 | 文件源码
def call_report(request):
    event_assignment = get_object_or_404(EventAssignment,
                                         pk=request.session['assignment_id'])
    event = event_assignment.event
    user = request.user
    contact_history = Contact.objects.filter(
        event=event, author=user
    ).order_by('-date_of_contact')
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="call_report.pdf"'
    buffr = BytesIO()

    styles = getSampleStyleSheet()
    cell_style = styles['BodyText']
    cell_style.alignment = TA_LEFT

    report_details = []
    title = Paragraph('Call Note Report', styles['title'])
    report_details.append(title)
    conf_details_text = event.number + ': ' + event.title + ' (' \
        + user.username+ ')'
    report_details.append(Paragraph(conf_details_text, styles['h2']))
    report = SimpleDocTemplate(buffr, pagesize=letter,
                               leftMargin=inch/2, rightMargin = inch/2)
    data = []
    for contact in contact_history:
        person = contact.person.name
        if contact.person.title:
            person = person + '<br/>' + contact.person.title
        if contact.person.company:
            person = person + '<br/>' + contact.person.company
        date = Paragraph(str(contact.date_of_contact.date()), cell_style)
        person = Paragraph(person, cell_style)
        notes = Paragraph(contact.notes[:3500], cell_style)
        data.append([date, person, notes])
        table = Table(data, [inch, 3 * inch, 4.5 * inch])
        table.setStyle(TableStyle([('VALIGN', (0,0), (-1, -1), 'TOP')]))
        report_details.append(table)
        data = []
    # if len(data) > 0:
    #     call_detail_table = Table(data, [inch, 2 * inch, 4.5 * inch])
    #     call_detail_table.setStyle(TableStyle([('VALIGN', (0,0),
    #                                             (-1, -1), 'TOP')]))
    #     report_details.append(call_detail_table)


    report.build(report_details)

    pdf = buffr.getvalue()
    buffr.close()
    response.write(pdf)
    return response
项目:2016.2-SME_UnB    作者:fga-gpp-mds    | 项目源码 | 文件源码
def generatePdf(transductor_id):
    import time
    from reportlab.lib.enums import TA_JUSTIFY
    from reportlab.lib.pagesizes import letter
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.lib.units import inch

    doc = SimpleDocTemplate("src/report/static/Relatorio"+transductor_id+".pdf",
                            pagesize=letter,
                            rightMargin=72, leftMargin=72,
                            topMargin=72, bottomMargin=18)
    Story = []
    logo = "src/report/static/currentGraphic"+transductor_id+".png"
    logo2 = "src/report/static/voltageGraphic"+transductor_id+".png"
    logo3 = "src/report/static/activePowerGraphic"+transductor_id+".png"
    logo4 = "src/report/static/reactivePowerGraphic"+transductor_id+".png"
    logo5 = "src/report/static/apparentPowerGraphic"+transductor_id+".png"

    magName = "Pythonista"
    issueNum = 12
    subPrice = "99.00"
    limitedDate = "03/05/2010"
    freeGift = "tin foil hat"

    formatted_time = time.ctime()
    full_name = "SME-UnB"
    address_parts = ["Campus Universitario UnB", "Brasilia-DF, 70910-900"]

    im = Image(logo, 8 * inch, 5 * inch)
    im2 = Image(logo2, 8 * inch, 5 * inch)
    im3 = Image(logo3, 8 * inch, 5 * inch)
    im4 = Image(logo4, 8 * inch, 5 * inch)
    im5 = Image(logo5, 8 * inch, 5 * inch)

    Story.append(im)
    Story.append(im2)
    Story.append(im3)
    Story.append(im4)
    Story.append(im5)

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    ptext = '<font size=12>%s</font>' % formatted_time

    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))

    ptext = '<font size=12>%s</font>' % full_name
    Story.append(Paragraph(ptext, styles["Normal"]))
    for part in address_parts:
        ptext = '<font size=12>%s</font>' % part.strip()
        Story.append(Paragraph(ptext, styles["Normal"]))

    Story.append(Spacer(1, 12))
    Story.append(Spacer(1, 12))
    ptext = '<font size=12>{ % trans Report Energy Monitoring % }</font>'
    Story.append(Paragraph(ptext, styles["Normal"]))

    doc.build(Story)
    return 1