示例#1
1
def relatorio_documento_base(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="srfa02.pdf"'

    doc = SimpleDocTemplate(response, rightMargin=72,leftMargin=72, topMargin=72,bottomMargin=18)
    
    Story=[]
    magName = "Pythonista"
    issueNum = 12
    subPrice = "99.00"
    limitedDate = "03/05/2010"
    freeGift = "tin foil hat"
     
    formatted_time = time.ctime()
    full_name = "Mike Driscoll"
    address_parts = ["411 State St.", "Marshalltown, IA 50158"]
     
     
    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))
     
    # Create return address
    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))
    ptext = '<font size=12>Dear %s:</font>' % full_name.split()[0].strip()
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))
     
    ptext = '<font size=12>We would like to welcome you to our subscriber base for %s Magazine! \
            You will receive %s issues at the excellent introductory price of $%s. Please respond by\
            %s to start receiving your subscription and get the following free gift: %s.</font>' % (magName, 
                                                                                                    issueNum,
                                                                                                    subPrice,
                                                                                                    limitedDate,
                                                                                                    freeGift)
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))
     
     
    ptext = '<font size=12>Thank you very much and we look forward to serving you.</font>'
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))
    ptext = '<font size=12>Sincerely,</font>'
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 48))
    ptext = '<font size=12>Ima Sucker</font>'
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))
    doc.build(Story)
    
    return response
 def func(val):
     story = [
             DocAssert(val,'this should fail'),
             DocPara('repr(doc._nameSpace)',escape=True),
             ]
     doc = SimpleDocTemplate(outputfile('test_doc_programming_asserts.pdf'))
     doc.build(story)
示例#3
0
def email_admin(self, subject, text, sorted_self):

    site_name = SiteSetting.objects.all().first().site_name

    styleSheet = getSampleStyleSheet()

    # Send the admin a PDF of client details
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="clientDetails.pdf"'

    string_buffer = StringIO()

    new_pdf = []
    header = Paragraph(site_name + " Attendee Details", styleSheet['Heading1'])
    new_pdf.append(header)

    for element in sorted_self:
        new_pdf.append(Paragraph(element[0], styleSheet['Heading3']))
        new_pdf.append(Paragraph(element[1], styleSheet['BodyText']))
        new_pdf.append(Spacer(1, 2))

    doc = SimpleDocTemplate(string_buffer)
    doc.build(new_pdf)
    pdf = string_buffer.getvalue()
    string_buffer.close()

    msg = EmailMultiAlternatives(subject, text, EMAIL_HOST_USER, [EMAIL_HOST_USER])
    msg.attach(self.first_name + self.last_name + site_name + ".pdf", pdf, "application/pdf")
    msg.send(fail_silently=True)
示例#4
0
def print_rep(uid):
    registerFont(TTFont('DroidSans', 'DroidSans.ttf'))

    pdf = StringIO()

    doc = SimpleDocTemplate(pdf, pagesize=A4)
    elements = []
    style = getSampleStyleSheet()
    style.add(ParagraphStyle(name='Header', alignment=TA_LEFT,
                             fontName='DroidSans',
                             fontSize=14, leading=16))
    style.add(ParagraphStyle(name='Left', alignment=TA_LEFT,
                             fontName='DroidSans',
                             fontSize=12))
    style.add(ParagraphStyle(name='Right', alignment=TA_RIGHT,
                             fontName='DroidSans',
                             fontSize=12))
    if uid == 0:
        elements.append(Paragraph(u'<u>Users List</u>', style['Header']))
        u = User.query.all()     
        for i, o in enumerate(u):
            elements.append(Paragraph(u'%s. %s %s %s' % (i+1, o.name, o.email, o.progress), style['Left']))
    else:
        u = User.query.get(uid)
        elements.append(Paragraph(u'%s %s %s' % (u.name, u.email, u.progress), style['Header']))

    doc.build(elements)
    pdf_file = pdf.getvalue()
    pdf.close()
    response = make_response(pdf_file)

    response.headers['Content-Disposition'] = "attachment; filename='pdf_user.pdf"
    response.mimetype = 'application/pdf'
    return response
示例#5
0
    def prepareDoc(self):
        rightMargin, leftMargin, topMargin, bottomMargin = 72, 72, 72, 18

        doc = SimpleDocTemplate(None, pagesize=A4,
            rightMargin=rightMargin, leftMargin=leftMargin,
            topMargin=topMargin, bottomMargin=bottomMargin)

        frameWidth = doc.width / 2
        headerHeight = 50
        userInfoHeight = 228
        itemsFrameHeight = doc.height - userInfoHeight - headerHeight

        header = Frame(leftMargin, doc.height, doc.width, headerHeight)
        column1 = Frame(leftMargin, doc.height - userInfoHeight,
                        frameWidth, userInfoHeight)
        column2 = Frame(leftMargin + frameWidth, doc.height - userInfoHeight,
                        frameWidth, userInfoHeight)
        items = Frame(leftMargin,
                      doc.height - userInfoHeight - itemsFrameHeight,
                      doc.width, itemsFrameHeight)

        template = PageTemplate(frames=[header, column1, column2, items])
        doc.addPageTemplates(template)

        half = doc.width / 2
        self.columnWidths = (half / 2, half / 2)

        self.itemColumnWidths = (
            (float(2) / 3) * doc.width,
            (float(1) / 3) * doc.width * (float(1) / 3),
            (float(1) / 3) * doc.width * (float(2) / 3)
        )

        return doc
示例#6
0
文件: __init__.py 项目: vezzi/NouGAT
 def render(self, pdfTitle):
     doc_template_args = self.theme.doc_template_args()
     doc = SimpleDocTemplate("{}".format(pdfTitle),
                             title=self.title,
                             author=self.author,
                             **doc_template_args)
     doc.build(self.story, canvasmaker=NumberedCanvas)
def pdf_private_invoice(modeladmin, request, queryset):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    # Append invoice number and invoice date
    if len(queryset) != 1:
        _file_name = '-'.join([a.invoice_number for a in queryset.order_by("invoice_number")])
        response['Content-Disposition'] = 'attachment; filename="invoice%s.pdf"' %(_file_name.replace(" ", "")[:150])
    else:
        response['Content-Disposition'] = 'attachment; filename="invoice-%s-%s-%s-part-personnelle.pdf"' %(queryset[0].patient.name, 
                                                                                          queryset[0].invoice_number, 
                                                                                          queryset[0].invoice_date.strftime('%d-%m-%Y'))
    
    elements = []
    doc = SimpleDocTemplate(response, rightMargin=2*cm, leftMargin=2 * cm, topMargin=1 * cm, bottomMargin=1*cm)
    
    recapitulatif_data = []

    for qs in queryset.order_by("invoice_number"):
        dd = [qs.prestations.all().order_by("date", "carecode__gross_amount")[i:i+20] for i in range(0, len(qs.prestations.all()), 20)]
        for _prestations in dd:
            _inv = qs.invoice_number + (("" + str(dd.index(_prestations) + 1) + qs.invoice_date.strftime('%m%Y')) if len(dd) > 1 else "")
            _result = _build_invoices(_prestations, 
                                      _inv, 
                                      qs.invoice_date,
                                      qs.medical_prescription_date, 
                                      qs.accident_id, 
                                      qs.accident_date )
                                      
            elements.extend(_result["elements"])
            recapitulatif_data.append((_result["invoice_number"], _result["patient_name"], _result["invoice_amount"]))
            elements.append(PageBreak())
    #elements.extend(_build_recap(recapitulatif_data))
    doc.build(elements)
    return response
示例#8
0
    def render(self, response, title, author):
        doc_template_args = self.theme.doc_template_args()
        doc = SimpleDocTemplate(response, title=title, author=author,
            **doc_template_args)
        doc.build(self.story)

        return response
示例#9
0
文件: doclet.py 项目: AndyKovv/hostel
def testRml():
    from reportlab.platypus.doctemplate import SimpleDocTemplate
    from reportlab.platypus.flowables import Spacer
    from reportlab.lib.randomtext import randomText

    templ = SimpleDocTemplate('doclet_output.pdf')

    #need a style
    story = []
    normal = ParagraphStyle('normal')
    normal.firstLineIndent = 18
    normal.spaceBefore = 6

    para = Paragraph("Test of doclets.  You should see a little table with a reversed word.", normal)
    story.append(para)

    story.append(Spacer(36,36))
                 
    theDoclet = TestReverseDoclet()
    story.append(theDoclet.asFlowable())
    
    for i in range(5):
        para = Paragraph(randomText(), normal)
        story.append(para)



    templ.build(story)    

    print('saved doclet_output.pdf')
示例#10
0
def email_admin(self, subject, text, sorted_self):

    ssheet = getSampleStyleSheet()

    # Send the admin a PDF of client details
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="clientDetails.pdf"'

    string_buffer = StringIO()

    new_pdf = []
    header = Paragraph("BIOMAAP Attendee Details", ssheet['Heading1'])
    new_pdf.append(header)

    for element in sorted_self:
        new_pdf.append(Paragraph(element[0], ssheet['Heading3']))
        new_pdf.append(Paragraph(element[1], ssheet['BodyText']))
        new_pdf.append(Spacer(1, 2))

    doc = SimpleDocTemplate(string_buffer)
    doc.build(new_pdf)
    pdf = string_buffer.getvalue()
    string_buffer.close()

    msg = EmailMultiAlternatives(subject, text, "*****@*****.**", ["*****@*****.**"])
    msg.attach(self.first_name + self.last_name + "BIOMAAP.pdf", pdf, "application/pdf")
    msg.send(fail_silently=True)
示例#11
0
def export_to_pdf(modeladmin, request, queryset):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    # Append invoice number and invoice date
    if len(queryset) != 1:
        _file_name = '-'.join([a.invoice_number for a in queryset.order_by("invoice_number")])
        response['Content-Disposition'] = 'attachment; filename="invoice%s.pdf"' %(_file_name.replace(" ", "")[:150])
    else:
        response['Content-Disposition'] = 'attachment; filename="invoice-%s-%s-%s.pdf"' %(queryset[0].patient.name, 
                                                                                          queryset[0].invoice_number, 
                                                                                          queryset[0].invoice_date.strftime('%d-%m-%Y'))
    
    elements = []
    doc = SimpleDocTemplate(response, rightMargin=2*cm, leftMargin=2 * cm, topMargin=1 * cm, bottomMargin=1*cm)
    
    recapitulatif_data = []

    for qs in queryset.order_by("invoice_number"):
        dd = [qs.prestations.all().order_by("date", "carecode__gross_amount")[i:i+20] for i in range(0, len(qs.prestations.all()), 20)]
        for _prestations in dd:
            _inv = qs.invoice_number + (("" + str(dd.index(_prestations) + 1) + qs.invoice_date.strftime('%m%Y')) if len(dd) > 1 else "")
            _result = _build_invoices(_prestations, 
                                      _inv, 
                                      qs.invoice_date, 
                                      qs.accident_id, 
                                      qs.accident_date )
                                      
            elements.extend(_result["elements"])
            recapitulatif_data.append((_result["invoice_number"], _result["patient_name"], _result["invoice_amount"]))
            elements.append(PageBreak())
    elements.extend(_build_recap(recapitulatif_data))
    doc.build(elements)
    return response
示例#12
0
    def renderToc(self, tocpath, toc_entries, rtl):
        doc = SimpleDocTemplate(tocpath, pagesize=(pdfstyles.page_width, pdfstyles.page_height))
        elements = []
        elements.append(
            Paragraph(_("Contents"), pdfstyles.heading_style(mode="chapter", text_align="left" if not rtl else "right"))
        )
        toc_table = []
        styles = []
        col_widths = self._getColWidths()
        for row_idx, (lvl, txt, page_num) in enumerate(toc_entries):
            if lvl == "article":
                page_num = str(page_num)
            elif lvl == "chapter":
                page_num = "<b>%d</b>" % page_num
                styles.append(("TOPPADDING", (0, row_idx), (-1, row_idx), 10))
            elif lvl == "group":
                page_num = " "
                styles.append(("TOPPADDING", (0, row_idx), (-1, row_idx), 10))

            toc_table.append(
                [
                    Paragraph(txt, pdfstyles.text_style(mode="toc_%s" % str(lvl), text_align="left")),
                    Paragraph(page_num, pdfstyles.text_style(mode="toc_article", text_align="right")),
                ]
            )
        t = Table(toc_table, colWidths=col_widths)
        t.setStyle(styles)
        elements.append(t)
        doc.build(elements)
示例#13
0
文件: toc.py 项目: ingob/mwlib.rl
    def renderToc(self, tocpath, toc_entries):
        doc = SimpleDocTemplate(tocpath, pagesize=(pdfstyles.page_width, pdfstyles.page_height))
        elements = []
        elements.append(Paragraph(_('Contents'), pdfstyles.heading_style(mode='chapter', text_align='left')))
        toc_table =[]
        styles = []
        col_widths = self._getColWidths()
        for row_idx, (lvl, txt, page_num) in enumerate(toc_entries):
            if lvl == 'article':
                page_num = str(page_num)
            elif lvl == 'chapter':
                page_num = '<b>%d</b>' % page_num
                styles.append(('TOPPADDING', (0, row_idx), (-1, row_idx), 10))
            elif lvl == 'group':
                page_num = ' '
                styles.append(('TOPPADDING', (0, row_idx), (-1, row_idx), 10))

            toc_table.append([
                Paragraph(txt, pdfstyles.text_style(mode='toc_%s' % str(lvl), text_align='left')),
                Paragraph(page_num, pdfstyles.text_style(mode='toc_article', text_align='right'))
                ])
        t = Table(toc_table, colWidths=col_widths)
        t.setStyle(styles)
        elements.append(t)
        doc.build(elements)
示例#14
0
def email_admin(self, subject, text, sorted_self):

    styleSheet = getSampleStyleSheet()

    # Send the admin a PDF of client details
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="clientDetails.pdf"'

    string_buffer = StringIO()

    new_pdf = []
    header = Paragraph("DISS Attendee Details", styleSheet['Heading1'])
    new_pdf.append(header)

    for element in sorted_self:
        new_pdf.append(Paragraph(element[0], styleSheet['Heading3']))
        new_pdf.append(Paragraph(element[1], styleSheet['BodyText']))
        new_pdf.append(Spacer(1, 2))

    doc = SimpleDocTemplate(string_buffer)
    doc.build(new_pdf)
    pdf = string_buffer.getvalue()
    string_buffer.close()

    msg = EmailMultiAlternatives(subject, text, "*****@*****.**", ["*****@*****.**"])
    msg.attach(self.first_name + self.last_name + "DISS.pdf", pdf, "application/pdf")
    msg.send()
示例#15
0
def print_rep(uid):
    registerFont(TTFont("DroidSans", "DroidSans.ttf"))

    pdf = StringIO()

    doc = SimpleDocTemplate(pdf, pagesize=A4)
    elements = []
    style = getSampleStyleSheet()
    style.add(ParagraphStyle(name="Left", alignment=TA_LEFT, fontName="DroidSans", fontSize=12))
    style.add(ParagraphStyle(name="Right", alignment=TA_RIGHT, fontName="DroidSans", fontSize=12))
    if uid == 0:
        u = User.query.all()
        for o in u:
            elements.append(Paragraph(u"%s %s %s" % (o.name, o.email, o.progress), style["Left"]))
    else:
        u = User.query.get(uid)
        elements.append(Paragraph(u"%s %s %s" % (u.name, u.email, u.progress), style["Left"]))

    doc.build(elements)
    pdf_file = pdf.getvalue()
    pdf.close()
    response = make_response(pdf_file)

    response.headers["Content-Disposition"] = "attachment; filename='pdf_user.pdf"
    response.mimetype = "application/pdf"
    return response
 def test1(self):
     """Ilpo Nyyss\xf6nen posted this broken test"""
     normalStyle = ParagraphStyle(name="normal")
     keepStyle = ParagraphStyle(name="keep", keepWithNext=True)
     content = [Paragraph("line 1", keepStyle), Indenter(left=1 * cm), Paragraph("line 2", normalStyle)]
     doc = SimpleDocTemplate(outputfile("test_platypus_breaking1.pdf"))
     doc.build(content)
示例#17
0
def testRml():
    from reportlab.platypus.doctemplate import SimpleDocTemplate
    from reportlab.platypus.flowables import Spacer
    from reportlab.lib.randomtext import randomText

    templ = SimpleDocTemplate('doclet_output.pdf')

    #need a style
    story = []
    normal = ParagraphStyle('normal')
    normal.firstLineIndent = 18
    normal.spaceBefore = 6

    para = Paragraph(
        "Test of doclets.  You should see a little table with a reversed word.",
        normal)
    story.append(para)

    story.append(Spacer(36, 36))

    theDoclet = TestReverseDoclet()
    story.append(theDoclet.asFlowable())

    for i in range(5):
        para = Paragraph(randomText(), normal)
        story.append(para)

    templ.build(story)

    print('saved doclet_output.pdf')
示例#18
0
 def make_output( me, filename, pagesize=None, layout =None, view_descr =None):
     from reportlab.platypus.doctemplate import SimpleDocTemplate
     story = me.make_embeddable_output( layout, view_descr)
     doc_args = me.get_doc_args( pagesize)
     doc = SimpleDocTemplate( filename, **doc_args)
     doc.build( story)
     return doc # always True
示例#19
0
 def render_to_response(self, flowables, outfile):
     """Renders a list of flowables as a PDF to the specified `outfile`."""
     doc = SimpleDocTemplate(outfile)
     doc.build(flowables,
               onFirstPage=add_page_number,
               onLaterPages=add_page_number)
     return outfile
示例#20
0
def relatorio_documento_base(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="srfa02.pdf"'

    doc = SimpleDocTemplate(response,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)

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

    formatted_time = time.ctime()
    full_name = "Mike Driscoll"
    address_parts = ["411 State St.", "Marshalltown, IA 50158"]

    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))

    # Create return address
    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))
    ptext = '<font size=12>Dear %s:</font>' % full_name.split()[0].strip()
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))

    ptext = '<font size=12>We would like to welcome you to our subscriber base for %s Magazine! \
            You will receive %s issues at the excellent introductory price of $%s. Please respond by\
            %s to start receiving your subscription and get the following free gift: %s.</font>' % (
        magName, issueNum, subPrice, limitedDate, freeGift)
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))

    ptext = '<font size=12>Thank you very much and we look forward to serving you.</font>'
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))
    ptext = '<font size=12>Sincerely,</font>'
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 48))
    ptext = '<font size=12>Ima Sucker</font>'
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))
    doc.build(Story)

    return response
示例#21
0
def Naryad_Zakaz_PrintForm(ul,dom,date,date_str):
	day_task = GetListTaskDom(ul,dom,date)

	data = [['№пп','Наименование\nработ','Подъезд','Квартира','Примечание'],
		]
	
	n = 1
	

	elements = []

	### --- Имя файла для вывода ---
	FILE_NAME = os.getcwd()+'/tmp/'+str(time.time())+'.pdf'

	Font = ttfonts.TTFont('Arial','font/arial.ttf')
	Font2 = ttfonts.TTFont('ArialBD','font/arialbd.ttf')

	pdfmetrics.registerFont(Font)
	pdfmetrics.registerFont(Font2)

	style = getSampleStyleSheet()
	style.add(ParagraphStyle(name='Disp',wordWrap=True,fontName='ArialBD',fontSize=12,spaceAfter=5*mm,spaceBefore=5*mm,alignment=2))
	style.add(ParagraphStyle(name='Naryad_Zakaz',wordWrap=True,fontName='ArialBD',fontSize=14,spaceAfter=5*mm,spaceBefore=5*mm,alignment=1))
	style.add(ParagraphStyle(name='DateDom',wordWrap=True,fontName='ArialBD',fontSize=12,spaceAfter=5*mm,spaceBefore=5*mm,alignment=1))
	style.add(ParagraphStyle(name='Table',wordWrap=True,fontName='Arial',fontSize=11,spaceAfter=1*mm,spaceBefore=1*mm,alignment=0))

	doc = SimpleDocTemplate(FILE_NAME,topMargin=10*mm,bottomMargin=10*mm,leftMargin=10*mm,rightMargin=10*mm)



	for item in day_task:
	    row = [n,Paragraph(item[9],style["Table"]),item[13],item[12],'']
	    n = n + 1
	    data.append(row)




	t=Table(data)
	t.setStyle([('FONTNAME',(0,0),(-1,0),'ArialBD'),
		    ('FONTSIZE',(0,0),(-1,0),11),
		    ('ALIGN',(0,0),(-1,0),'CENTER'),
		    ('VALIGN',(0,0),(-1,0),'MIDDLE'),
		    ('GRID',(0,0),(-1,-1),0.25,colors.black),
		    ('FONTNAME',(0,1),(-1,-1),'Arial'),
		    ('FONTSIZE',(0,1),(-1,-1),11),
		    ('ALIGN',(0,1),(0,-1),'CENTER'),
		    ('ALIGN',(1,1),(-1,-1),'LEFT'),
		    ('VALIGN',(0,1),(-1,-1),'TOP'),
		    ])


	elements.append(Paragraph('Наряд-Заказ',style["Naryad_Zakaz"]))
	elements.append(Paragraph('на выполнение работ по адресу: '+ul+' дом '+dom+' на '+date_str,style["DateDom"]))
	elements.append(t)
	elements.append(Paragraph('Диспетчер ООО "Артэкс"',style["Disp"]))

	doc.build(elements)
	os.system(PDFVIEW+" "+FILE_NAME+" &")
示例#22
0
 def func(val):
     story = [
         DocAssert(val, 'this should fail'),
         DocPara('repr(doc._nameSpace)', escape=True),
     ]
     doc = SimpleDocTemplate(
         outputfile('test_doc_programming_asserts.pdf'))
     doc.build(story)
示例#23
0
 def render(self):
     buffer = io.BytesIO()
     doc_template_args = self.theme.doc_template_args()
     doc = SimpleDocTemplate(buffer, title=self.title, author=self.author,
                             **doc_template_args)
     doc.build(self.story)
     pdf = buffer.getvalue()
     buffer.close()
     return pdf
示例#24
0
def draw_table(context, pagesize):
    from reportlab.platypus.doctemplate import SimpleDocTemplate
    from reportlab.platypus import Table, TableStyle, Paragraph
    from reportlab.lib import colors
    from canvas import Canvas

    if OUT2PDF:
        from reportlab.pdfgen.canvas import Canvas

        context = "alabala.pdf"

    data = []
    for i in range(3):
        row = []
        for j in range(3):
            row.append(str(i) + str(j) + unicode("bp", "cp1251"))
        data.append(row)

    widths = [20, None, None]
    table = Table(data, colWidths=widths)

    if 1:
        style = TableStyle(())

        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.pdfbase import pdfmetrics
        from reportlab import rl_config

        rl_config.T1SearchPath.insert(0, "/usr/share/fonts/X11/Type1/")
        pdfmetrics.dumpFontData()

        # pdfmetrics.registerFont( TTFont('TIMES', 'Verdana.ttf'))

        fontname = "CharterBT-Roman"
        pdfmetrics.findFontAndRegister(fontname)

        style.add("FONTNAME", (0, 0), (-1, -1), fontname, 84)
        style.add("FONTSIZE", (0, 0), (-1, -1), 24)
        style.add("LEADING", (0, 0), (-1, -1), 24)
        style.add("BOX", (0, 0), (-1, -1), 0.25, colors.black)
        style.add("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black)
        # style.add('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black)
        style.add("LINEBELOW", (0, -1), (-1, -1), 2, colors.green)

        style.add("LEFTPADDING", (0, 0), (-1, -1), 0)
        style.add("RIGHTPADDING", (0, 0), (-1, -1), 0)
        style.add("BOTTOMPADDING", (0, 0), (-1, -1), 0)
        style.add("TOPPADDING", (0, 0), (-1, -1), 0)

        table.setStyle(style)

    story = 3 * [table]

    doc = SimpleDocTemplate(filename=context, pagesize=pagesize)
    if not OUT2PDF:
        doc.setPageCallBack(getattr(context, "new_page", None))
    doc.build(story, canvasmaker=Canvas)
 def render(self):
     buffer = cStringIO.StringIO()
     doc_template_args = self.theme.doc_template_args()
     doc = SimpleDocTemplate(buffer, title=self.title, author=self.author,
         **doc_template_args)
     doc.build(self.story)
     pdf = buffer.getvalue()
     buffer.close()
     return pdf
示例#26
0
def __to_pdf(temp, data):
    doc = SimpleDocTemplate(temp, pagesize=landscape(A4), leftMargin=MARGIN,
                            rightMargin=MARGIN, topMargin=MARGIN,
                            bottomMargin=MARGIN,
                            title=u'Situația activ/pasiv pentru %s' % data['building'].name,
                            author='www.habitam.ro')
     
    flowables = [Spacer(1, 6 * cm), __format_data(data), Spacer(1, cm), signatures()]
    doc.habitam_data = data    
    doc.build(flowables, onFirstPage=__balance_format, onLaterPages=__balance_format)
示例#27
0
def make_pagerecorder( story, pagesize =None, **kargs):
    from reporter.engine.rl2wx.page_recorder import PageRecorder
    from reporter.engine.rl2wx.canvas import Canvas as wxCanvas
    from reportlab.platypus.doctemplate import SimpleDocTemplate
    page_recorder = PageRecorder( pagesize)
    doc = SimpleDocTemplate( filename=page_recorder, pagesize=pagesize, **kargs)
    doc.setPageCallBack( getattr( page_recorder, 'new_page', None))
    doc.build( list(story), canvasmaker=wxCanvas)
    page_recorder.debug_doc = doc
    return page_recorder
示例#28
0
 def build(self):
     doc = SimpleDocTemplate(
         os.path.join(self.report_directory, "report.pdf"),
         pagesize = A4,
         title=self.title,
         author=self.author,
         rightMargin=self.theme.margins['right'],
         leftMargin=self.theme.margins['left'],
         topMargin=self.theme.margins['top'],
         bottomMargin=self.theme.margins['bottom'])
     doc.build(self.story, onFirstPage=self.first_page, onLaterPages=self.later_pages)
示例#29
0
 def test1(self):
     '''Ilpo Nyyss\xf6nen posted this broken test'''
     normalStyle = ParagraphStyle(name='normal')
     keepStyle = ParagraphStyle(name='keep', keepWithNext=True)
     content = [
         Paragraph("line 1", keepStyle),
         Indenter(left=1 * cm),
         Paragraph("line 2", normalStyle),
     ]
     doc = SimpleDocTemplate(outputfile('test_platypus_breaking1.pdf'))
     doc.build(content)
示例#30
0
def relatorio_base_consulta(request, lista, titulo):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="'+str(titulo).replace(' ', '_')+'.pdf"'
    doc = SimpleDocTemplate(response, rightMargin=72,leftMargin=72, topMargin=72,bottomMargin=18)
    styles=getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    ptext = '<font size=14>%s</font>' % titulo
    story = []
    story.append(Paragraph(ptext, styles["Normal"]))
    doc.build(story)
    return response
 def test1(self):
     '''Ilpo Nyyss\xf6nen posted this broken test'''
     normalStyle = ParagraphStyle(name = 'normal')
     keepStyle = ParagraphStyle(name = 'keep', keepWithNext = True)
     content = [
         Paragraph("line 1", keepStyle),
         Indenter(left = 1 * cm),
         Paragraph("line 2", normalStyle),
         ]
     doc = SimpleDocTemplate(outputfile('test_platypus_breaking1.pdf'))
     doc.build(content)
示例#32
0
    def generate(self):
        doc = SimpleDocTemplate(
            '/home/danimar/Documentos/danfe.pdf',
            pagesize=A4, leftMargin=0.5 * inch, rightMargin=0.5 * inch,
            topMargin=0.5 * inch, bottomMargin=0.5 * inch)

        elementos = []

        elementos.append(self._header())
        elementos.append(self._segundo_cabecalho())

        doc.build(elementos)
示例#33
0
    def gerar(self):
        doc = SimpleDocTemplate(
            '/home/danimar/projetos/pdfs/danfe.pdf',
            pagesize=A4, leftMargin=0.5 * inch, rightMargin=0.5 * inch,
            topMargin=0.5 * inch, bottomMargin=0.5 * inch)

        elementos = []
        
        elementos.append(self._header())
        elementos.append(self._segundo_cabecalho())

        doc.build(elementos)
示例#34
0
def	Stamp(buff,d_id,person):
    
    ### --- Список согласователей ---
    per = FIO_Job_Person(person)

    Font1 = ttfonts.TTFont('PT','kis/fonts/PTC55F.ttf')
    Font2 = ttfonts.TTFont('PTB','kis/fonts/PTC75F.ttf')
    Font3 = ttfonts.TTFont('PTI','kis/fonts/PTS56F.ttf')

    pdfmetrics.registerFont(Font1)
    pdfmetrics.registerFont(Font2)
    pdfmetrics.registerFont(Font3)


    style = getSampleStyleSheet()
    style.add(ParagraphStyle(name='Head',wordWrap=True,fontName='PTB',fontSize=14,spaceAfter=5*mm,spaceBefore=5*mm,alignment=1))
    style.add(ParagraphStyle(name='DepName',wordWrap=True,fontName='PTB',fontSize=10,spaceAfter=5*mm,spaceBefore=5*mm,alignment=1))
    style.add(ParagraphStyle(name='Data',wordWrap=True,fontName='PT',fontSize=8,spaceAfter=1*mm,spaceBefore=1*mm,alignment=0))
    
    doc = SimpleDocTemplate(buff,topMargin=10*mm,bottomMargin=10*mm,leftMargin=20*mm,rightMargin=10*mm)

    elements = []

    elements.append(Paragraph('КИС Договоры заявки',style["Head"]))
    elements.append(Paragraph('Номер заявки '+str(d_id),style["Head"]))


    Tdata = [['Участники договорной\nработы','ФИО лица,\nзавизировавшего договор'],]

    author = per[0]
    Tdata.append([Paragraph(u'Ответственный исполнитель, '+author[0],style["Data"]),Paragraph(author[1],style["Data"])],)
    
    for item in per[1:]:
	Tdata.append([Paragraph(item[0],style["Data"]),Paragraph(item[1],style["Data"])],)
    
    TableHead=Table(Tdata)
    TableHead.setStyle([('FONTNAME',(0,0),(-1,-1),'PTB'),
		('FONTSIZE',(0,0),(-1,-1),10),
		('ALIGN',(0,0),(-1,0),'CENTER'),
		('ALIGN',(0,1),(-1,-1),'LEFT'),
		('VALIGN',(0,0),(-1,-1),'MIDDLE'),
		('GRID',(0,0),(-1,-1),0.25,colors.black),
		])


    elements.append(TableHead)



    doc.build(elements)

    return buff
示例#35
0
    def saveAsHandout(self):
        """Write the PDF document, multiple slides per page."""

        styleSheet = getSampleStyleSheet()
        h1 = styleSheet['Heading1']
        bt = styleSheet['BodyText']

        if self.sourceFilename :
            filename = os.path.splitext(self.sourceFilename)[0] + '.pdf'

        outfile = BytesIO()
        doc = SimpleDocTemplate(outfile, pagesize=rl_config.defaultPageSize, showBoundary=0)
        doc.leftMargin = 1*cm
        doc.rightMargin = 1*cm
        doc.topMargin = 2*cm
        doc.bottomMargin = 2*cm
        multiPageWidth = rl_config.defaultPageSize[0] - doc.leftMargin - doc.rightMargin - 50

        story = []
        orgFullPageSize = (self.pageWidth, self.pageHeight)
        t = makeSlideTable(self.slides, orgFullPageSize, multiPageWidth, self.cols)
        story.append(t)

##        #ensure outline visible by default
##        if self.showOutline:
##            doc.canv.showOutline()

        doc.build(story)
        return self.savetofile(outfile, filename)
 def generate_systematic_pdf(self, filename):
     '''
     The public method to create a pdf file.
     
     Might throw an exception if the file can't be written.
     '''
     
     tree = self.systematic_dao.get_tree()
     
     doc = SimpleDocTemplate(filename)
     story = []
     for child in tree.root_node.children:
         story = self._print_root_node(story, child)
         story.append(PageBreak())
     doc.build(story)        
示例#37
0
def generar_pdf_estudio_list(response, estudios):
    pdf = SimpleDocTemplate(
        response,
        pagesize=A4,
        title='Listado de estudios',
        topMargin=MARGINS['top'],
        bottomMargin=MARGINS['bottom'],
    )

    largos_columnas = [columna[1] for columna in COLUMNAS]
    elements = pdf_tabla(estudios, largos_columnas, pdf_tabla_encabezado,
                         pdf_tabla_body)

    pdf.build(elements)
    return response
示例#38
0
def relatorio_base_consulta(request, lista, titulo):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="' + str(
        titulo).replace(' ', '_') + '.pdf"'
    doc = SimpleDocTemplate(response,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    ptext = '<font size=14>%s</font>' % titulo
    story = []
    story.append(Paragraph(ptext, styles["Normal"]))
    doc.build(story)
    return response
示例#39
0
 def publish(self, filename, includeTOC=True):
     if includeTOC and self.toc_included:
         doc = PDFDocTemplate(filename)
         doc.multiBuild(self.contents, onLaterPages=self.pageLayout)
     else:
         doc = SimpleDocTemplate(filename)
         doc.build(self.contents, onLaterPages=self.pageLayout)
示例#40
0
    def doc(self, e):
        format = e.get('format', 'A4')
        raw_margins = e.get('margin', '2cm, 2cm, 2cm, 2cm')
        title = e.get('title')

        if ',' in format:
            w, h = (toLength(i.strip()) for i in format.split(','))
            format = (w, h)
        else:
            format = eval('pagesizes.' + format.upper())

        topMargin, rightMargin, bottomMargin, leftMargin = (toLength(
            i.strip()) for i in raw_margins.split(','))

        def make_canvas(*args, **kwargs):
            canvas = Canvas(*args, **kwargs)
            canvas.setLineWidth(0.25)
            return canvas

        if self.document is None:
            self.document = SimpleDocTemplate(self.out_buffer,
                                              pagesize=format,
                                              title=title,
                                              topMargin=topMargin,
                                              leftMargin=leftMargin,
                                              rightMargin=rightMargin,
                                              bottomMargin=bottomMargin,
                                              canvasmaker=make_canvas)

        for i in self.parse_children(e):
            yield i
示例#41
0
    def test(self):
        outPDF = "test_autocolwidths.pdf"

        # Column widths in mm
        colWidths = None

        # Some test data in German.
        testdata = \
        [u"<para>Mit <i>Silbentrennungsverfahren</i> werden extrem lange W\xF6rter, die im deutschen Sprachgebrauch allt\xE4glich sind, automatisch in kleinere Bestandteile zerlegt, wobei die Lesbarkeit nach M\xF6glichkeit erhalten bleiben sollte.</para>",
         u"<para>Dieser Absatz hat nur sehr kurze Wörter.</para>",
         u"<para>Der hier erst recht!</para>",
         u"<para>Der Bundeskanzler arbeitet im <font size='12'>Bundeskanzler</font>amt.</para>",
        ]

        pagesize = pagesizes.portrait(pagesizes.A4)

        tablestyle = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('BOX', (0, 0), (-1, -1), 1, colors.black),
            ('BACKGROUND', (0, 0), (-1, 0), colors.orange),
            ('INNERGRID', (0, 1), (-1, -1), 0.5, colors.black),
            ('LEFTPADDING', (0, 0), (-1, -1), 3),
            ('RIGHTPADDING', (0, 0), (-1, -1), 3),
        ])

        doc = SimpleDocTemplate(outPDF,
                                title="Hyphenation for styled text paragraphs",
                                pagesize=pagesize,
                                allowSplitting=1)
        story = []

        header = ["Col%d" % (i + 1) for i in range(4)]
        tabContent = [header]
        row = [makeParagraphs(txt, cellStyle) for txt in testdata]
        tabContent.append(row)
        row = [
            makeParagraphs((u"Zeile 2 Spalte %i" % (i + 1)), cellStyle)
            for i in range(4)
        ]
        tabContent.append(row)
        table = LongTable(tabContent,
                          colWidths=colWidths,
                          style=tablestyle,
                          repeatRows=1)
        story.append(table)
        doc.build(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
示例#42
0
    def build_container_file(self):

        s = set(self.childs.all().order_by(
            '-midia__versions__created').values_list(
                'midia__versions__content_type', flat=True))

        if not (s - TIPOS_IMG_PERMITIDOS):
            response = HttpResponse(content_type='application/pdf')
            response['Content-Disposition'] = \
                'inline; filename="documento.pdf"'

            doc = SimpleDocTemplate(
                response,
                rightMargin=0,
                leftMargin=0,
                topMargin=0,
                bottomMargin=0)

            c = canvas.Canvas(response)
            c.setTitle(self.titulo)
            A4_landscape = landscape(A4)
            for img in self.childs.order_by('ordem'):
                path = img.midia.last.file.path

                if img.midia.last.is_paisagem:
                    c.setPageSize(A4_landscape)
                else:
                    c.setPageSize(A4)

                dim = A4_landscape if img.midia.last.is_paisagem else A4
                c.drawImage(path, 0, 0,
                            width=dim[0],
                            height=dim[1])
                c.showPage()
            c.save()
            return response

        else:
            file_buffer = io.BytesIO()

            with zipfile.ZipFile(file_buffer, 'w') as file:
                for f in self.childs.order_by('ordem'):
                    fn = '%s-%s' % (
                        f.id,
                        f.midia.last.file.path.split(
                            '/')[-1])
                    file.write(f.midia.last.file.path,
                               arcname=fn)

            response = HttpResponse(file_buffer.getvalue(),
                                    content_type='application/zip')

            response['Cache-Control'] = 'no-cache'
            response['Pragma'] = 'no-cache'
            response['Expires'] = 0
            response['Content-Disposition'] = \
                'inline; filename=%s.zip' % self.raiz.slug
            return response
示例#43
0
 def pdf_response(self):
     """
    returns pdf HttpResponse.
 """
     response = HttpResponse(mimetype="application/pdf")
     response['Content-Disposition'] = 'filename=' + self.filename + '.pdf'
     doc = SimpleDocTemplate(response,
                             topMargin=inch / 2,
                             bottomMargin=inch / 2,
                             leftMargin=inch / 2,
                             rightMargin=inch / 2)
     elements = []
     data = []
     for i in range(self.table.no_of_rows()):
         q = []
         for j in range(self.table.no_of_columns()):
             q.append(self.table.cell(i, j))
         data.append(q)
     header = []
     if self.date:
         header.append(['Date : ' + self.date])
     for heading in self.headings:
         header.append([heading])
     header.append([''])
     er = len(header)
     width, height = defaultPageSize
     width = width - inch
     t = pdfTable(header + data, [
         int(width * self.table.col_width_percent(i) / 100.)
         for i in range(self.table.no_of_columns())
     ])
     style_list = []
     for i in range(len(header)):
         style_list.append(('SPAN', (0, i), (-1, i)))
     style_list += [
         ('ALIGN', (0, 1 if self.date else 0), (-1, er - 1), 'CENTER'),
         ('FONT', (0, 0), (-1, er), 'Helvetica-Bold'),
         ('INNERGRID', (0, er), (-1, -1), 1, colors.black),
         ('BOX', (0, er), (-1, -1), 1, colors.black),
         ('BACKGROUND', (0, er), (-1, -1), colors.HexColor('#efefef'))
     ]
     t.setStyle(TableStyle(style_list))
     elements.append(t)
     doc.build(elements)
     return response
示例#44
0
    def saveAsHandout(self):
        """Write the PDF document, multiple slides per page."""

        styleSheet = getSampleStyleSheet()
        h1 = styleSheet["Heading1"]
        bt = styleSheet["BodyText"]

        if self.sourceFilename:
            filename = os.path.splitext(self.sourceFilename)[0] + ".pdf"

        outfile = getStringIO()
        doc = SimpleDocTemplate(outfile, pagesize=rl_config.defaultPageSize, showBoundary=0)
        doc.leftMargin = 1 * cm
        doc.rightMargin = 1 * cm
        doc.topMargin = 2 * cm
        doc.bottomMargin = 2 * cm
        multiPageWidth = rl_config.defaultPageSize[0] - doc.leftMargin - doc.rightMargin - 50

        story = []
        orgFullPageSize = (self.pageWidth, self.pageHeight)
        t = makeSlideTable(self.slides, orgFullPageSize, multiPageWidth, self.cols)
        story.append(t)

        ##        #ensure outline visible by default
        ##        if self.showOutline:
        ##            doc.canv.showOutline()

        doc.build(story)
        return self.savetofile(outfile, filename)
示例#45
0
文件: imprimir.py 项目: cedir/web
def generar_informe(response, estudio):
    # Create the PDF object, using the response object as its "file."
    doc = SimpleDocTemplate(
        response,
        pagesize=A4,
        topMargin=55*mm,
        bottomMargin=65*mm if estudio.enlace_video else 25*mm,
        rightMargin=17*mm,
        leftMargin=17*mm
    )

    elements = []

    _datos_estudio(elements, estudio)
    _informe(elements, estudio)

    doc.build(elements, onFirstPage=_draw_firstpage_frame(estudio), onLaterPages=_draw_firstpage_frame(estudio, False))
    return response
示例#46
0
def generar_pdf_presentacion(response, presentacion):

    pdf = SimpleDocTemplate(
        response,
        pagesize = (A4),
        topMargin = TOPMARGIN,
        bottomMargin = BOTTOMMARGIN,
        rightMargin = RIGHTMARGIN,
        leftMargin = LEFTMARGIN,
    )

    elements = pdf_encabezado(presentacion['obra_social'], presentacion['fecha'], presentacion['periodo'])
    estudios, total_presentacion = pdf_estudios(presentacion['estudios'])
    for estudio in estudios:
        elements += estudio
    elements += [HLINE ,KeepTogether(Paragraph(f"Total: ${total_presentacion}", styles['Heading2']))]
    pdf.build(elements, canvasmaker=NumberedPageCanvas)
    return response
示例#47
0
def generate_history_report(request, patientId):
    """
    generates report of patients' history
    :param request: http request
    :param patientId: patient Id
    :return: http response
    """
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

    thePatient = Patient.objects.get(pk=int(patientId))
    theHistory = PatientHistory( thePatient, request).computeHistory()
    theReport = ReportGenerator(request,theHistory, thePatient.get_name()).report()

    doc = SimpleDocTemplate(response)

    doc.build(theReport)
    return response
示例#48
0
文件: imprimir.py 项目: cedir/web
def generar_informe(response, estudio):
    # Create the PDF object, using the response object as its "file."
    doc = SimpleDocTemplate(response,
                            pagesize=A4,
                            topMargin=55 * mm,
                            bottomMargin=65 *
                            mm if estudio.enlace_video else 25 * mm,
                            rightMargin=17 * mm,
                            leftMargin=17 * mm)

    elements = []

    _datos_estudio(elements, estudio)
    _informe(elements, estudio)

    doc.build(elements,
              onFirstPage=_draw_firstpage_frame(estudio),
              onLaterPages=_draw_firstpage_frame(estudio, False))
    return response
示例#49
0
def export_to_pdf(modeladmin, request, queryset):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    # Append invoice number and invoice date
    if len(queryset) != 1:
        _file_name = '-'.join([a.invoice_number for a in queryset.order_by("invoice_number")])
        response['Content-Disposition'] = 'attachment; filename="invoice%s.pdf"' % (_file_name.replace(" ", "")[:150])
    else:
        response['Content-Disposition'] = 'attachment; filename="invoice-%s-%s-%s.pdf"' % (queryset[0].patient.name,
                                                                                           queryset[0].invoice_number,
                                                                                           queryset[
                                                                                               0].invoice_date.strftime(
                                                                                               '%d-%m-%Y'))

    doc = SimpleDocTemplate(response, rightMargin=2 * cm, leftMargin=2 * cm, topMargin=1 * cm, bottomMargin=1 * cm)
    elements = get_doc_elements(queryset, False)
    doc.build(elements)

    return response
示例#50
0
def armar_pdf(response: Response, datos: Dict, lineas: List, totales: Dict,
              es_inscripto: bool) -> Response:
    # Create the PDF object, using the response object as its "file."
    pagesizes = A4 if not es_inscripto else landscape(A4)
    pdf = SimpleDocTemplate(
        response,
        pagesize=pagesizes,
        topMargin=MARGINS['top'],
        bottomMargin=MARGINS['bottom'],
        rightMargin=MARGINS['right'],
        leftMargin=MARGINS['left'],
    )

    elements = encabezado(datos) \
        + tabla(lineas, es_inscripto) \
        + informacion_extra(totales, es_inscripto)

    pdf.build(elements, canvasmaker=NumberedPageCanvas)
    return response
示例#51
0
def show_pdf(request,cat_id):
    tag = Tag.objects.get(pk=cat_id)
    word_ids = Tag.objects.get(pk=cat_id).items.values('object_id')
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s.pdf'%(str(tag))
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    D = '/usr/share/fonts/truetype/ttf-lg-aboriginal/'
    pdfmetrics.registerFont(TTFont('Vera', D+'AboriginalSansREGULAR9433.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBd', D+'AboriginalSansBOLD9433.ttf'))
    pdfmetrics.registerFont(TTFont('VeraIt', D+'AboriginalSansITALIC9433.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBI', D+'AboriginalSansBOLDITALIC9433.ttf'))

    registerFontFamily('Vera',normal='Vera',bold='VeraBd',italic='VeraIt',boldItalic='VeraBI')

    buffer = StringIO()

    doc = SimpleDocTemplate(buffer)
    Catalog = []
    styles = getSampleStyleSheet()
    header = Paragraph("%s"%(str(tag)), styles['Heading1'])
    Catalog.append(header)
    style = ParagraphStyle(
        name='Normal',
        fontName='Vera',
        fontSize=12,
    )
    count = 0
    for id in word_ids:
        word = Word.objects.get(pk=id['object_id'])
        p = Paragraph("%s - %s" % (word.secwepemc, word.english()),style)
        Catalog.append(p)
        s = Spacer(1, 0.25*inch)
        Catalog.append(s)
    doc.build(Catalog)

    # Get the value of the StringIO buffer and write it to the response.
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
示例#52
0
文件: imprimir.py 项目: cedir/web
def generar_pdf_caja(response: HttpResponse,
                     movimientos: MovimientosSerializer,
                     fecha: Optional[datetime], monto_acumulado: Decimal,
                     total: Decimal) -> HttpResponse:
    pdf = SimpleDocTemplate(
        response,
        pagesize=landscape(A4),
        title='Movimientos de caja {0}'.format(fecha),
        topMargin=MARGINS['top'],
        bottomMargin=MARGINS['bottom'],
    )

    elements = pdf_encabezado(fecha, monto_acumulado)
    largos_columnas = [columna[1] for columna in COLUMNAS]
    elements += pdf_tabla(movimientos, largos_columnas, pdf_tabla_encabezado,
                          pdf_tabla_body)
    elements += pdf_pie(total)

    pdf.build(elements)
    return response
示例#53
0
    def get_inmemory_pdf(batch):
        io_buffer = BytesIO()
        doc = SimpleDocTemplate(io_buffer,
                                rightMargin=2 * cm,
                                leftMargin=2 * cm,
                                topMargin=1 * cm,
                                bottomMargin=1 * cm)
        elements = get_doc_elements(batch.invoice_items)
        doc.build(elements)

        f = io_buffer.getvalue()
        in_memory_file = InMemoryUploadedFile(
            io_buffer,
            field_name=None,
            name=InvoiceItemBatchPdf.get_filename(batch=batch),
            content_type="application/pdf",
            size=sys.getsizeof(f),
            charset=None)

        return in_memory_file
 def test1(self):
     from reportlab.lib.styles import ParagraphStyle
     from reportlab.platypus import SimpleDocTemplate, Paragraph
     from reportlab.platypus.flowables import DocAssign, DocExec, DocPara, DocIf, DocWhile
     normal = ParagraphStyle(name='Normal',
                             fontName='Helvetica',
                             fontSize=8.5,
                             leading=11)
     header = ParagraphStyle(name='Heading1',
                             parent=normal,
                             fontSize=14,
                             leading=19,
                             spaceAfter=6,
                             keepWithNext=1)
     story = [
         DocAssign('currentFrame', 'doc.frame.id'),
         DocAssign('currentPageTemplate', 'doc.pageTemplate.id'),
         DocAssign('aW', 'availableWidth'),
         DocAssign('aH', 'availableHeight'),
         DocAssign('aWH', 'availableWidth,availableHeight'),
         DocAssign('i', 3),
         DocIf('i>3', Paragraph('The value of i is larger than 3', normal),
               Paragraph('The value of i is not larger than 3', normal)),
         DocIf('i==3', Paragraph('The value of i is equal to 3', normal),
               Paragraph('The value of i is not equal to 3', normal)),
         DocIf('i<3', Paragraph('The value of i is less than 3', normal),
               Paragraph('The value of i is not less than 3', normal)),
         DocWhile('i', [
             DocPara('i',
                     format='The value of i is %(__expr__)d',
                     style=normal),
             DocExec('i-=1')
         ]),
         DocPara('repr(doc._nameSpace)', escape=True),
         DocPara('doc.canv.getPageNumber()',
                 'The current page number is %(__expr__)d',
                 style=normal)
     ]
     doc = SimpleDocTemplate(outputfile('test_doc_programming.pdf'))
     doc.build(story)
 def test1(self):
     from reportlab.lib.styles import ParagraphStyle
     from reportlab.platypus import SimpleDocTemplate, Paragraph
     from reportlab.platypus.flowables import DocAssign, DocExec, DocPara, DocIf, DocWhile
     normal = ParagraphStyle(name='Normal', fontName='Helvetica', fontSize=8.5, leading=11)
     header = ParagraphStyle(name='Heading1', parent=normal, fontSize=14, leading=19,
                 spaceAfter=6, keepWithNext=1)
     story = [
             DocAssign('currentFrame','doc.frame.id'),
             DocAssign('currentPageTemplate','doc.pageTemplate.id'),
             DocAssign('aW','availableWidth'),
             DocAssign('aH','availableHeight'),
             DocAssign('aWH','availableWidth,availableHeight'),
             DocAssign('i',3),
             DocIf('i>3',Paragraph('The value of i is larger than 3',normal),Paragraph('The value of i is not larger than 3',normal)),
             DocIf('i==3',Paragraph('The value of i is equal to 3',normal),Paragraph('The value of i is not equal to 3',normal)),
             DocIf('i<3',Paragraph('The value of i is less than 3',normal),Paragraph('The value of i is not less than 3',normal)),
             DocWhile('i',[DocPara('i',format='The value of i is %(__expr__)d',style=normal),DocExec('i-=1')]),
             DocPara('repr(doc._nameSpace)',escape=True),
             ]
     doc = SimpleDocTemplate(outputfile('test_doc_programming.pdf'))
     doc.build(story)
示例#56
0
def doLayout(title, data, colWidths, outPDF):
    """Create a tabular PDF file from the given data.
    """
    pagesize = pagesizes.portrait(pagesizes.A4)

    tablestyle = TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1, colors.black),
        ('BACKGROUND', (0, 0), (-1, 0), colors.orange),
        ('INNERGRID', (0, 1), (-1, -1), 0.5, colors.black),
        ('LEFTPADDING', (0, 0), (-1, -1), 3),
        ('RIGHTPADDING', (0, 0), (-1, -1), 3),
    ])

    doc = SimpleDocTemplate(outPDF,
                            title=title,
                            pagesize=pagesize,
                            allowSplitting=1)
    story = []

    header = ["%d mm" % w for w in colWidths]
    colWidths = [w * mm for w in colWidths]
    if sum(colWidths) > pagesize[0]:
        raise ValueError("Overall column width too wide!")

    tabContent = [header]
    for txt in data:
        row = []
        # Note: we have to create copies by calling makeParagraphs for each cell.
        # We cannot just create one Paragraph and reference it several times.
        for col in colWidths:
            row.append(makeParagraphs(txt, cellStyle))
        tabContent.append(row)
    table = LongTable(tabContent,
                      colWidths=colWidths,
                      style=tablestyle,
                      repeatRows=1)
    story.append(table)
    doc.build(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
示例#57
0
 def test1(self):
     from reportlab.lib.styles import ParagraphStyle
     from reportlab.platypus import SimpleDocTemplate, Paragraph
     from reportlab.platypus.flowables import DocAssign, DocExec, DocPara, DocIf, DocWhile
     normal = ParagraphStyle(name='Normal', fontName='Helvetica', fontSize=8.5, leading=11)
     header = ParagraphStyle(name='Heading1', parent=normal, fontSize=14, leading=19,
                 spaceAfter=6, keepWithNext=1)
     story = [
             DocAssign('currentFrame','doc.frame.id'),
             DocAssign('currentPageTemplate','doc.pageTemplate.id'),
             DocAssign('aW','availableWidth'),
             DocAssign('aH','availableHeight'),
             DocAssign('aWH','availableWidth,availableHeight'),
             DocAssign('i',3),
             DocIf('i>3',Paragraph('The value of i is larger than 3',normal),Paragraph('The value of i is not larger than 3',normal)),
             DocIf('i==3',Paragraph('The value of i is equal to 3',normal),Paragraph('The value of i is not equal to 3',normal)),
             DocIf('i<3',Paragraph('The value of i is less than 3',normal),Paragraph('The value of i is not less than 3',normal)),
             DocWhile('i',[DocPara('i',format='The value of i is %(__expr__)d',style=normal),DocExec('i-=1')]),
             DocPara('"{"+", ".join(("%s=%s" % (_k,(_v.__class__.__name__ if "<" in repr(_v) else repr(_v)[1:] if repr(_v) and repr(_v)[0] in "ub" else repr(_v))) for _k,_v in sorted(doc._nameSpace.items()) if _k not in ("_k","_v")))+"}"',escape=True),
             DocPara('doc.canv.getPageNumber()','The current page number is %(__expr__)d',style=normal) 
             ]
     doc = SimpleDocTemplate(outputfile('test_doc_programming.pdf'))
     doc.build(story)
 def pdf_response(self):
   """
      returns pdf HttpResponse.
   """
   response = HttpResponse(mimetype="application/pdf")
   response['Content-Disposition'] = 'filename='+ self.filename + '.pdf'
   doc = SimpleDocTemplate(response,topMargin = inch/2,bottomMargin = inch/2,leftMargin = inch/2, rightMargin = inch/2)      
   elements = []
   data = []
   for i in range(self.table.no_of_rows()):
     q = []
     for j in range(self.table.no_of_columns()):
       q.append(self.table.cell(i,j))
     data.append(q) 
   header = []
   if self.date:
     header.append(['Date : '+self.date])
   for heading in self.headings:
     header.append([heading])
   header.append([''])
   er = len(header)    
   width,height = defaultPageSize
   width = width - inch    
   t=pdfTable(header+data,[int(width*self.table.col_width_percent(i)/100.) for i in range(self.table.no_of_columns())])
   style_list = []
   for i in range(len(header)):
     style_list.append(('SPAN',(0,i),(-1,i)))
   style_list+=[('ALIGN',(0,1 if self.date else 0),(-1,er-1),'CENTER'),
                ('FONT',(0,0),(-1,er),'Helvetica-Bold'),
                ('INNERGRID', (0,er), (-1,-1), 1, colors.black),
                ('BOX', (0,er), (-1,-1), 1, colors.black),
                ('BACKGROUND',(0,er),(-1,-1),colors.HexColor('#efefef'))]
   t.setStyle(TableStyle(style_list))
   elements.append(t) 
   doc.build(elements)
   return response
 def func(val):
     story = [
             DocAssert(val,'this should fail'),
             DocPara("'val=%r'" % val),
             DocPara('"{"+", ".join(("%s=%s" % (_k,(_v.__class__.__name__ if "<" in repr(_v) else repr(_v)[1:] if repr(_v) and repr(_v)[0] in "ub" else repr(_v))) for _k,_v in sorted(doc._nameSpace.items()) if _k not in ("_k","_v")))+"}"',escape=True),
             ]
     doc = SimpleDocTemplate(outputfile('test_doc_programming_asserts.pdf'))
     doc.build(story)