コード例 #1
0
def alternate_orientations():
    doc = SimpleDocTemplate("orientations.pdf",
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)
    styles = getSampleStyleSheet()
    normal = styles["Normal"]

    margin = 0.5 * inch
    frame = Frame(margin, margin, doc.width, doc.height, id='frame')
    portrait_template = PageTemplate(id='portrait',
                                     frames=[frame],
                                     pagesize=letter)
    landscape_template = PageTemplate(id='landscape',
                                      frames=[frame],
                                      pagesize=landscape(letter))
    doc.addPageTemplates([portrait_template, landscape_template])

    story = []
    story.append(Paragraph('This is a page in portrait orientation', normal))

    # Change to landscape orientation
    story.append(NextPageTemplate('landscape'))
    story.append(PageBreak())
    story.append(Spacer(inch, 2 * inch))
    story.append(Paragraph('This is a page in landscape orientation', normal))

    # Change back to portrait
    story.append(NextPageTemplate('portrait'))
    story.append(PageBreak())
    story.append(Paragraph("Now we're back in portrait mode again", normal))

    doc.build(story)
コード例 #2
0
ファイル: printview.py プロジェクト: mediatum/mediatum
 def build(self, printfile, style=1):
     template = SimpleDocTemplate(printfile, showBoundary=0)
     tFirst = PageTemplate(id='First', frames=self.getStyle(1, style), onPage=self.myPages, pagesize=defaultPageSize)
     tNext = PageTemplate(id='Later', frames=self.getStyle(2, style), onPage=self.myPages, pagesize=defaultPageSize)
     template.addPageTemplates([tFirst, tNext])
     template.allowSplitting = 1
     BaseDocTemplate.build(template, self.data)
コード例 #3
0
 def addPageTemplates(self, pageTemplates):
     '''fix up the one and only Frame'''
     if pageTemplates:
         f = pageTemplates[0].frames[0]
         f._leftPadding = f._rightPadding = f._topPadding = f._bottomPadding = 0
         #f._reset()
         f._geom()
     SimpleDocTemplate.addPageTemplates(self, pageTemplates)
コード例 #4
0
 def addPageTemplates(self, pageTemplates):
     """
     fix up the one and only Frame
     """
     if pageTemplates:
         f = pageTemplates[0].frames[0]
         f._leftPadding = f._rightPadding = f._topPadding = f._bottomPadding = 0
         f._geom()
     SimpleDocTemplate.addPageTemplates(self, pageTemplates)
コード例 #5
0
    def build(self, style=1):
        template = SimpleDocTemplate(config.get("paths.tempdir", "") + "print.pdf", showBoundary=0)
        tFirst = PageTemplate(id='First', frames=self.getStyle(1, style), onPage=self.myPages, pagesize=defaultPageSize)
        tNext = PageTemplate(id='Later', frames=self.getStyle(2, style), onPage=self.myPages, pagesize=defaultPageSize)

        template.addPageTemplates([tFirst, tNext])
        template.allowSplitting = 1
        BaseDocTemplate.build(template, self.data)
        return template.canv._doc.GetPDFData(template.canv)
コード例 #6
0
def create_cover_page(title, table_contents, text_para=None, file_obj=None):
    if file_obj is None:
        file_obj = tempfile.TemporaryFile(suffix='.pdf')

    # this is all kind of weird, stolen from here: http://stackoverflow.com/a/11942346/1003950
    def footer(canvas, doc):
        canvas.saveState()
        P = Paragraph(
            "(c) Compliance.ai. No claim to original U.S. Government Works.",
            styles['Normal'])
        w, h = P.wrap(doc.width, doc.bottomMargin)
        P.drawOn(canvas, doc.leftMargin, h)
        canvas.restoreState()

    pdf_doc = SimpleDocTemplate(file_obj, pagesize=letter)
    frame = Frame(pdf_doc.leftMargin,
                  pdf_doc.bottomMargin,
                  pdf_doc.width,
                  pdf_doc.height,
                  id='normal')
    template = PageTemplate(id='cover', frames=frame, onPage=footer)
    pdf_doc.addPageTemplates([template])

    CoverPage = []

    CoverPage.append(
        Image('assets/compliance_ai_logo_blk.png',
              width=int(5.0 * inch),
              height=int((5.0 / LOGO_ASPECT_RATIO) * inch)))
    CoverPage.append(Spacer(1, 0.5 * inch))

    CoverPage.append(Paragraph(title, styles['Title']))
    CoverPage.append(Spacer(1, 0.5 * inch))

    if text_para:
        CoverPage.append(Paragraph(text_para, styles['Normal']))
        CoverPage.append(Spacer(1, 0.5 * inch))

    num_cols = len(table_contents[0])
    table_col_widths = [TABLE_WIDTH / num_cols for i in xrange(0, num_cols)]

    # put the contents of all cells into a paragraph to ensure word wrap
    for (i, row) in enumerate(table_contents):
        new_row = []
        for (j, col) in enumerate(row):
            table_contents[i][j] = Paragraph(str(col), styles['Normal'])

    t = Table(table_contents, colWidths=table_col_widths)
    t.setStyle(TableStyle([['VALIGN', (0, 0), (-1, -1), 'TOP']]))
    CoverPage.append(t)
    CoverPage.append(Spacer(1, 0.5 * inch))

    pdf_doc.build(CoverPage)

    file_obj.flush()

    return file_obj
コード例 #7
0
ファイル: models.py プロジェクト: ivanahad/sep2015E
    def generate_pdf(self):
        """ Generate a pdf version of the pools."""
        doc = SimpleDocTemplate("files/"+self.name + ".pdf", rightMargin=72, leftMargin=72,
                                topMargin=72, bottomMargin=18, showBoundary=1)
        doc.pagesize=landscape(A4)
        Story=[]

        file_path="file_path"
        date = time.ctime()
        header_title="CDL - tableaux de poules"
        number_pool="10"
        field="Jc et Nath \n3080 Tervuren"
        tournament="Double Mixte - Juniors - JUN"

        #frames
        frameTable = Frame(doc.leftMargin, doc.height*0.20,
                    doc.height-doc.rightMargin , 400,
                    leftPadding=0, rightPadding=0, id='normal')

        def footer_header(canvas,doc):
            """Footer and header description"""
            canvas.saveState()
            canvas.setFont('Times-Roman',12)

            #Header
            header_y=doc.height + 72
            canvas.drawString(20, header_y, date)
            canvas.drawString(doc.width/2, header_y, header_title)
            canvas.drawString(doc.leftMargin, header_y-20, "Numéro:")
            canvas.drawString(doc.leftMargin+100, header_y-20, "Terrain:")
            canvas.drawString(doc.leftMargin+5, header_y-45, number_pool)
            canvas.drawString(doc.leftMargin+105, header_y-45, field)
            canvas.drawString(doc.leftMargin+5, header_y-70, tournament)

            #Footer
            footer_y=10
            canvas.drawString(25, footer_y, file_path)
            canvas.drawString(doc.width , footer_y, "page %d" % doc.page)
            canvas.restoreState()

        #Table score

        pools = Pool.objects.filter(tournament=self);
        templates=[]
        for pool in pools:
            Story.append(Spacer(1, 48))
            Story.append(self.pdf_pool(pool))
            Story.append(NextPageTemplate(str(pool)))
            Story.append(PageBreak())
            templates.append(PageTemplate(id=str(pool),frames=frameTable,onPage=footer_header))

        doc.addPageTemplates(templates)

        doc.build(Story)
コード例 #8
0
ファイル: main.py プロジェクト: ahmadhassanch/editable_table
def main1():
    file = "base3.html"
    # file = "fe_data0.html"
    f = open(file, "r")
    st = f.read()
    elements = []
    makePDF(st, elements)

    doc = SimpleDocTemplate("test.pdf", pagesize=letter)
    frame = Frame(15, 15, 580, 760, id='col1', showBoundary=1)  # 610x790
    Page = PageTemplate(id='col1', frames=[frame])
    doc.addPageTemplates([Page])
    doc.build(elements)
コード例 #9
0
ファイル: printview.py プロジェクト: schnittstabil/mediatum
 def build(self, printfile, style=1):
     template = SimpleDocTemplate(printfile, showBoundary=0)
     tFirst = PageTemplate(id='First',
                           frames=self.getStyle(1, style),
                           onPage=self.myPages,
                           pagesize=defaultPageSize)
     tNext = PageTemplate(id='Later',
                          frames=self.getStyle(2, style),
                          onPage=self.myPages,
                          pagesize=defaultPageSize)
     template.addPageTemplates([tFirst, tNext])
     template.allowSplitting = 1
     BaseDocTemplate.build(template, self.data)
コード例 #10
0
def gen_pdf(request, template=None):
    h_orientacion = 'Titulo_' + template.header_id.orientacion
    f_orientacion = 'Footer_' + template.footer_id.orientacion
    response, buff = init_pdf_doc()
    doc = SimpleDocTemplate(
        buff,
        pagesize=letter,
        rightMargin=40,
        leftMargin=40,
        topMargin=60,
        bottomMargin=18,
    )
    t = []
    #cambiar el path a relativo - se usa full path para desarrollo
    #path relativo
    # archivo_imagen2 = settings.MEDIA_ROOT+'/header/logo/login.png'
    #full path
    header_tmp = template.header_id.header
    content1 = str(header_tmp).replace('\n', '<br />\n')
    print(content1)
    header = Paragraph(content1, get_styles_customs(h_orientacion))
    logo = settings.MEDIA_ROOT + '/' + str(template.header_id.logo)
    imagen = Image(logo, width=80, height=60, hAlign='RIGHT')
    t.append(imagen)
    t.append(header)
    t.append(Paragraph('Rp./', get_styles_customs('Titulo2_I')))
    legend = request.POST.get('descripcion')
    content = str(legend).replace('\n', '<br />\n')

    t.append(
        Paragraph(content,
                  get_styles_customs('Normal_' + template.orientacion)))

    frame = Frame(doc.leftMargin,
                  doc.bottomMargin,
                  doc.width,
                  doc.height,
                  id='normal')
    header_content = Paragraph(template.footer_id.footer,
                               get_styles_customs(f_orientacion))
    template = PageTemplate(id='test',
                            frames=frame,
                            onPage=partial(header_footer,
                                           content=header_content))
    doc.addPageTemplates([template])

    doc.build(t)
    response.write(buff.getvalue())
    buff.close()

    return response
コード例 #11
0
ファイル: pdf.py プロジェクト: Flogerbe/coach
  def render(self, stream=None):
    '''
    Render the pdf with current lines & style
    '''
    # Use a buffer when no stream is given
    if stream is None:
      stream = StringIO()

    # Build lines
    self.add_days()
    self.build_lines()

    # Canvas is landscape oriented
    pdf = SimpleDocTemplate(stream, pagesize=landscape(letter))

    # Table is in a frame
    table = Table(self.lines, [1.5* inch ] * 7, self.row_heights, style=self.tableStyle, repeatRows=1)
    table.wrap(0,0) # important hacky way to span on full width
    tableFrame = Frame(inch / 2, inch / 2, 10*inch, 7*inch)

    # RunReport logo
    logo = Image('./medias/img/logo_ligne.png')
    logo.drawHeight = 2.2*inch*logo.drawHeight / logo.drawWidth
    logo.drawWidth = 2.2*inch

    # Plan infos are in a frame, in top left corner
    context = {
      'site' : self.site,
      'plan' : self.plan,
    }
    title = Paragraph(render_to_string('plan/export.pdf.title.html', context), self.titleStyle)

    # Add table elements
    pdf.addPageTemplates([
      PageTemplate(id='table', frames=[tableFrame]),
    ])
    story = [
      logo,
      title,
      Spacer(1, 0.4*inch), # make room for header
      table, # the plan
    ]
    pdf.build(story)

    if isinstance(stream, StringIO):
      output = stream.getvalue()
      stream.close()
      return output

    return None
コード例 #12
0
ファイル: help.py プロジェクト: hibozzy/mediatum
    def build(self, style=1):
        self.h1 = self.styleSheet['Heading1']
        self.h1.fontName = 'Helvetica'
        self.bv = self.styleSheet['BodyText']
        self.bv.fontName = 'Helvetica'
        self.bv.fontSize = 7
        self.bv.spaceBefore = 0
        self.bv.spaceAfter = 0

        self.header = self.styleSheet['Heading3']
        self.header.fontName = 'Helvetica'

        self.data.append(Paragraph(translation.t(self.language, 'mediatumhelptitle'), self.h1))
        self.data.append(Paragraph(self.path, self.bv))

        self.data.append((FrameBreak()))

        # format content
        self.content = self.content.replace("\n", "")
        repl = {'p': 'BodyText', 'h1': 'Heading1', 'h2': 'Heading2', 'h3': 'Heading3', 'h4': 'Heading4', 'h5': 'Heading5', 'li': 'Bullet'}
        curstyle = "BodyText"
        for item in re.split(r'<(p|h[1-5]|li)>|<(/p|/h[1-5]|/li)>', self.content):
            if item and item != "":
                if item in repl.keys():
                    curstyle = repl[item]
                elif item[0] == "/" and item[1:] in repl.keys():
                    curstyle = ""
                else:
                    if item.strip != "" and curstyle != "":
                        print 'add', item, "-->", curstyle
                        if curstyle == "Bullet":
                            item = "- " + item
                            print "bullet", item
                        self.data.append(Paragraph(item, self.styleSheet[curstyle]))

        template = SimpleDocTemplate(config.get("paths.tempdir", "") + "help.pdf", showBoundary=0)
        tFirst = PageTemplate(id='First', onPage=self.myPages, pagesize=defaultPageSize)
        tNext = PageTemplate(id='Later', onPage=self.myPages, pagesize=defaultPageSize)

        template.addPageTemplates([tFirst, tNext])
        template.allowSplitting = 1
        BaseDocTemplate.build(template, self.data)

        template.canv.setAuthor(translation.t(self.language, "main_title"))
        template.canv.setTitle("%s \n'%s' - %s: %s" % (translation.t(self.language, "edit_stats_header"),
                                                       'sdfsdfsdf', translation.t(self.language, "edit_stats_period_header"), '2003'))
        return template.canv._doc.GetPDFData(template.canv)
コード例 #13
0
    def create_document(self, destination_file, units):
        margin = 10 * units

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

        header_left = Frame(margin + 10, 260 * units, 45 * units, 30 * units)
        header_right = Frame(60 * units, 260 * units, 150 * units, 30 * units)
        body = Frame(margin, 45 * units, doc.width, 230 * units)
        footer = Frame(margin, 20 * units, doc.width, 15 * units)

        fp = PageTemplate(id=self.FIRST_PAGE_TEMPLATE_ID, frames=[header_left, header_right, body, footer])
        sp = PageTemplate(id=self.LATER_PAGES_TEMPLATE_ID, frames=[header_left, header_right, body, footer])

        doc.addPageTemplates([fp, sp])

        return doc
コード例 #14
0
def alternate_orientation():
    """
        Criando paginas com em formaro landscape e quebra de pagina com
        PageBreak
    """

    doc = SimpleDocTemplate('gen/cap03/alternate_orientation.pdf',
                            pagesize=A4,
                            rightMargin=1 * cm,
                            leftMargin=1.5 * cm,
                            topMargin=2.5 * cm,
                            bottomMargim=1.5 * cm)

    styles = getSampleStyleSheet()
    normal = styles['Normal']

    # Aqui criamos um frame e um template para cada tipo de orientação
    margin = 0.5 * cm
    frame = Frame(margin, margin, doc.width, doc.height, id='frame')
    frame_landscape = Frame(margin, margin, doc.height, doc.width, id='frame')
    portrait_template = PageTemplate(id='portrait',
                                     frames=[frame],
                                     pagesize=A4)
    landscape_template = PageTemplate(id='landscape',
                                      frames=[frame_landscape],
                                      pagesize=landscape(A4))

    doc.addPageTemplates([portrait_template, landscape_template])

    story = []
    story.append(Paragraph('This is a page in portrait orientation', normal))

    # alterar a orientação da página para landscape
    story.append(NextPageTemplate('landscape'))
    story.append(PageBreak())
    story.append(Spacer(cm, 0.5 * cm))
    story.append(Paragraph('This is a page in landscape orientation', normal))

    # altera a orientação de volta para retrato
    story.append(NextPageTemplate('portrait'))
    story.append(PageBreak())
    story.append(Paragraph('Now back to portrait again', normal))

    doc.build(story)
コード例 #15
0
def create_pdf(fname, arr, path):   
    filename =  path +fname.split('/')[6]+".pdf"
    width,height = landscape(A4) 
    print("width = %d, height = %d\n" % (width, height))  
    doc = SimpleDocTemplate(filename, pagesize=(height, width))  
    frame1 = Frame(0, 0, height, width, 0, 0, 0, 0, id="normal1")  
    doc.addPageTemplates([PageTemplate(id="Later", frames=frame1)])  
    Story=[]
    for pic in arr:
        # with imagss(filename=pic) as original:
        #      with original.convert('pdf') as converted:  
        #          Story.append(converted) 
        im = Image(pic, height, width)
        Story.append(im)  
        Story.append(PageBreak())  
        print (pic)  
    doc.build(Story)  
    print ("%s created" % filename) 
    return filename
コード例 #16
0
def preview_template_asPDF(request, template=None):
    h_orientacion = 'Titulo_' + template.header_id.orientacion
    print('Orientacion Header', h_orientacion)
    f_orientacion = 'Footer_' + template.footer_id.orientacion
    print('Orientacion Footer', f_orientacion)

    response, buff = init_pdf_doc()
    doc = SimpleDocTemplate(
        buff,
        pagesize=letter,
        rightMargin=40,
        leftMargin=40,
        topMargin=60,
        bottomMargin=18,
    )
    t = []
    header_tmp = template.header_id.header
    content1 = str(header_tmp).replace('\n', '<br />\n')
    print(content1)
    header = Paragraph(content1, get_styles_customs(h_orientacion))
    logo = settings.MEDIA_ROOT + '/' + str(template.header_id.logo)
    imagen = Image(logo, width=50, height=50, hAlign='RIGHT')
    t.append(imagen)
    t.append(header)
    t.append(Paragraph('Rp./', get_styles_customs('Titulo2_I')))
    frame = Frame(doc.leftMargin,
                  doc.bottomMargin,
                  doc.width,
                  doc.height,
                  id='normal')
    header_content = Paragraph(template.footer_id.footer,
                               get_styles_customs(f_orientacion))
    template = PageTemplate(id='test',
                            frames=frame,
                            onPage=partial(header_footer,
                                           content=header_content))
    doc.addPageTemplates([template])

    doc.build(t)
    response.write(buff.getvalue())
    buff.close()
    return response
コード例 #17
0
ファイル: pdfgen.py プロジェクト: ocomets/web-scraper
def pdfgen(relevant_extracts, sector, keywords):
    today = datetime.datetime.today()
    today.replace(second=0, microsecond=0)

    outputdir = join('..', 'output')
    if not exists(outputdir):
        mkdir(outputdir)
    chdir(outputdir)

    doc = SimpleDocTemplate('%s_%s.pdf' %
                            (sector, today.strftime("%Y-%m-%d_%H.%M")))
    template = PageTemplate(
        'normal', [Frame(2.5 * cm, 2.5 * cm, 15 * cm, 25 * cm, id='F1')])
    doc.addPageTemplates(template)

    Story = [Spacer(1, 0.5 * inch)]
    styleSheet = getSampleStyleSheet()
    style = styleSheet['BodyText']
    title = Paragraph(
        '<para align=center><b>%s Industry Earnings Call Transcripts Report</b></para>'
        % sector, style)
    Story.append(title)
    subtitle = Paragraph(
        '<para align=center>Keywords: %s</para>' % ", ".join(keywords), style)
    Story.append(subtitle)
    Story.append(Spacer(1, 0.5 * inch))

    for extract in relevant_extracts:
        Story.append(Paragraph("From %s" % extract["title"], h1))
        Story.append(
            Paragraph(
                "Published on %s at %s" % (extract["date"], extract["time"]),
                h1))
        text = Preformatted(extract["bodyContent"].encode('utf8'),
                            style,
                            maxLineLength=100)
        Story.append(text)
        Story.append(Spacer(1, 0.2 * inch))

    doc.build(Story)
コード例 #18
0
def create_pdf(filename, path, page, cliptype, imageformat):
    """
    """

    if cliptype == ClipType.ALL:
        width, height = portrait(A4)
    else:
        width, height = landscape(A4)

    print("width = %d, height = %d\n" % (width, height))

    doc = SimpleDocTemplate(filename, pagesize=(height, width))
    frame1 = Frame(0, 0, height, width, 0, 0, 0, 0, id="normal1")
    doc.addPageTemplates([PageTemplate(id="Later", frames=frame1)])
    Story = []

    for page in range(page):
        print 'create_pdf', page
        image1 = os.path.join(path,
                              '{0}.{1}.{2}'.format(page, '1', imageformat))
        image2 = os.path.join(path,
                              '{0}.{1}.{2}'.format(page, '2', imageformat))
        image3 = os.path.join(path,
                              '{0}.{1}.{2}'.format(page, '3', imageformat))
        if os.path.exists(image1) and os.stat(image1).st_size:
            Story.append(Image(image1, height, width))
            Story.append(PageBreak())
        if os.path.exists(image2) and os.stat(image2).st_size:
            Story.append(Image(image2, height, width))
            Story.append(PageBreak())
        if os.path.exists(image3) and os.stat(image3).st_size:
            Story.append(Image(image3, height, width))
            Story.append(PageBreak())

    doc.build(Story)
    print "%s created" % filename
コード例 #19
0
ym = doc.bottomMargin
#debug info
print(
    f'chunk size: {xc}x{yc}\ngrid: {xcs}x{ycs}\nmargins: L({doc.leftMargin}) R({doc.rightMargin}) T({doc.topMargin}) B({doc.bottomMargin})'
)


def foot(canvas, doc):
    canvas.saveState()
    canvas.setFont('Times-Roman', 9)
    canvas.drawString(0.5 * inch, 0.2 * inch, "Strona %d" % doc.page)
    canvas.restoreState()


#first page template
doc.addPageTemplates([repo_page_template()])

#debug piece
P0 = Paragraph(
    '''
               <b>A pa<font color=red>r</font>a<i>graph</i></b>
               <super><font color=yellow>1</font></super>''',
    styles["BodyText"])
P = KeepInFrame(20 * xc / 5, 9 * yc / 10, [
    Paragraph(
        '''
    <para align=center spaceb=3>The <b>ReportLab Left
    <font color=red>Logo</font></b>
    Image</para>''', styles["BodyText"])
])
I = Image('.\\logo.jpg')
コード例 #20
0
from reportlab.lib.units import inch, cm
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, LongTable, TableStyle
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.platypus import Paragraph, Frame, Spacer
from reportlab.platypus import BaseDocTemplate, Frame, Paragraph, PageBreak, PageTemplate, NextPageTemplate, KeepTogether, FrameBreak

styles=getSampleStyleSheet()
data = "lorem ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore et".split()

doc = SimpleDocTemplate("test11.pdf", pagesize = A4, leftMargin = 0, rightMargin = 0, topMargin = 0, showBoundary=1)

Elements=[]
p1 = Paragraph("I am column 1! " * 300, styles['Normal'])
p2 = Paragraph("I am column 2! " * 800, styles['Normal'])

frame1 = Frame(1.45*cm, doc.bottomMargin + 1*cm, doc.width/2-1.45*2*cm, doc.height-7*cm, id='col1')
frame2 = Frame(doc.width/2 + 1.45*cm, doc.bottomMargin + 1*cm, doc.width/2-1.45*2*cm, doc.height-7*cm, id='col2')

doc.addPageTemplates([
    PageTemplate(id = 'TwoCol', frames = [frame1,frame2], ),
])

Elements.append(NextPageTemplate('TwoCol'))
Elements.append(KeepTogether(p1))
Elements.append(FrameBreak())   
Elements.append(KeepTogether(p2))

doc.build(Elements)
コード例 #21
0
# The simple doc template sets up our document. You can specify page size, margins etc
pdf = SimpleDocTemplate('Report Preview.pdf',
                        topMargin=57,
                        bottomMargin=35,
                        author='Your Name',
                        showBoundary=False)
# Create Frame for holding flowables. Frame object is used by the platypus modules. Args: x,y (bottom left),
frame = Frame(pdf.leftMargin,
              pdf.bottomMargin,
              pdf.width,
              pdf.height,
              showBoundary=False)
# Add Frame to the page template and call on template to draw static objects
template = PageTemplate(frames=[frame], onPage=draw_static_elements)
# Add the template to the simple doc
pdf.addPageTemplates(template)
# Get the preset paragraph/text styles
styles = getSampleStyleSheet()
# TrueType (.ttf) fonts are those used on Mac and PC systems, as opposed to Type1 fonts developed by Adobe in their PDFs.
# Must use a font with .ttc, .ttf, .otf format. ReportLab searches through your computer for them. 'Font Suitcase' not usable unfortunately
pdfmetrics.registerFont(TTFont('Palatino Linotype', 'Palatino Linotype.ttf'))
# Create custom paragraph style
styles.add(
    ParagraphStyle(name='MainTitle',
                   fontName='Palatino Linotype',
                   underlineWidth=1,
                   fontSize=16,
                   alignment=TA_CENTER))
styles.add(
    ParagraphStyle(name='EquityHeading',
                   fontName='Palatino Linotype',
コード例 #22
0
ファイル: prints.py プロジェクト: egegunes/hastatakip
    def get(self, request, *args, **kwargs):
        istek = self.get_object()

        muayene_tarihi = str(istek.tarih)
        ad = str(istek.hasta.ad)
        soyad = str(istek.hasta.soyad)
        pk = str(istek.pk)

        title = unidecode("%s-%s-istek-%s-%s" % (ad, soyad, pk, muayene_tarihi))
        filename = title + ".pdf"

        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'filename=%s' % filename

        buff = BytesIO()

        doc = SimpleDocTemplate(buff,
                                pagesize=letter,
                                title=title,
                                author="Dr. Ziya T. Güneş",
                                rightMargin=inch/4,
                                leftMargin=inch/4,
                                topMargin=inch/2,
                                bottomMargin=inch/4,
                                showBoundary=0)

        frame1 = Frame(doc.leftMargin,
                       doc.bottomMargin,
                       doc.width,
                       doc.height / 8,
                       id="footer")
        frame2 = Frame(doc.leftMargin,
                       doc.bottomMargin + doc.height / 8 + 6,
                       doc.width,
                       doc.height * 6 / 8,
                       id="body")
        frame3 = Frame(doc.leftMargin,
                       doc.bottomMargin + doc.height * 7 / 8 + 12,
                       doc.width * 3 / 4 - 6,
                       doc.height / 8,
                       id="header_right")
        frame4 = Frame(doc.leftMargin + doc.width * 3 / 4 + 6,
                       doc.bottomMargin + doc.height * 7 / 8 + 12,
                       doc.width / 4 - 6,
                       doc.height / 8,
                       id="header_left")

        receteTemplate = PageTemplate(frames=[frame1, frame2, frame3, frame4])
        doc.addPageTemplates(receteTemplate)

        self.register_font()
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name="footer",
                                  fontName="Vera",
                                  fontSize=10,
                                  alignment=2,
                                  leading=20))
        styles.add(ParagraphStyle(name="heading",
                                  parent=self.base_style,
                                  fontSize=16,
                                  alignment=1,
                                  spaceAfter=30))
        styles.add(ParagraphStyle(name="body",
                                  parent=self.base_style,
                                  fontSize=10,
                                  alignment=0,
                                  leftIndent=30,
                                  spaceAfter=0,
                                  leading=20))
        styles.add(ParagraphStyle(name="header_left",
                                  parent=self.base_style,
                                  fontSize=12,
                                  alignment=0))
        styles.add(ParagraphStyle(name="header_right",
                                  parent=self.base_style,
                                  fontSize=12,
                                  alignment=2))

        story = []

        ad = Paragraph("Dr. Ziya T. GÜNEŞ", styles['footer'])
        tel = Paragraph("0(232) 422 00 56", styles['footer'])
        mail = Paragraph("*****@*****.**", styles['footer'])
        adres = Paragraph("Işılay Saygın Sokak No:17 Kat:2 Alsancak/İzmir", styles['footer'])

        story.append(ad)
        story.append(tel)
        story.append(mail)
        story.append(adres)

        story.append(FrameBreak())

        heading = Paragraph("TETKİK İSTEM", styles['heading'])

        story.append(heading)

        for name in istek.get_true_fields():
            par1 = Paragraph("* %s" % (name), styles['body'])
            story.append(par1)

        story.append(FrameBreak())

        hasta = str(istek.hasta)
        hasta_paragraph = Paragraph(hasta, styles['header_left'])

        story.append(hasta_paragraph)

        story.append(FrameBreak())

        tarih_paragraph = Paragraph(muayene_tarihi, styles['header_right'])

        story.append(tarih_paragraph)

        doc.build(story)

        response.write(buff.getvalue())
        buff.close()

        return response
コード例 #23
0
ファイル: statsaccess.py プロジェクト: agromsl/mediatum
    def build(self, style=1):
        self.h1 = self.styleSheet['Heading1']
        self.h1.fontName = 'Helvetica'
        self.bv = self.styleSheet['BodyText']
        self.bv.fontName = 'Helvetica'
        self.bv.fontSize = 7
        self.bv.spaceBefore = 0
        self.bv.spaceAfter = 0

        self.chartheader = self.styleSheet['Heading3']
        self.chartheader.fontName = 'Helvetica'

        self.formatRight = self.styleSheet['Normal']
        self.bv.formatRight = 'Helvetica'
        self.formatRight.alignment = 2

        nameColl = self.collection.getName()

        while True:
            # page 1
            p = Paragraph("%s \n'%s'" % (t(self.language, "edit_stats_header"), nameColl), self.h1)
            p.wrap(defaultPageSize[0], defaultPageSize[1])

            if p.getActualLineWidths0()[0] < 19 * cm:
                break
            else:
                nameColl = nameColl[0:-4] + "..."

        self.data.append(p)

        self.data.append(Paragraph("%s: %s" % (t(self.language, "edit_stats_period_header"), self.period), self.chartheader))
        self.data.append(Paragraph(t(self.language, "edit_stats_pages_of") % ("1", "4"), self.formatRight))

        self.data.append((FrameBreak()))
        # top 10
        self.data += self.getStatTop("data", namecut=60)

        # page 2
        self.data.append(Paragraph("%s \n'%s' %s - " % (t(self.language, "edit_stats_header"), self.collection.getName(),
                                                        self.period) + t(self.language, "edit_stats_pages_of") % ("2", "4"), self.bv))
        self.data.append((FrameBreak()))
        # country
        self.data += self.getStatCountry("data")
        self.data.append(PageBreak())

        # page 3
        self.data.append(Paragraph("%s \n'%s' %s - " % (t(self.language, "edit_stats_header"), self.collection.getName(),
                                                        self.period) + t(self.language, "edit_stats_pages_of") % ("3", "4"), self.bv))
        self.data.append((FrameBreak()))
        # date
        self.data += self.getStatDate("data")
        self.data.append(PageBreak())

        # page 4
        self.data.append(Paragraph("%s \n'%s' %s - " % (t(self.language, "edit_stats_header"), self.collection.getName(),
                                                        self.period) + t(self.language, "edit_stats_pages_of") % ("4", "4"), self.bv))
        self.data.append((FrameBreak()))
        # weekday
        self.data += self.getStatDay("data")
        # time
        self.data += self.getStatTime("data")

        template = SimpleDocTemplate(config.get("paths.tempdir", "") + "statsaccess.pdf", showBoundary=0)
        tFirst = PageTemplate(id='First', onPage=self.myPages, pagesize=defaultPageSize)
        tNext = PageTemplate(id='Later', onPage=self.myPages, pagesize=defaultPageSize)

        template.addPageTemplates([tFirst, tNext])
        template.allowSplitting = 1
        BaseDocTemplate.build(template, self.data)

        template.canv.setAuthor(t(self.language, "main_title"))
        template.canv.setTitle("%s \n'%s' - %s: %s" % (t(self.language,
                                                         "edit_stats_header"),
                                                       self.collection.getName(),
                                                       t(self.language,
                                                         "edit_stats_period_header"),
                                                       self.period))
        return template.canv._doc.GetPDFData(template.canv)
コード例 #24
0
# SET UP THE FRAME FOR THE TITLE
frame_title = Frame(doc.leftMargin, (doc.bottomMargin) + (doc.height)-(50*mm), (doc.width), (doc.height-(260*mm)), id = 'title')

# SET UP THE FRAME FOR MAIN TABLE
frame_table = Frame(doc.leftMargin, (doc.bottomMargin) + (doc.height)-(95*mm), (doc.width), (doc.height-(235*mm)), id = 'table')

# SET UP THE FRAME FOR HEADING 1 - GENERAL
frame_heading1 = Frame(doc.leftMargin, (doc.bottomMargin) + (doc.height)-(175*mm), (doc.width), (doc.height-(200*mm)), id = 'heading1')

# SET UP THE FRAME FOR HEADING 2 - SITE VISITS
frame_heading2 = Frame(doc.leftMargin, (doc.bottomMargin) + (doc.height)-(255*mm), (doc.width), (doc.height-(195*mm)), id = 'heading2')


# ADD THE TEMPLATE FRAMES FOR THE HEADER AND FOOTER
doc.addPageTemplates([PageTemplate(id = 'HEADFOOTPAGE1', pagesize = PAGESIZE, frames = [frame_1, frame_2, frame_3, frame_4, frame_title, frame_table, frame_heading1, frame_heading2])])





# SET UP THE FRAME FOR HEADING 3 - AUDIO VISUAL
frame_heading3 = Frame(doc.leftMargin, (doc.bottomMargin) + (doc.height)-(200*mm), (doc.width), (doc.height)-(100*mm), id = 'heading3')


# ADD THE FRAMES TO THE TEMPLACE - ON THE SECOND PAGE
doc.addPageTemplates([PageTemplate(id = 'HEADFOOTPAGE2', pagesize = PAGESIZE, frames = [frame_3, frame_4, frame_heading3])])



# ADD THE ADDRESS DETAILS TO THE STORY - IN THE FIRST FRAME
コード例 #25
0
ファイル: prints.py プロジェクト: egegunes/hastatakip
    def get(self, request, *args, **kwargs):
        rapor = self.get_object()

        ad = str(rapor.hasta.ad)
        soyad = str(rapor.hasta.soyad)
        pk = str(rapor.id)
        muayene_tarihi = str(rapor.tarih)

        title = unidecode("%s-%s-rapor-%s-%s" % (ad, soyad, pk, muayene_tarihi))
        filename = title + ".pdf"

        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'filename=%s' % filename

        buff = BytesIO()

        doc = SimpleDocTemplate(buff,
                                pagesize=letter,
                                title=title,
                                author="Dr. Ziya T. Güneş",
                                topMargin=inch/2,
                                bottomMargin=inch/4,
                                leftMargin=inch/4,
                                rightMargin=inch/4)

        frame1 = Frame(doc.leftMargin,
                       doc.bottomMargin,
                       doc.width,
                       doc.height / 8,
                       id="footer")
        frame2 = Frame(doc.leftMargin,
                       doc.bottomMargin + doc.height / 8 + 6,
                       doc.width,
                       doc.height * 6 / 8,
                       id="body")
        frame3 = Frame(doc.leftMargin,
                       doc.bottomMargin + doc.height * 7 / 8 + 6,
                       doc.width,
                       doc.height / 8,
                       id="header")

        receteTemplate = PageTemplate(frames=[frame1, frame2,frame3])
        doc.addPageTemplates(receteTemplate)

        self.register_font()

        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name="centered",
                                  parent=self.base_style,
                                  alignment=1,
                                  fontSize=24,
                                  spaceAfter=30))
        styles.add(ParagraphStyle(name="body",
                                  parent=self.base_style,
                                  fontSize=12,
                                  leading=20))
        styles.add(ParagraphStyle(name="footer",
                                  fontName="Vera",
                                  fontSize=10,
                                  leading=20,
                                  alignment=2))
        styleH = styles['centered']
        styleB = styles['body']
        styleF = styles['footer']

        story = []

        dogum_tarihi = str(rapor.hasta.dogum_tarihi)
        hasta = str(rapor.hasta)
        tani = str(rapor.tani)
        gun = str(rapor.gun)

        heading = "RAPOR"
        body = "%s tarihinde başvuran, %s doğum tarihli %s'ın %s tanısı ile %s gün istirahati uygundur." % (muayene_tarihi, dogum_tarihi, hasta, tani, gun)
        tel = "0(232) 422 00 56"
        mail = "*****@*****.**"
        adres = "Işılay Saygın Sokak No:17 Kat:2 Alsancak/İzmir"

        story.append(Paragraph(tel, styleF))
        story.append(Paragraph(mail, styleF))
        story.append(Paragraph(adres, styleF))

        story.append(FrameBreak())

        story.append(Paragraph(heading, styleH))
        story.append(Paragraph(body, styleB))

        doc.build(story)

        response.write(buff.getvalue())
        buff.close()

        return response
コード例 #26
0
def form_health_passport():
    doc = SimpleDocTemplate("health_passport2.pdf",
                            pagesize=landscape(A4),
                            leftMargin=10 * mm,
                            rightMargin=10 * mm,
                            topMargin=10 * mm,
                            bottomMargin=10 * mm,
                            allowSplitting=1,
                            title="Форма {}".format("Паспорт здоровья"))
    width, height = landscape(A4)
    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "PTAstraSerifBold"
    style.fontSize = 9
    style.leading = 5
    styleBold = deepcopy(style)
    styleBold.fontName = "PTAstraSerifBold"
    styleCenter = deepcopy(style)
    styleCenter.alignment = TA_CENTER
    styleCenterBold = deepcopy(styleBold)
    styleCenterBold.alignment = TA_CENTER
    styleJustified = deepcopy(style)
    styleJustified.alignment = TA_JUSTIFY
    styleJustified.spaceAfter = 5.5 * mm
    styleJustified.fontSize = 12
    styleJustified.leading = 4.5 * mm

    righ_frame = Frame(148.5 * mm,
                       0 * mm,
                       width=148.5 * mm,
                       height=210 * mm,
                       leftPadding=10 * mm,
                       bottomPadding=6,
                       rightPadding=10 * mm,
                       topPadding=6,
                       showBoundary=1)
    left_frame = Frame(0 * mm,
                       0 * mm,
                       width=148.5 * mm,
                       height=210 * mm,
                       leftPadding=10 * mm,
                       bottomPadding=6,
                       rightPadding=10 * mm,
                       topPadding=6,
                       showBoundary=1)
    doc.addPageTemplates(
        PageTemplate(id='TwoCol',
                     frames=[righ_frame, left_frame],
                     pagesize=landscape(A4)))

    space = 5.5 * mm
    objs = [
        Spacer(1, 3 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold">Министерство здравоохранения Российской Федерации</font>',
            styleCenter),
        Spacer(1, 3 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold"><u>{}</u></font>'.format(
                hospital_name), styleCenter),
        Spacer(1, 2 * mm),
        Paragraph(
            '<font face="PTAstraSerifReg"><font size=9>(наименование медицинской организации)</font></font>',
            styleCenter),
        Spacer(1, 3 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold"><u>{}</u></font>'.format(
                organization_address), styleCenter),
        Spacer(1, 5 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold" size=12>Код ОГРН {}</font>'.format(
                hospital_kod_ogrn), styleCenter),
        Spacer(1, 10 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold" size=12>ПАСПОРТ ЗДОРОВЬЯ РАБОТНИКА № <u>{}</u></font>'
            .format(number_health_passport), styleCenter),
        Spacer(1, space),
        Paragraph(
            '<font face="PTAstraSerifReg"size=10><u>{} года</u></font>'.format(
                pytils.dt.ru_strftime(u"%d %B %Y",
                                      inflected=True,
                                      date=datetime.datetime.now())),
            styleCenter),
        Spacer(1, 7),
        Paragraph(
            '<font face="PTAstraSerifReg" size=7>(дата оформления)</font>',
            styleCenter),
        Spacer(1, space),
        Paragraph(
            '<font face="PTAstraSerifReg">1.Фамилия, имя, отчество:  '
            '<u>{}</u> </font>'.format(individual_fio), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">2.Пол: <u>{}</u> <img src="img/FFFFFF-0.png" width="90" />'
            '3.Дата Рождения: <u>{}</u> </font>'.format(
                individual_sex, individual_date_born), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">4.Паспорт: серия <u>{}</u> <img src="img/FFFFFF-0.png" width="20" />'
            'номер: <u>{}</u> </font>'.format(document_passport_serial,
                                              document_passport_number),
            styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">кем выдан: <u>{}</u></font>'.format(
                document_passport_issued), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">5. Адрес регистрации по месту жительства (пребывания):'
            ' <u>{}</u></font>'.format(individual_address), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">6. Номер страхового полиса:'
            ' <u>{}</u></font>'.format(document_polis_number), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">7. Наименование работодателя:'
            ' <u>{}</u></font>'.format(individual_work_organization),
            styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">7.1 Форма собственности и вид экономической деятельности '
            'работодателя по ОКВЭД: <u>{}</u></font>'.format(
                work_organization_okved), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">7.2  Наименование структурного подразделения (цех, участок, отдел):'
            ' <u> {} </u></font>'.format(individual_department),
            styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">8. Профессия (должность) (в настоящее время):'
            ' <u>{}</u></font>'.format(individual_profession), styleJustified),
        FrameBreak(),
        Spacer(1, space),
        Paragraph('<font face="PTAstraSerifReg">12. Заключение:</font>',
                  styleJustified),
    ]
    styleT = deepcopy(style)
    styleT.alignment = TA_CENTER
    styleT.fontSize = 10
    styleT.leading = 4.5 * mm

    opinion = [
        [
            Paragraph(
                '<font face="PTAstraSerifReg">Заключение по результатам предварительного '
                'и периодического медицинского осмотра</font>', styleT),
            Paragraph(
                '<font face="PTAstraSerifReg">Дата получения заключения</font>',
                styleT),
            Paragraph(
                '<font face="PTAstraSerifReg"> Подпись профпатолога</font>',
                styleT)
        ],
    ]

    for i in range(0, 5):
        para = [
            Paragraph(
                '<font face="PTAstraSerifReg" size=11>Профпригоден/\nпрофнепригоден</font>',
                styleT)
        ]
        opinion.append(para)

    tbl = Table(opinion,
                colWidths=(48 * mm, 40 * mm, 40 * mm),
                hAlign='LEFT',
                style=[
                    ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('TOPPADDING', (0, 0), (-1, -1), 1.5 * mm),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm),
                ])

    objs.append(tbl)

    objs.append(Spacer(1, 10 * mm))
    objs.append(
        Paragraph('<font face="PTAstraSerifReg">Для заметок:</font>',
                  styleJustified))

    s = "___________________________________________________________"
    for i in range(0, 6):
        objs.append(Spacer(1, 1 * mm))
        objs.append(
            Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(s),
                      styleJustified))

    objs.append(NextPageTemplate("TwoCol"))
    objs.append(FrameBreak())
    objs.append(Spacer(1, 7 * mm))
    objs.append(
        Paragraph(
            '<font face="PTAstraSerifReg">11. Результаты лабораторных и инструментальных исследований'
            '</font>', styleJustified))

    tbl_result = [[
        Paragraph(
            '<font face="PTAstraSerifReg" size=11>Вид исследования</font>',
            styleT),
        Paragraph(
            '<font face="PTAstraSerifReg" size=11>Даты исследований</font>',
            styleT), '', '', '', ''
    ], ['', '', '', '', '', '']]

    styleTR = deepcopy(styleT)
    styleTR.alignment = TA_LEFT
    styleTR.fontSize = 11
    styleTR.spaceAfter = 12 * mm

    for i in list_result:
        para = [
            Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(i),
                      styleTR)
        ]
        tbl_result.append(para)

    tbl = Table(tbl_result,
                colWidths=(41 * mm, 22 * mm, 17 * mm, 17 * mm, 17 * mm,
                           17 * mm),
                hAlign='LEFT',
                style=[
                    ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('LEFTPADDING ', (0, 2), (0, -1), 0.1 * mm),
                    ('SPAN', (0, 0), (0, 1)),
                    ('SPAN', (1, 0), (-1, 0)),
                ])
    objs.append(tbl)

    objs.append(FrameBreak())
    objs.append(Spacer(1, 7 * mm))
    objs.append(
        Paragraph(
            '<font face="PTAstraSerifReg">9. Условия труда в настоящее время</font>',
            styleJustified))

    tbl_result = [[
        Paragraph(
            '<font face="PTAstraSerifReg" size=10>Наименование производственного фактора, вида работы с '
            'указанием пункта</font>', styleT),
        Paragraph(
            '<font face="PTAstraSerifReg" size=10>Стаж работы с фактором</font>',
            styleT),
    ]]
    for i in range(0, 4):
        para = ['', '']
        tbl_result.append(para)

    row_height = []
    for i in tbl_result:
        row_height.append(8 * mm)

    row_height[0] = None
    tbl = Table(tbl_result,
                colWidths=(75 * mm, 55 * mm),
                rowHeights=row_height,
                hAlign='LEFT',
                style=[
                    ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('LEFTPADDING ', (0, 2), (0, -1), 0.1 * mm),
                    ('SPAN', (1, 1), (1, -1)),
                ])

    objs.append(tbl)

    objs.append(Spacer(1, 5 * mm))

    styleDoc = deepcopy(styleJustified)
    styleDoc.spaceAfter = 1 * mm
    objs.append(
        Paragraph(
            '<font face="PTAstraSerifReg">10. Заключения врачей - специалистов:</font>',
            styleDoc,
        ))
    tbl_result = [[
        Paragraph(
            '<font face="PTAstraSerifReg" size=11>Врач-специалист</font>',
            styleT),
        Paragraph(
            '<font face="PTAstraSerifReg" size=11>Даты исследований</font>',
            styleT), '', '', '', ''
    ], ['', '', '', '', '', '']]

    for i in list_doctor:
        para = [
            Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(i),
                      styleTR)
        ]
        tbl_result.append(para)

    row_height = []
    for i in tbl_result:
        row_height.append(9 * mm)

    row_height[0] = None
    row_height[1] = None
    tbl = Table(tbl_result,
                colWidths=(41 * mm, 22 * mm, 17 * mm, 17 * mm, 17 * mm,
                           17 * mm),
                rowHeights=row_height,
                hAlign='LEFT',
                style=[
                    ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('LEFTPADDING ', (0, 2), (0, -1), 0.1 * mm),
                    ('SPAN', (0, 0), (0, 1)),
                    ('SPAN', (1, 0), (-1, 0)),
                ])
    objs.append(tbl)

    doc.build(objs)
コード例 #27
0
def writeResumePDF(resumeEntry, outputFile):
    doc = SimpleDocTemplate(outputFile, pagesize=letter)
    normalFrame = Frame(doc.leftMargin,
                        doc.rightMargin,
                        doc.width,
                        doc.height,
                        id='normal',)
    page = PageTemplate(frames=[normalFrame])
    doc.addPageTemplates([page, ])

    bulletStyle = ParagraphStyle(name='bulletStyle', leftIndent=0.25*inch)

    Document = []  # list of flowables for doc.build

    #begin with the resume's header data, piece-by-piece
    HeaderData = []
    for column in [resumeEntry.middle_initial(),
                   resumeEntry.email, ]:
        if column != '':
            HeaderData.append([column, []])
    for website in resumeEntry.resume_web_set.all():
        HeaderData.append([website.account, []])

    i = 0
    for column in [resumeEntry.cell,
                   resumeEntry.home,
                   resumeEntry.fax,
                   resumeEntry.address1,
                   resumeEntry.address2,
                   resumeEntry.region, ]:
        if column != '':
            if i == len(HeaderData):
                HeaderData.append(['', []])
            HeaderData[i][1] = column
            i += 1

    citstazip = ''
    if resumeEntry.city != '':
        citstazip += resumeEntry.city
    if resumeEntry.state != '':
        if citstazip != '':
            citstazip += ', '
        citstazip += resumeEntry.state
    if resumeEntry.zipcode != '':
        if citstazip != '':
            citstazip += ' '
        citstazip += resumeEntry.zipcode

    if citstazip != '':
        if i == len(HeaderData):
            HeaderData.append(['', []])
        HeaderData[i][1] = citstazip
        i += 1

    headerStyle = TableStyle([('ALIGN', (0, 0), (0, -1), 'LEFT'),
                              ('ALIGN', (1, 0), (1, -1), 'RIGHT'), ])
    Document.append(Table(HeaderData,
                          colWidths=[doc.width/2, doc.width/2],
                          style=headerStyle))

    #now for the sections, entries, and datums
    outline = resumeEntry.getResumeFields()
    for section in outline.keys():
        Document.append(KeepTogether([Paragraph(section.section.title,
                                                styles['Normal']),
                                      Paragraph(section.section.description,
                                                styles['Normal'])]))
        Document.append(Spacer(height=0.25*inch, width=1))
        for entry in outline[section].keys():
            entryHeader = []
            for item in [entry.entry.title, entry.entry.subtitle]:
                if item != '':
                    entryHeader.append([item, []])
            i = 0
            for item in [entry.date_string(0), entry.cityState()]:
                if i == len(entryHeader):
                    entryHeader.append(['', []])
                entryHeader[i][1] = item
                i += 1
            Document.append(Table(entryHeader,
                                  colWidths=[doc.width/2, doc.width/2],
                                  style=headerStyle))
            for item in [entry.entry.contact, entry.entry.description]:
                if item != '':
                    Document.append(Paragraph(item, bulletStyle))
            if entry.entry.display == 'L':
                for datum in entry.dataset.all():
                    Document.append(Paragraph(datum.text,
                                    bulletStyle))
            else:  # remaining option is display set to 'D' for delimited
                Document.append(Paragraph('\t'+entry.delimited(),
                                          styles['Normal']))
            Document.append(Spacer(height=0.25*inch, width=1))

    doc.build(Document)
    return outputFile
コード例 #28
0
class PDFExporterBase:
    no_input_filename_str = "&lt;Unsaved File&gt;"
    no_input_full_filename_str = "an unsaved file"

    def __init__(self,
                 input_filename,
                 output_filename,
                 title,
                 orient_landscape=False):

        if orient_landscape:
            rightMargin = 62
            leftMargin = 50
            topMargin = 50
            bottomMargin = 50
        else:
            rightMargin = 62
            leftMargin = 50
            topMargin = 50
            bottomMargin = 90

        self.doc = SimpleDocTemplate(
            output_filename,
            pagesize=landscape(A4) if orient_landscape else A4,
            rightMargin=rightMargin,
            leftMargin=leftMargin,
            topMargin=topMargin,
            bottomMargin=bottomMargin)

        self.setup_custom_fonts()

        print(f"Left Margin: {self.leftMargin}")
        print(f"Right Margin: {self.rightMargin}")
        print(f"Top Margin: {self.topMargin}")
        print(f"Bottom Margin: {self.bottomMargin}")
        print(f"Inner Width: {self.inner_width}")
        print(f"Inner Height: {self.inner_height}")
        self.elements = []

        # Create landscape and portrait page templates
        portrait_frame = Frame(self.leftMargin,
                               self.bottomMargin,
                               self.inner_width,
                               self.inner_height,
                               id='portrait_frame ')
        landscape_frame = Frame(self.leftMargin,
                                self.bottomMargin,
                                self.inner_height,
                                self.inner_width,
                                id='landscape_frame ')
        # portrait_frame = Frame(leftMargin, bottomMargin, width, height, id='portrait_frame ')
        # landscape_frame = Frame(leftMargin, bottomMargin, height, width, id='landscape_frame ')
        #
        self.doc.addPageTemplates([
            PageTemplate(id='portrait', frames=portrait_frame),
            PageTemplate(id='landscape',
                         frames=landscape_frame,
                         pagesize=landscape(A4)),
        ])
        # TODO: This was breaking the top header, but I don't know why?
        #  DDF 24 Feb 2020

        # Table for image and text at the top
        if input_filename is None:
            self.filename = self.no_input_filename_str
            self.full_filename = "an unsaved method file"
        else:
            self.filename = pathlib.Path(input_filename).name
            self.full_filename = input_filename

        self.title = title

        self.elements.append(self.make_report_header(title, self.filename))

        self.elements.append(Spacer(1, cm))

    def setup_custom_fonts(self):
        custom_font = "/home/domdf/GunShotMatch/GunShotMatch/GuiV2/GSMatch2_Core/Arvo_modified.ttf"
        pdfmetrics.registerFont(TTFont("Arvo_modified", custom_font))
        # TODO: modify glyph to taste using BirdFont

        self.xbar = "<font name='Arvo_modified'>�</font>"

    def make_report_header(self, title, filename, orient_landscape=False):
        """
		Create report header, containing the title of the report,

		:param title: The title of the report
		:type title: str
		:param filename: The name of the file the report was generated from, without the directory structure
		:type filename: str

		:return:
		:rtype:
		"""

        header = Paragraph(f"<font size='16'>{title}</font>",
                           style=styles["Normal"])

        header_text_style = TableStyle([
            # (x, y)
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('VALIGN', (0, 0), (-1, -1), 'CENTER'),
        ])

        header_style = TableStyle([
            # (x, y)
            ('ALIGN', (0, 0), (0, 0), 'LEFT'),
            ('ALIGN', (-1, -1), (-1, -1), 'RIGHT'),
            ('VALIGN', (0, 0), (-1, -1), 'CENTER'),
            ("LINEBELOW", (0, 0), (-1, -1), 1, colors.black),
            ("LINEABOVE", (0, 0), (-1, -1), 1, colors.black),
        ])

        l_text_table = Table(
            [
                [header],
                [
                    Paragraph(f"<font size='12'>{filename}</font>",
                              style=styles["Normal"])
                ],
            ],
            colWidths=[self.inner_width - inch],
            rowHeights=[cm, cm],
            style=header_text_style,
            hAlign="LEFT",
        )

        with path(GuiV2.icons._256, "logo-v2.png") as logo_path:
            im = Image(str(logo_path), inch, inch)

        return Table(
            [
                [l_text_table, im],
            ],
            colWidths=[self.inner_width - inch, inch],
            rowHeights=[3 * cm],
            style=header_style,
            hAlign="LEFT",
        )

    def build(self):
        self.doc.multiBuild(self.elements,
                            canvasmaker=FooterCanvas,
                            onFirstPage=self.onFirstPage,
                            onLaterPages=self.onLaterPages)

    def make_parameter_table(self,
                             label,
                             data,
                             show_unit=True,
                             col_widths=None):
        """

		:param label:
		:type label:
		:param data:
		:type data:
		:return:
		:rtype:
		"""

        font_size = 9
        row_height = font_size * 2

        category_style = TableStyle([
            # (x, y)
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ("LINEBELOW", (0, 0), (3, 1), 1, colors.black),
        ])

        top_row = [
            Paragraph(f"<font size='11'><b>{label}</b></font>",
                      styles["Normal"])
        ]
        header_row = [
            Paragraph(f"<font size='{font_size}'>Parameter</font>",
                      styles["Normal"]),
            Paragraph(f"<font size='{font_size}'>Value</font>",
                      styles["Normal"]),
        ]
        if show_unit:
            header_row.append(
                Paragraph(
                    f"<font size='{font_size}'>Unit </font><font size='9'>(if applicable)</font>",
                    styles["Normal"]))

        rows = [top_row, header_row]
        for param in data:
            rows.append([
                Paragraph(
                    f"<font size='{font_size}'>{convert_newlines(param[0])}</font>",
                    styles["Normal"]),
                Paragraph(
                    f"<font size='{font_size}'>{convert_newlines(param[1])}</font>",
                    styles["Normal"]),
            ])

            if show_unit:
                rows[-1].append(
                    Paragraph(
                        f"<font size='{font_size}'>{convert_newlines(param[2])}</font>",
                        styles["Normal"]))

        if show_unit:
            if col_widths:
                col_widths = col_widths[:3]
            else:
                col_widths = [
                    self.inner_width * (3.5 / 7), self.inner_width * (1.5 / 7),
                    self.inner_width * (2 / 7)
                ]
        else:
            if col_widths:
                col_widths = col_widths[:2]
            else:
                col_widths = [
                    self.inner_width * (3 / 7), self.inner_width * (4 / 7)
                ]

        return Table(
            rows,
            colWidths=col_widths,
            # rowHeights=[0.8 * cm] + ([row_height] * (len(rows) - 1)),
            rowHeights=[0.8 * cm] + ([None] * (len(rows) - 1)),
            style=category_style,
            hAlign="LEFT",
            repeatRows=2)

    def draw_footer(self, canvas, doc):

        canvas.setStrokeColorRGB(0, 0, 0)
        canvas.setLineWidth(0.5)
        canvas.setFont('Times-Roman', 10)

        username = getpass.getuser()
        device = socket.gethostname()
        creation_time = datetime.datetime.now().strftime("%H:%M:%S %d/%m/%Y")

        footer_string = f"Generated from {self.full_filename} by {username}@{device} on {creation_time}"
        # split_len = 100
        split_len = self.inner_width / 4.6
        print("Making Footer!")
        generated_by_height = canvas.footer_height + (cm * 0.5)

        if len(footer_string) > split_len:
            wrap_text = textwrap.wrap(footer_string, width=split_len)[::-1]
            for idx, line in enumerate(wrap_text):
                canvas.drawString(doc.leftMargin,
                                  generated_by_height + (idx * 0.5 * cm), line)
            canvas.line(
                x1=doc.leftMargin,
                y1=generated_by_height + (len(wrap_text) * 0.5 * cm),
                x2=doc.pagesize[0] - 50,
                y2=generated_by_height + (len(wrap_text) * 0.5 * cm),
            )

        elif len(footer_string) < self.inner_width / 6:
            canvas.drawString(doc.leftMargin, canvas.footer_height,
                              footer_string)
            canvas.line(
                x1=doc.leftMargin,
                y1=canvas.footer_height + (0.5 * cm),
                x2=doc.pagesize[0] - 50,
                y2=canvas.footer_height + (0.5 * cm),
            )

        else:
            canvas.drawString(doc.leftMargin, generated_by_height,
                              footer_string)
            canvas.line(
                x1=doc.leftMargin,
                y1=generated_by_height + (0.5 * cm),
                x2=doc.pagesize[0] - 50,
                y2=generated_by_height + (0.5 * cm),
            )

    def onFirstPage(self, canvas, doc):

        canvas.saveState()

        self.draw_footer(canvas, doc)

        canvas.restoreState()

    def draw_later_header(self, canvas, doc):
        header_string = f"{self.title} - {self.filename}".replace(
            "&lt;", "<").replace("&gt;", ">")

        canvas.setStrokeColorRGB(0, 0, 0)
        canvas.setLineWidth(0.5)
        canvas.setFont(_baseFontName, 10)
        print(
            f"Later Header Height: {self.bottomMargin + self.inner_height + 5}"
        )
        canvas.drawString(self.leftMargin + 5,
                          self.inner_height + self.bottomMargin + 5,
                          header_string)

    def onLaterPages(self, canvas, doc):

        canvas.saveState()

        self.draw_footer(canvas, doc)
        self.draw_later_header(canvas, doc)

        canvas.restoreState()

    @property
    def page_width(self):
        return self.doc.pagesize[0]

    @property
    def page_height(self):
        return self.doc.pagesize[1]

    @property
    def inner_height(self):
        return self.page_height - self.topMargin - self.bottomMargin

    @property
    def inner_width(self):
        return self.page_width - self.leftMargin - self.rightMargin

    @property
    def leftMargin(self):
        return self.doc.leftMargin

    @property
    def rightMargin(self):
        return self.doc.rightMargin

    @property
    def topMargin(self):
        return self.doc.topMargin

    @property
    def bottomMargin(self):
        return self.doc.bottomMargin

    @staticmethod
    def convert_spaces(string, padding=0):
        string = string.rjust(padding)
        return string.replace(" ", "&nbsp;")
コード例 #29
0
    def build(self):
        if isfile(self.filename):
            return

        if not isdir(dirname(self.filename)):
            os.makedirs(dirname(self.filename))

        # If you ever need to add or remove content from the PDF, use these
        # frames bellow as a starting point. You will need to reposition
        # everything by hand until you get the desired result. Remove
        # `showBoundary=1` when you're done.

    # frame1 = Frame(inch, inch * 8.75, inch * 6.5, inch * 1.25, showBoundary=1)
    # frame2 = Frame(inch, inch * 5.25, inch * 3.5, inch * 3.5, showBoundary=1)
    # frame3 = Frame(inch * 4.5, inch * 7, inch * 3, inch * 1.7, showBoundary=1)
    # frame4 = Frame(inch, inch, inch * 6.5, inch * 4.25, showBoundary=1)

    # Every frame is used to display some of the content. Once a frame is
    # full, the content is sent to the next frame. Some trickery are
    # used to ensure that content is display to the next frame even if
    # there is place left (see `spaceBefore=999` down bellow).
        frame1 = Frame(inch, inch * 8.75, inch * 6.5, inch * 1.25)
        frame2 = Frame(inch * 0.7, inch * 5.4, inch * 3.5, inch * 3.5)
        frame3 = Frame(inch * 4.2, inch * 5.6, inch * 3.3, inch * 3)
        frame4 = Frame(inch, inch, inch * 6.5, inch * 4.4)
        frame5 = Frame(inch, inch, inch * 6.5, inch * 3.4)
        frames = [frame1, frame2, frame3, frame4, frame5]

        # Creating the document to the proper format
        doc = SimpleDocTemplate(self.filename, pagesize=letter)

        # Added a single page template with our frames
        doc.addPageTemplates([PageTemplate(frames=frames)])

        # Creating the QR code drawing
        qrw = QrCodeWidget(self.qrcode)
        b = qrw.getBounds()
        w = b[2] - b[0]
        h = b[3] - b[1]
        d = Drawing(240, 240, transform=[240 / w, 0, 0, 240 / h, 0, 0])
        d.add(qrw)

        if self.ticket.seat_num:
            ticket_type = 'BYOC'
            ticket_seat = self.ticket.seat_num
        else:
            ticket_type = 'Console'
            ticket_seat = '-'

        # Creating all the needed paragraph with their corresponding style
        name = Paragraph('Nom: {}'.format(self.fullname), style_n1)
        username = Paragraph('Pseudonyme: {}'.format(self.username), style_n1)
        ttype = Paragraph('Type: {}'.format(ticket_type), style_n1)
        seat = Paragraph('Siège: {}'.format(ticket_seat), style_n1)

        title = Paragraph('Billet LAN Montmorency 2015', style_h1)
        info = Paragraph(
            """De 10h samedi le 14 novembre jusqu'à 16h dimanche
            le 15 novembre""", style_h2)
        warning = Paragraph(
            """Attention! Vous devrez présenter votre carte
            étudiante lors de votre enregistrement, sans quoi vous devrez
            payer la différence du billet en argent comptant ou l'accès au
            site vous sera refusé.""", style_n2)
        note = Paragraph(
            """Veuillez présenter ce billet à l'acceuil lors de
            votre arrivée au LAN. Notez que vous devrez présenter une pièce
            d’identité avec photo lors de votre enregistrement. Il est
            recommandé de sauvegarder ce PDF sur un appareil mobile, mais il
            est aussi possible de l'imprimer.""", style_n3)

        # Creating the story in the right order
        story = []
        story.append(title)
        story.append(info)
        story.append(d)
        story.append(name)
        story.append(username)
        story.append(ttype)
        story.append(seat)
        if self.ticket.discount_amount:
            story.append(warning)
        story.append(note)

        # Build and save the document
        doc.build(story)
コード例 #30
0
ファイル: json_to_pdf.py プロジェクト: Nerevarsoul/stuff
doc.addPageTemplates(
    [
        PageTemplate(
            id='FourCol',
            frames=[
                Frame(
                    30,
                    doc.bottomMargin + 540,
                    90,
                    35,
                    id='header',
                    showBoundary=0
                ),
                Frame(
                    30,
                    doc.bottomMargin + 390,
                    762,
                    162,
                    id='img',
                    showBoundary=0
                ),
                Frame(
                    30,
                    doc.bottomMargin + 350,
                    750,
                    55,
                    id='trade',
                    showBoundary=0
                ),
                Frame(
                    30,
                    doc.bottomMargin + 270,
                    750,
                    90,
                    id='ind_entry',
                    showBoundary=0
                ),
                Frame(
                    30,
                    doc.bottomMargin + 175,
                    doc.width / 4 - 10,
                    doc.height / 6 + 10,
                    id='1',
                    showBoundary=0  # set to 1 for debugging
                ),
                Frame(
                    doc.leftMargin + doc.width / 4 - 7,
                    doc.bottomMargin + 175,
                    doc.width / 4 - 10,
                    doc.height / 6 + 10,
                    id='2',
                    showBoundary=0
                ),
                Frame(
                    doc.leftMargin + doc.width / 2 - 14,
                    doc.bottomMargin + 175,
                    doc.width / 4 - 10,
                    doc.height / 6 + 10,
                    id='3',
                    showBoundary=0
                ),
                Frame(
                    doc.leftMargin + 3 * doc.width / 4 - 21,
                    doc.bottomMargin + 175,
                    doc.width / 4 - 10,
                    doc.height / 6 + 10,
                    id='4',
                    showBoundary=0
                ),
                Frame(
                    30,
                    doc.bottomMargin + 95,
                    750,
                    90,
                    id='ind_exit',
                    showBoundary=0
                ),
                Frame(
                    30,
                    FOMC_Y_POSITION,
                    FOMC_WIDTH,
                    FOMC_HEIGHT,
                    id='fomc_column1',
                    showBoundary=0
                ),
                Frame(
                    30 + doc.width / 4 - 7,
                    FOMC_Y_POSITION,
                    FOMC_WIDTH,
                    FOMC_HEIGHT,
                    id='fomc_column2',
                    showBoundary=0
                ),
                Frame(
                    30 + 2 * doc.width / 4 - 14,
                    FOMC_Y_POSITION,
                    FOMC_WIDTH,
                    FOMC_HEIGHT,
                    id='fomc_column3',
                    showBoundary=0
                ),
                Frame(
                    30 + 3 * doc.width / 4 - 21,
                    FOMC_Y_POSITION,
                    FOMC_WIDTH,
                    FOMC_HEIGHT,
                    id='fomc_column4',
                    showBoundary=0
                ),
                Frame(
                    30,
                    doc.bottomMargin - 5,
                    doc.width,
                    30,
                    id='next_fomc',
                    showBoundary=0
                )
            ],
        )
    ]
)
コード例 #31
0
from reportlab.lib.colors import black, green, red, brown,blueviolet, pink, blue,white
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter

from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Frame, PageTemplate
styles = getSampleStyleSheet()

doc = SimpleDocTemplate("json_table.pdf", pagesize=letter)
frame = Frame(0, 10, 650, 780, id='col1', showBoundary=0)
Page = PageTemplate(id='col1', frames=[frame])
doc.addPageTemplates([Page])

f = open("sample2.json", "r")
import json
# st = f.read()
# print(st)
json_file = json.load(f)
text = []
col_span = []
width = []
elements = []

for key in json_file:
    head = []
    col = []
    body = []
    colbody = []
    # w = []

    for x in key["header"]:
コード例 #32
0
ファイル: views.py プロジェクト: geekaia/capsdjango
def gerarRelatorio(request):

    # Se for informado algo será considerado
    pcr = "t"
    try:
        pcr = request.GET['pcr']
        pcrq = paciente.objects.get(pk=int(pcr))
    except:
        pcr = "t"

    Story = []

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT))
    styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT))

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    nomearquivo = "relatorio" + datetime.date.today().strftime(
        "%d/%m/%Y") + ".pdf"
    response[
        'Content-Disposition'] = 'filename="' + nomearquivo + '"'  # attachment; filename=
    buff = BytesIO()

    styleN = styles['Normal']

    def footer(canvas, doc):
        canvas.saveState()
        P = Paragraph(
            "<hr/><br/>Rua Francisco Lira, 1470, Sena marques. CEP 78.600-000 - Barra do Garças-MT <br/>Tel.: (66) 3401-7805  ",
            styles["Center"])
        w, h = P.wrap(doc.width, doc.bottomMargin)
        P.drawOn(canvas, doc.leftMargin, h)

        canvas.line(doc.leftMargin, 62, doc.width + 67, 62)

        logo = os.path.join(BASE_DIR, "logopref.png")

        im = Image(logo, 0.7 * inch, 0.7 * inch)
        h = im.imageHeight
        w = im.imageWidth
        c = w / 2
        ch = h / 2

        print("Width: ", w)
        print("Height: ", h)
        print("c: ", c)
        print("ch: ", ch)

        print("Doc width: ", doc.width)
        print("LeftM width: ", doc.leftMargin)
        print("Centro: ", (doc.width / 2) + c - 37)

        im.drawOn(canvas, (doc.width / 2) + c - (doc.leftMargin / 2),
                  doc.height + doc.topMargin - 5)

        #
        # header = Paragraph(im, styles['Center'])
        # w, h = header.wrap(doc.width, doc.topMargin)
        # header.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - h)
        #
        ptext = "<br/>PREFEITURA DE BARRA DO GARÇAS<br/>"
        ptext += "SECRETARIA MUNICIPAL DE SAÚDE<br/>"
        ptext += "Centro de Atenção Psicossoail CAPS II TM<br/><br/>"

        header = Paragraph(ptext, styles['Center'])
        w, h = header.wrap(doc.width, doc.topMargin)
        header.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - h)

        canvas.restoreState()

    doc = SimpleDocTemplate(
        buff,
        pagesize=A4,
        rightMargin=72,
        leftMargin=72,
        topMargin=135,
        bottomMargin=72,
    )

    frame = Frame(doc.leftMargin,
                  doc.bottomMargin,
                  doc.width,
                  doc.height,
                  id='normal')

    template = PageTemplate(id='test', frames=frame, onPage=footer)
    doc.addPageTemplates([template])

    ptext = "<b>RELATÓRIO</b><br/> <br/>"

    if pcr == "t":
        datainicialr = request.GET['datainicialr']
        datafinalr = request.GET['datafinalr']

        datainicialrt = datetime.datetime.strptime(datainicialr, '%Y-%m-%d')
        datafinalrt = datetime.datetime.strptime(datafinalr, '%Y-%m-%d')

    Story.append(Paragraph(ptext, styles["Center"]))

    ptext = "<b>Relatório gerado no dia </b> " + datetime.date.today(
    ).strftime("%d/%m/%Y") + "<br/>"

    if pcr == "t":
        ptext += "<b>Data inicial: </b> " + datainicialrt.strftime(
            "%d/%m/%Y") + "<br/>"
    else:

        ptext += "<b>Paciente: </b> " + pcrq.nome + "<br/><br/>"

    l = ""
    tadd = ""

    try:
        l = request.GET['lista']

        if l == 't':
            tadd = ""
        else:
            profl = Profissional.objects.get(pk=int(l))
            tadd = " <br/><b>Profissional:</b>  " + profl.user.get_full_name()
            tadd += " <br/><b>Especialidade:</b>  " + profl.get_especialidade_display(
            )

    except:
        print("Erro lista : ", tadd)
        # tadd = ""

    if pcr == "t":
        ptext += " <b>Data final:</b>  " + datafinalrt.strftime(
            "%d/%m/%Y") + tadd + " <br/><br/>"

    Story.append(Paragraph(ptext, styles["Left"]))

    datatable = []

    evolucao = []

    # consultasInt = Consulta.objects.filter(data__gte=datafinalr).filter(data__lte=datainicialr)
    if pcr == "t":
        consultasInt = Consulta.objects.filter(data__lte=datafinalr).filter(
            data__gte=datainicialr).filter(status='conc').order_by("data")

        # em = Horario.objects.filter(profissional_id__exact=hora.profissional.id).filter(
        #     validadefim__gte=hora.validadeinicio).filter(
        #     validadeinicio__lte=hora.validadeinicio).exclude(id=hora.id)

        try:
            l = request.GET['lista']

            if l != 't':
                profl = Profissional.objects.get(pk=int(l))
                consultasInt = consultasInt.filter(profissional=profl)
        except:
            pass

        print('quantidade de consultasInt:', len(consultasInt))
    else:

        consultasInt = Consulta.objects.filter(paciente=pcrq).filter(
            status='conc').order_by("data")

    cont = 1

    if l == 't':
        datatable.append(
            ['Num', 'Data', 'Hora', 'Nome', 'Especialidade', 'Paciente'])
    else:
        if pcr == 't':
            datatable.append(['Num', 'Data', 'Hora',
                              'Paciente'])  # Relatório de um profissional
        else:
            datatable.append(['Num', 'Data', 'Hora', 'Nome',
                              'Especialidade'])  # De um paciente em específico
            evolucao.append(['Profissional', 'Anotações'])

    for con in consultasInt:
        if l == 't':
            datatable.append([
                cont,
                con.data.strftime("%d/%m/%Y"), con.hora,
                Paragraph(con.profissional.user.get_full_name(),
                          styles["Left"]),
                con.profissional.get_especialidade_display(),
                Paragraph(con.paciente.nome, styles["Left"])
            ])
        else:
            if pcr == 't':
                datatable.append([
                    cont,
                    con.data.strftime("%d/%m/%Y"), con.hora,
                    Paragraph(con.paciente.nome, styles["Left"])
                ])
            else:
                datatable.append([
                    cont,
                    con.data.strftime("%d/%m/%Y"), con.hora,
                    Paragraph(con.profissional.user.get_full_name(),
                              styles["Left"]),
                    con.profissional.get_especialidade_display()
                ])

        cont += 1

    from reportlab.lib.units import mm

    if (len(consultasInt) >= 1):
        if l == 't':
            t = Table(datatable,
                      colWidths=(10 * mm, 22 * mm, 20 * mm, 50 * mm, 50 * mm,
                                 50 * mm))
        else:
            if pcr == "t":
                t = Table(datatable,
                          colWidths=(10 * mm, 22 * mm, 20 * mm, 100 * mm))
            else:
                t = Table(datatable,
                          colWidths=(10 * mm, 22 * mm, 20 * mm, 50 * mm,
                                     53 * mm))
        #
        t.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ]))

        Story.append(t)
    else:
        print("Não há registros de consulta")

    try:
        pc = paciente.objects.get(pk=pcr)
        print("Oi4", pc.nome)
        evData = Evolucao.objects.all().filter(paciente=pc)
        print("Oi1")

        # evolucao.append(['Profissional', 'Anotações'])

        for ev in evData:
            text = Paragraph(ev.anotacoes.replace("\n", "<br/>"),
                             styles["Justify"])
            esp = Paragraph(
                ev.profissional.get_especialidade_display() + ": " +
                ev.profissional.user.get_full_name() + " -- dia: " +
                ev.ultimaatualizacao.strftime("%d/%m/%Y"), styles["Left"])
            evolucao.append([esp, text])
        print("Oi2 ", len(evData))

        t2 = Table(evolucao, colWidths=((10 + 22 + 20) * mm, (50 + 53) * mm))
        print('oi3333')
        #
        t2.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ]))

        Story.append(Paragraph("<br/><br/>", styles['Left']))
        Story.append(t2)
    except:
        print('Não há registros de evolução')

    doc.build(Story)

    response.write(buff.getvalue())
    buff.close()

    return response
コード例 #33
0
def form_01(request_data):
    """
    форма Пасопрт здоровья Приказ Министерства здравоохранения и социального развития РФ от 12 апреля 2011 г. N 302н
    """
    ind_card = Card.objects.get(pk=request_data["card_pk"])
    patient_data = ind_card.get_data_individual()

    work_data = patient_data['work_position']
    work_data = work_data.split(';')
    work_department, work_position = "", ""
    if len(work_data) >= 2:
        work_department = work_data[1]

    if len(work_data) >= 1:
        work_position = work_data[0]
    else:
        work_position = work_data

    hospital: Hospitals = request_data["hospital"]

    hospital_name = hospital.title
    hospital_address = hospital.safe_address
    hospital_kod_ogrn = hospital.safe_ogrn

    health_passport_num = request_data["card_pk"]  # номер id patient из базы

    list_result = [
        'Общ. анализ крови',
        'Общ.анализ мочи',
        'Глюкоза крови',
        'Холестерин',
        'RW',
        'Флюорография',
        'ЭКГ',
        'Спирометрия',
        'УЗИ м/желёз (маммогр.)',
        'Аудиометрия',
        'УЗИ огр.м/таза',
        'Исслед. вестибулярн. аппарата',
        'Исслед.вибрационн. чувствительности',
        'Острота зрения',
        'Рефрактометрия',
        'Объём аккомодации',
        'Исслед.бинокулярн. зрения',
        'Цветоощущение',
        'Офтальмотонометрия',
        'Биомикроскопия сред глаза',
        'Поля зрения',
        'Бактериоскопия мазка',
        'Офтальмоскопия глазного дня',
        'Мазок из зева и носа',
        'Ретикулоциты',
        'АЛК или КП в моче',
        'Метгемоглобины',
        'Базальн. Зернист. Эритроцитов',
    ]  # список лабораторных, инструментальных исследований
    list_doctor = [
        'Терапевт', 'Психиатр', 'Нарколог', 'Гинеколог', 'Офтальмолог', 'Лор',
        'Невролог', 'Дерматолог', 'Хирург', 'Стоматолог'
    ]  # список врачей-специалистов

    for i in range(0, 3):
        list_doctor.append('')

    if sys.platform == 'win32':
        locale.setlocale(locale.LC_ALL, 'rus_rus')
    else:
        locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')

    pdfmetrics.registerFont(
        TTFont('PTAstraSerifBold',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf')))
    pdfmetrics.registerFont(
        TTFont('PTAstraSerifReg',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf')))

    buffer = BytesIO()

    doc = SimpleDocTemplate(buffer,
                            pagesize=A4,
                            leftMargin=10 * mm,
                            rightMargin=10 * mm,
                            topMargin=10 * mm,
                            bottomMargin=10 * mm,
                            allowSplitting=1,
                            title="Форма {}".format("Паспорт здоровья"))
    width, height = landscape(A4)
    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "PTAstraSerifBold"
    style.fontSize = 9
    style.leading = 6
    styleBold = deepcopy(style)
    styleBold.fontName = "PTAstraSerifBold"
    styleCenter = deepcopy(style)
    styleCenter.alignment = TA_CENTER
    styleCenter.leading = 1
    styleCenterBold = deepcopy(styleBold)
    styleCenterBold.alignment = TA_CENTER
    styleCenterBold.leading = 10
    styleJustified = deepcopy(style)
    styleJustified.alignment = TA_JUSTIFY
    styleJustified.spaceAfter = 4 * mm
    styleJustified.fontSize = 12
    styleJustified.leading = 4.5 * mm

    righ_frame = Frame(148.5 * mm,
                       0 * mm,
                       width=148.5 * mm,
                       height=210 * mm,
                       leftPadding=10 * mm,
                       bottomPadding=6,
                       rightPadding=10 * mm,
                       topPadding=6,
                       showBoundary=1)
    left_frame = Frame(0 * mm,
                       0 * mm,
                       width=148.5 * mm,
                       height=210 * mm,
                       leftPadding=10 * mm,
                       bottomPadding=6,
                       rightPadding=10 * mm,
                       topPadding=6,
                       showBoundary=1)
    doc.addPageTemplates(
        PageTemplate(id='TwoCol',
                     frames=[righ_frame, left_frame],
                     pagesize=landscape(A4)))

    space = 5.5 * mm
    space_symbol = '&nbsp;'

    work_p = patient_data['work_place_db'] if patient_data[
        'work_place_db'] else patient_data['work_place']
    objs = [
        Spacer(1, 3 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold">Министерство здравоохранения Российской Федерации</font>',
            styleCenter),
        Spacer(1, 5 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold"><u>{}</u></font>'.format(
                hospital_name), styleCenterBold),
        Spacer(1, 1),
        Paragraph(
            '<font face="PTAstraSerifReg"><font size=9>(наименование медицинской организации)</font></font>',
            styleCenter),
        Spacer(1, 7 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold"><u>{}</u></font>'.format(
                hospital_address), styleCenter),
        Spacer(1, 5 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold" size=12>Код ОГРН {}</font>'.format(
                hospital_kod_ogrn), styleCenter),
        Spacer(1, 10 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold" size=12>ПАСПОРТ ЗДОРОВЬЯ РАБОТНИКА № <u>{}</u></font>'
            .format(health_passport_num), styleCenter),
        Spacer(1, space),
        Paragraph(
            '<font face="PTAstraSerifReg"size=10><u>{} года</u></font>'.format(
                pytils.dt.ru_strftime(u"%d %B %Y",
                                      inflected=True,
                                      date=datetime.datetime.now())),
            styleCenter),
        Spacer(1, 3 * mm),
        Paragraph(
            '<font face="PTAstraSerifReg" size=7>(дата оформления)</font>',
            styleCenter),
        Spacer(1, space),
        Paragraph(
            '<font face="PTAstraSerifReg">1.Фамилия, имя, отчество:'
            '<u>{}</u> </font>'.format(patient_data['fio']), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">2.Пол: <u>{}</u> <img src="forms/img/FFFFFF-space.png" width="90" />'
            '3.Дата Рождения: <u>{}</u> </font>'.format(
                patient_data['sex'], patient_data['born']),
            styleJustified,
        ),
        Paragraph(
            '<font face="PTAstraSerifReg">4.Паспорт: серия <u>{}</u> <img src="forms/img/FFFFFF-space.png" width="25"/>'
            'номер: <u>{}</u></font>'.format(patient_data['passport_serial'],
                                             patient_data['passport_num']),
            styleJustified,
        ),
        Paragraph(
            '<font face="PTAstraSerifReg">Дата выдачи: <u>{}</u></font>'.
            format(patient_data['passport_date_start']), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg"> Кем Выдан: <u>{}</u></font>'.format(
                patient_data['passport_issued']), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">5. Адрес регистрации по месту жительства (пребывания):'
            ' <u>{}</u></font>'.format(patient_data['main_address']),
            styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">6. Номер страхового полиса(ЕНП):'
            ' <u>{}</u></font>'.format(patient_data['oms']['polis_num']),
            styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">7. Наименование работодателя:'
            ' <u>{}</u></font>'.format(work_p), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">7.1 Форма собственности и вид экономической деятельности '
            'работодателя по ОКВЭД: <u>{}</u></font>'.format(
                50 * space_symbol), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">7.2  Наименование структурного подразделения (цех, участок, отдел):<u> {}</u></font>'
            .format(work_department), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">8. Профессия (должность) (в настоящее время):'
            ' <u>{}</u></font>'.format(work_position), styleJustified),
        FrameBreak(),
        Spacer(1, space),
        Paragraph('<font face="PTAstraSerifReg">12. Заключение:</font>',
                  styleJustified),
    ]
    styleT = deepcopy(style)
    styleT.alignment = TA_CENTER
    styleT.fontSize = 10
    styleT.leading = 4.5 * mm

    opinion = [
        [
            Paragraph(
                '<font face="PTAstraSerifReg">Заключение по результатам предварительного '
                'и периодического медицинского осмотра</font>', styleT),
            Paragraph(
                '<font face="PTAstraSerifReg">Дата получения заключения</font>',
                styleT),
            Paragraph(
                '<font face="PTAstraSerifReg"> Подпись профпатолога</font>',
                styleT),
        ],
    ]

    for i in range(0, 5):
        para = [
            Paragraph(
                '<font face="PTAstraSerifReg" size=11>Профпригоден/\nпрофнепригоден</font>',
                styleT)
        ]
        opinion.append(para)

    tbl = Table(
        opinion,
        colWidths=(48 * mm, 40 * mm, 40 * mm),
        hAlign='LEFT',
        style=[
            ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('TOPPADDING', (0, 0), (-1, -1), 1.5 * mm),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm),
        ],
    )

    objs.append(tbl)

    objs.append(Spacer(1, 10 * mm))
    objs.append(
        Paragraph('<font face="PTAstraSerifReg">Для заметок:</font>',
                  styleJustified))

    s = "___________________________________________________________"
    for i in range(0, 6):
        objs.append(Spacer(1, 1 * mm))
        objs.append(
            Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(s),
                      styleJustified))

    objs.append(NextPageTemplate("TwoCol"))
    objs.append(FrameBreak())
    objs.append(Spacer(1, 7 * mm))
    objs.append(
        Paragraph(
            '<font face="PTAstraSerifReg">11. Результаты лабораторных и инструментальных исследований'
            '</font>', styleJustified))

    tbl_result = [
        [
            Paragraph(
                '<font face="PTAstraSerifReg" size=11>Вид исследования</font>',
                styleT),
            Paragraph(
                '<font face="PTAstraSerifReg" size=11>Даты исследований</font>',
                styleT),
            '',
            '',
            '',
            '',
        ],
        ['', '', '', '', '', ''],
    ]

    styleTR = deepcopy(styleT)
    styleTR.alignment = TA_LEFT
    styleTR.fontSize = 11
    styleTR.spaceAfter = 12 * mm

    for i in list_result:
        para = [
            Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(i),
                      styleTR)
        ]
        tbl_result.append(para)

    tbl = Table(
        tbl_result,
        colWidths=(41 * mm, 22 * mm, 17 * mm, 17 * mm, 17 * mm, 17 * mm),
        hAlign='LEFT',
        style=[
            ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm),
            ('SPAN', (0, 0), (0, 1)),
            ('SPAN', (1, 0), (-1, 0)),
        ],
    )
    objs.append(tbl)

    objs.append(FrameBreak())
    objs.append(Spacer(1, 7 * mm))
    objs.append(
        Paragraph(
            '<font face="PTAstraSerifReg">9. Условия труда в настоящее время</font>',
            styleJustified))

    tbl_result = [[
        Paragraph(
            '<font face="PTAstraSerifReg" size=10>Наименование производственного фактора, вида работы с '
            'указанием пункта</font>', styleT),
        Paragraph(
            '<font face="PTAstraSerifReg" size=10>Стаж работы с фактором</font>',
            styleT),
    ]]
    for i in range(0, 4):
        para = ['', '']
        tbl_result.append(para)

    row_height = []
    for i in tbl_result:
        row_height.append(8 * mm)

    row_height[0] = None
    tbl = Table(
        tbl_result,
        colWidths=(75 * mm, 55 * mm),
        rowHeights=row_height,
        hAlign='LEFT',
        style=[
            ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm),
            ('LEFTPADDING ', (0, 2), (0, -1), 0.1 * mm),
            ('SPAN', (1, 1), (1, -1)),
        ],
    )

    objs.append(tbl)

    objs.append(Spacer(1, 5 * mm))

    styleDoc = deepcopy(styleJustified)
    styleDoc.spaceAfter = 1 * mm
    objs.append(
        Paragraph(
            '<font face="PTAstraSerifReg">10. Заключения врачей - специалистов:</font>',
            styleDoc,
        ))
    tbl_result = [
        [
            Paragraph(
                '<font face="PTAstraSerifReg" size=11>Врач-специалист</font>',
                styleT),
            Paragraph(
                '<font face="PTAstraSerifReg" size=11>Даты исследований</font>',
                styleT),
            '',
            '',
            '',
            '',
        ],
        ['', '', '', '', '', ''],
    ]

    for i in list_doctor:
        para = [
            Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(i),
                      styleTR)
        ]
        tbl_result.append(para)

    row_height = []
    for i in tbl_result:
        row_height.append(9 * mm)

    row_height[0] = None
    row_height[1] = None
    tbl = Table(
        tbl_result,
        colWidths=(41 * mm, 22 * mm, 17 * mm, 17 * mm, 17 * mm, 17 * mm),
        rowHeights=row_height,
        hAlign='LEFT',
        style=[
            ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm),
            ('LEFTPADDING ', (0, 2), (0, -1), 0.1 * mm),
            ('SPAN', (0, 0), (0, 1)),
            ('SPAN', (1, 0), (-1, 0)),
        ],
    )
    objs.append(tbl)

    def first_pages(canvas, document):
        canvas.saveState()
        canvas.restoreState()

    def later_pages(canvas, document):
        canvas.saveState()
        canvas.restoreState()

    doc.build(objs, onFirstPage=first_pages, onLaterPages=later_pages)

    pdf = buffer.getvalue()
    buffer.close()
    return pdf
コード例 #34
0
class Impresion():
    def __init__(self):
        super(Impresion, self).__init__()

##############################################################################

    def encabezadoLandscape(self, canvas, doc):
        ancho, alto = self.tam
        canvas.saveState()
        fonts = canvas.getAvailableFonts()
        for i in fonts:
            print(i)
        canvas.drawImage("logo_imca.png", 10, 7.2 * inch, width=200, height=70)
        canvas.setFont('Helvetica', 19)
        canvas.setFillColor(colors.black)
        canvas.drawString(3.5*inch, 7.7*inch, 'Instituto Municipal de ' \
        'Cerámica de Avellaneda "Emilio Villafañe"')
        canvas.setFont('Helvetica', 10)
        canvas.drawString(3.5*inch, 7.5*inch, 'dependiente de la Secretaría '\
        'de Educación, Cultura y Promoción de las Artes')
        #A4[1]-50
        canvas.rect(0, 7 * inch, width=alto, height=0.1, stroke=1, fill=1)
        canvas.restoreState()

##############################################################################

    def encabezado(self, canvas, doc):
        ancho, alto = self.tam
        canvas.saveState()
        fonts = canvas.getAvailableFonts()
        for i in fonts:
            print(i)
        canvas.drawImage("logo_imca.png",
                         10,
                         10.5 * inch,
                         width=200,
                         height=70)
        canvas.setFont('Helvetica', 12)
        canvas.setFillColor(colors.black)
        canvas.drawString(3.2*inch, 11*inch, 'Instituto Municipal de ' \
        'Cerámica de Avellaneda "Emilio Villafañe"')
        canvas.setFont('Helvetica', 8)
        canvas.drawString(3.2*inch, 10.8*inch, 'dependiente de la Secretaría '\
        'de Educación, Cultura y Promoción de las Artes')
        #A4[1]-50
        canvas.rect(0, 10.3 * inch, width=ancho, height=0.1, stroke=1, fill=1)
        canvas.restoreState()

##############################################################################

    def pie(self, canvas, doc):
        canvas.saveState()
        canvas.setFont('Times-Roman', 9)
        canvas.drawString(inch, 0.75 * inch, "Av. Mitre 2724, Avellaneda "\
        "(B1872GFF) Provincia de Buenos Aires. Telefax. 0054-11-4204-8223"\
        "/6378 D I P R E G E P 7 5 7 8")
        canvas.restoreState()

##############################################################################

    def createPageTemplate(self, orientacion, size):

        self.doc = SimpleDocTemplate("phello.pdf")
        if size == A4:
            self.tam = A4
            ancho, alto = A4
        else:
            self.tam = LEGAL
            ancho, alto = LEGAL

        if orientacion == "landscape":
            frameT = Frame(0, 0, alto, ancho, showBoundary=1)
            self.doc.pagesize = landscape(self.tam)
            PTUnaColumna = PageTemplate(id='UnaColumna',
                                        frames=[frameT],
                                        onPage=self.encabezadoLandscape,
                                        onPageEnd=self.pie)

        else:
            frameT = Frame(0, 0, ancho, alto, showBoundary=1)
            self.doc.pagesize = self.tam
            PTUnaColumna = PageTemplate(id='UnaColumna',
                                        frames=[frameT],
                                        onPage=self.encabezado,
                                        onPageEnd=self.pie)
        PTUnaColumna.pageBreakBefore = 0
        PTUnaColumna.keepWithNext = 0
        self.doc.addPageTemplates([PTUnaColumna])

##############################################################################

    def creoEstilo(self):
        self.styles = getSampleStyleSheet()
        self.estilo1 = self.styles['BodyText']
        self.estilo2 = self.styles['Normal']

##############################################################################

    def creoStory(self):
        self.story = []
        self.story.append(Spacer(1, 1.4 * inch))

##############################################################################

    def cierroStory(self):
        self.doc.build(self.story)

##############################################################################

    def agregoString(self, txt, estilo='Titulo'):
        titulo = Paragraph(txt, self.styles[estilo])
        self.story.append(titulo)

##############################################################################

    def definoEstilos(self, name='Titulo', size=16, font="Helvetica", lead=18):
        self.styles.add(
            ParagraphStyle(name=name,
                           alignment=TA_CENTER,
                           fontSize=size,
                           fontName=font,
                           leading=lead))

##############################################################################

    def agregoTabla(self, t):
        self.story.append(t)

##############################################################################

    def imprimo(self):
        try:
            sitemap = os.name
            if sitemap == 'posix':
                print('linux')
                os.system('evince phello.pdf')
            else:
                print('win')
                os.system("start AcroRD32 phello.pdf &")
        except:
            print("No está instalado el evince")

##############################################################################

    def agregoTitulo(self, titulo):
        canvas.saveState()
        canvas.setFont('Times-Roman', 9)
        canvas.drawString(inch, 0.75 * inch, titulo)
        canvas.restoreState()

##############################################################################

    def agregoSpacer(self):
        self.story.append(Spacer(1, 0.1 * inch))
コード例 #35
0
ファイル: statsaccess.py プロジェクト: hibozzy/mediatum
    def build(self, style=1):
        self.h1 = self.styleSheet['Heading1']
        self.h1.fontName = 'Helvetica'
        self.bv = self.styleSheet['BodyText']
        self.bv.fontName = 'Helvetica'
        self.bv.fontSize = 7
        self.bv.spaceBefore = 0
        self.bv.spaceAfter = 0

        self.chartheader = self.styleSheet['Heading3']
        self.chartheader.fontName = 'Helvetica'

        self.formatRight = self.styleSheet['Normal']
        self.bv.formatRight = 'Helvetica'
        self.formatRight.alignment = 2

        nameColl = self.collection.getName()

        while True:
            # page 1
            p = Paragraph(
                "%s \n'%s'" %
                (t(self.language, "edit_stats_header"), nameColl), self.h1)
            p.wrap(defaultPageSize[0], defaultPageSize[1])

            if p.getActualLineWidths0()[0] < 19 * cm:
                break
            else:
                nameColl = nameColl[0:-4] + "..."

        self.data.append(p)

        self.data.append(
            Paragraph(
                "%s: %s" %
                (t(self.language, "edit_stats_period_header"), self.period),
                self.chartheader))
        self.data.append(
            Paragraph(
                t(self.language, "edit_stats_pages_of") % ("1", "4"),
                self.formatRight))

        self.data.append((FrameBreak()))
        # top 10
        self.data += self.getStatTop("data", namecut=60)

        # page 2
        self.data.append(
            Paragraph(
                "%s \n'%s' %s - " % (t(self.language, "edit_stats_header"),
                                     self.collection.getName(), self.period) +
                t(self.language, "edit_stats_pages_of") % ("2", "4"), self.bv))
        self.data.append((FrameBreak()))
        # country
        self.data += self.getStatCountry("data")
        self.data.append(PageBreak())

        # page 3
        self.data.append(
            Paragraph(
                "%s \n'%s' %s - " % (t(self.language, "edit_stats_header"),
                                     self.collection.getName(), self.period) +
                t(self.language, "edit_stats_pages_of") % ("3", "4"), self.bv))
        self.data.append((FrameBreak()))
        # date
        self.data += self.getStatDate("data")
        self.data.append(PageBreak())

        # page 4
        self.data.append(
            Paragraph(
                "%s \n'%s' %s - " % (t(self.language, "edit_stats_header"),
                                     self.collection.getName(), self.period) +
                t(self.language, "edit_stats_pages_of") % ("4", "4"), self.bv))
        self.data.append((FrameBreak()))
        # weekday
        self.data += self.getStatDay("data")
        # time
        self.data += self.getStatTime("data")

        template = SimpleDocTemplate(config.get("paths.tempdir", "") +
                                     "statsaccess.pdf",
                                     showBoundary=0)
        tFirst = PageTemplate(id='First',
                              onPage=self.myPages,
                              pagesize=defaultPageSize)
        tNext = PageTemplate(id='Later',
                             onPage=self.myPages,
                             pagesize=defaultPageSize)

        template.addPageTemplates([tFirst, tNext])
        template.allowSplitting = 1
        BaseDocTemplate.build(template, self.data)

        template.canv.setAuthor(t(self.language, "main_title"))
        template.canv.setTitle(
            "%s \n'%s' - %s: %s" %
            (t(self.language, "edit_stats_header"), self.collection.getName(),
             t(self.language, "edit_stats_period_header"), self.period))
        return template.canv._doc.GetPDFData(template.canv)
コード例 #36
0
ファイル: prints.py プロジェクト: egegunes/hastatakip
    def get(self, request, *args, **kwargs):
        recete = self.get_object()

        ad = str(recete.hasta.ad)
        soyad = str(recete.hasta.soyad)
        pk = str(recete.id)
        muayene_tarihi = str(recete.tarih)

        title = unidecode("%s-%s-recete-%s-%s" % (ad, soyad, pk, muayene_tarihi))
        filename = title + ".pdf"

        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'filename=%s' % filename

        buff = BytesIO()

        doc = SimpleDocTemplate(buff,
                                pagesize=letter,
                                title=title,
                                author="Dr. Ziya T. Güneş",
                                rightMargin=inch/4,
                                leftMargin=inch/4,
                                topMargin=inch/2,
                                bottomMargin=inch/4,
                                showBoundary=0)

        frame1 = Frame(doc.leftMargin,
                       doc.bottomMargin,
                       doc.width,
                       doc.height / 8,
                       id="footer")
        frame2 = Frame(doc.leftMargin,
                       doc.bottomMargin + doc.height / 8 + 6,
                       doc.width,
                       doc.height * 6 / 8,
                       id="body")
        frame3 = Frame(doc.leftMargin,
                       doc.bottomMargin + doc.height * 7 / 8 + 12,
                       doc.width * 3 / 4 - 6,
                       doc.height / 8,
                       id="header_right")
        frame4 = Frame(doc.leftMargin + doc.width * 3 / 4 + 6,
                       doc.bottomMargin + doc.height * 7 / 8 + 12,
                       doc.width / 4 - 6,
                       doc.height / 8,
                       id="header_left")

        receteTemplate = PageTemplate(frames=[frame1, frame2, frame3, frame4])
        doc.addPageTemplates(receteTemplate)

        self.register_font()
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name="footer",
                                  fontName="Vera",
                                  fontSize=10,
                                  alignment=2,
                                  leading=20))
        styles.add(ParagraphStyle(name="heading",
                                  parent=self.base_style,
                                  fontSize=20,
                                  alignment=0,
                                  spaceAfter=40))
        styles.add(ParagraphStyle(name="ilac_ad",
                                  parent=self.base_style,
                                  fontSize=14,
                                  alignment=0,
                                  leftIndent=30,
                                  spaceAfter=10,
                                  leading=20))
        styles.add(ParagraphStyle(name="ilac_kullanim",
                                  parent=self.base_style,
                                  fontSize=12,
                                  alignment=0,
                                  leftIndent=50,
                                  spaceAfter=20,
                                  leading=20))
        styles.add(ParagraphStyle(name="header_left",
                                  parent=self.base_style,
                                  fontSize=12,
                                  alignment=0))
        styles.add(ParagraphStyle(name="header_right",
                                  parent=self.base_style,
                                  fontSize=12,
                                  alignment=2))

        story = []

        ad = Paragraph("Dr. Ziya T. GÜNEŞ", styles['footer'])
        tel = Paragraph("0(232) 422 00 56", styles['footer'])
        mail = Paragraph("*****@*****.**", styles['footer'])
        adres = Paragraph("Işılay Saygın Sokak No:17 Kat:2 Alsancak/İzmir", styles['footer'])

        story.append(ad)
        story.append(tel)
        story.append(mail)
        story.append(adres)

        story.append(FrameBreak())

        heading = Paragraph("R<u>p/</u>", styles['heading'])

        story.append(heading)

        ilac1 = Paragraph("1. %s (%d kutu)" % (recete.ilac1.ad, recete.ilac1_kutu), styles['ilac_ad'])
        ilac1_kullanim = Paragraph("S: %s" % (recete.ilac1_kullanim), styles['ilac_kullanim'])
        story.append(ilac1)
        story.append(ilac1_kullanim)

        if recete.ilac2:
            ilac2 = Paragraph("2. %s (%d kutu)" % (recete.ilac2.ad, recete.ilac2_kutu), styles['ilac_ad'])
            ilac2_kullanim = Paragraph("S: %s" % (recete.ilac2_kullanim), styles['ilac_kullanim'])
            story.append(ilac2)
            story.append(ilac2_kullanim)

        if recete.ilac3:
            ilac3 = Paragraph("3. %s (%d kutu)" % (recete.ilac3.ad, recete.ilac3_kutu), styles['ilac_ad'])
            ilac3_kullanim = Paragraph("S: %s" % (recete.ilac3_kullanim), styles['ilac_kullanim'])
            story.append(ilac3)
            story.append(ilac3_kullanim)

        if recete.ilac4:
            ilac4 = Paragraph("4. %s (%d kutu)" % (recete.ilac4.ad, recete.ilac4_kutu), styles['ilac_ad'])
            ilac4_kullanim = Paragraph("S: %s" % (recete.ilac4_kullanim), styles['ilac_kullanim'])
            story.append(ilac4)
            story.append(ilac4_kullanim)

        if recete.ilac5:
            ilac5 = Paragraph("5. %s (%d kutu)" % (recete.ilac5.ad, recete.ilac5_kutu), styles['ilac_ad'])
            ilac5_kullanim = Paragraph("S: %s" % (recete.ilac5_kullanim), styles['ilac_kullanim'])
            story.append(ilac5)
            story.append(ilac5_kullanim)

        story.append(FrameBreak())

        hasta = str(recete.hasta)
        hasta_paragraph = Paragraph(hasta, styles['header_left'])

        story.append(hasta_paragraph)

        story.append(FrameBreak())

        tarih_paragraph = Paragraph(muayene_tarihi, styles['header_right'])

        story.append(tarih_paragraph)

        doc.build(story)

        response.write(buff.getvalue())
        buff.close()

        return response
コード例 #37
0
def generate_school_task_cards(data, filename="/tmp/school_tasks.pdf"):
    A4_width, A4_height = A4[0], A4[1]
    doc = SimpleDocTemplate(filename,
                            pagesize=A4,
                            rightMargin=0,
                            leftMargin=0,
                            topMargin=0,
                            bottomMargin=0)
    pdf_content = []
    frames = []
    w_counter = 0
    h_counter = 1
    width_position = 0
    same_line = True
    frame_w = 88.5 * mm
    frame_h = 140 * mm
    height_position = h_counter * frame_h
    frame_counter = 1
    for d in data:
        if A4_width - w_counter * frame_w > frame_w:
            if w_counter % 2 == 0:
                add = 0
            else:
                add = 40
            width_position = w_counter * frame_w + add
            same_line = True
        else:
            same_line = False
            w_counter = 0
            width_position = 0

        if not same_line:
            if A4_height - h_counter * frame_h >= frame_h:
                h_counter -= 1
                height_position = h_counter * frame_h
                same_line = True
        w_counter += 1

        frame_content = create_meeting_task_card(d)
        left_padding = (A4_width - 2 * 88.5 * mm - 40) / 2
        bottom_padding = (A4_height - 2 * 140 * mm) / 2
        frames.append(
            MyFrame(left_padding + width_position,
                    bottom_padding + height_position,
                    88.5 * mm,
                    140 * mm,
                    showBoundary=1))
        pdf_content.extend(frame_content)
        if len(frames) < len(data):
            pdf_content.append(FrameBreak())

        if frame_counter % 4 == 0 and len(data) - frame_counter > 0:
            w_counter = 0
            h_counter = 1
            same_line = True
            width_position = 0
            height_position = h_counter * frame_h
            pdf_content.append(NextPageTemplate("main_template"))
            pdf_content.append(PageBreak())

        frame_counter += 1

    template = PageTemplate(id='main_template', frames=frames)
    doc.addPageTemplates(template)
    doc.build(pdf_content)
コード例 #38
0
def generatePDF(FI, Equity, Investment, Valuation, monthlyInv, monthlyVal,
                equityTrades, bondTrades, net_position):

    logo = 'AIM_logo.jpg'
    portfolioDate = date.today()
    months = [
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
        'Nov', 'Dec'
    ]

    portfolioHoldings = [[
        '', 'Cost basis($)', 'Value on\n' + str(date.today()),
        'Unrealized\ngain/loss($)', 'Unrealized\ngain/loss(%)',
        '% of\nPortfolio'
    ], ['Bond'] + FI, ['Equity'] + Equity, ['Total Portfolio'] +
                         [round(a + b, 2) for (a, b) in zip(FI, Equity)]]

    #Page 4 data
    equity_data = [[
        'Equity', 'ISIN', 'Sector', 'Qty', 'Buy \nAverage($)',
        'Previous \nClosing Price($)', 'Holdings buy\nvalue($)',
        'Current\n Value($)', 'Unrealized\n gain/loss ($)',
        'Unrealized \ngain/loss(%)', '', '', '% of Asset Class',
        '% of portfolio'
    ]] + equityTrades

    bond_data = [[
        'Bond', 'ISIN', 'Sector', 'Qty', 'Buy \nAverage($)',
        'Previous\nClosing Price($)', 'Holdings buy\nvalue($)',
        'Current\nValue($)', 'Unrealized\n gain/loss ($)',
        'Unrealized \ngain/loss(%)', 'Accrued\nInterest (%)',
        'Maturity\n Date', '% of Asset Class', '% of portfolio'
    ]] + bondTrades

    portfolioDetails = equity_data + [[''] * 14] + bond_data

    netPosition = [[
        'Net Position', '', '', '', '', '', 'Holdings buy\nvalue($)',
        'Current\n Value($)', 'Unrealized\n gain/loss ($)',
        'Unrealized \ngain/loss(%)', '% of Asset Class', '% of portfolio'
    ]] + net_position

    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styleContent = ParagraphStyle(name='content',
                                  parent=styles['Normal'],
                                  fontSize=18,
                                  leading=35)
    styleH = styles['Heading1']
    style_right = ParagraphStyle(name='right',
                                 parent=styles['Heading1'],
                                 alignment=TA_RIGHT,
                                 fontSize=24)
    style_center = ParagraphStyle(name='center',
                                  parent=styles['Normal'],
                                  alignment=TA_CENTER,
                                  fontSize=16,
                                  leading=35)

    story = []
    doc = SimpleDocTemplate('portfolio.pdf',
                            pagesize=landscape(A4),
                            rightMargin=30,
                            leftMargin=30,
                            topMargin=30,
                            bottomMargin=30)

    myFrame = Frame(doc.leftMargin,
                    doc.bottomMargin,
                    doc.width,
                    doc.height,
                    id='myFrame')
    frame1 = Frame(doc.leftMargin,
                   doc.bottomMargin,
                   doc.width / 2 - 6,
                   doc.height,
                   id='col1')
    frame2 = Frame(doc.leftMargin + doc.width / 2 + 6,
                   doc.bottomMargin,
                   doc.width / 2 - 6,
                   doc.height,
                   id='col2')
    frame3 = Frame(doc.leftMargin,
                   doc.bottomMargin,
                   doc.width,
                   doc.height / 2,
                   id='col3')
    coverPage = PageTemplate(id='Cover', frames=[myFrame])
    threeTemplate = PageTemplate(id='ThreeSec',
                                 frames=[frame1, frame2, frame3])
    columnTemplate = PageTemplate(id='TwoCol', frames=[frame1, frame2])

    #Page 1
    story.append(Image(logo, 2 * inch, 2 * inch, hAlign='RIGHT'))
    story.append(Spacer(0, 10))
    story.append(Paragraph("CLIENT  PORTFOLIO", style_right))
    story.append(HRFlowable(width='100%', thickness=5, color=colors.navy))
    story.append(Spacer(0, 15))

    story.append(
        Paragraph(
            "TABLE OF CONTENTS",
            ParagraphStyle(name='content',
                           parent=styles['Normal'],
                           fontSize=18,
                           leading=35)))

    story.append(Paragraph("Investment Value" + "." * 104 + "1", styleN))
    story.append(Spacer(0, 15))
    story.append(Paragraph("Portfolio Holdings" + "." * 103 + "2", styleN))
    story.append(Spacer(0, 15))
    story.append(Paragraph("Net Position" + "." * 112 + "3", styleN))
    story.append(Spacer(0, 15))

    story.append(NextPageTemplate('ThreeSec'))
    story.append(PageBreak())

    #Page 2
    story.append(Paragraph("Investment Value", styleH))
    story.append(Paragraph("As of " + str(portfolioDate), styleContent))

    #Frame1
    draw = Drawing(200, 150)
    rect = Rect(doc.width / 4, 100, 120, 50)
    rect.fillColor = colors.lightcoral
    draw.add(rect)
    my_title = String(doc.width / 4 + 6, 135, 'Total Investment', fontSize=16)
    my_title.fillColor = colors.white
    draw.add(my_title)
    my_title = String(doc.width / 4 + 15,
                      110,
                      '$' + str(Investment),
                      fontSize=20)
    my_title.fillColor = colors.white
    draw.add(my_title)
    story.append(draw)

    story.append(FrameBreak())

    #Frame 2
    story.append(Spacer(0, 75))

    draw = Drawing(200, 150)
    rect = Rect(40, 112, 120, 50)
    rect.fillColor = colors.orange
    draw.add(rect)

    my_title = String(41, 145, 'Current Valuation', fontSize=16)
    my_title.fillColor = colors.white
    draw.add(my_title)
    my_title = String(55, 122, '$' + str(Valuation), fontSize=20)
    my_title.fillColor = colors.white
    draw.add(my_title)
    story.append(draw)

    story.append(FrameBreak())

    #Frame 3
    lineChart = line_chart(doc, months, portfolioDate, monthlyInv, monthlyVal,
                           Valuation, Investment)
    story.append(lineChart)

    story.append(NextPageTemplate('TwoCol'))
    story.append(PageBreak())

    # Page 3

    story.append(Paragraph("Portfolio Holdings", styleH))
    story.append(Paragraph("As of " + str(portfolioDate), styleContent))

    story.append(Spacer(0, 100))
    story.append(Paragraph("Summary of Portfolio Holdings", style_center))

    style = TableStyle([('BACKGROUND', (0, -1), (-1, -1), colors.whitesmoke),
                        ('ALIGN', (1, 0), (-1, -1), 'CENTER'),
                        ('FONTSIZE', (0, 0), (-1, -1), 8),
                        ('BODYTEXT', (0, 0), (-1, -1), 'TEXTWRAP'),
                        ('LINEABOVE', (0, 0), (-1, 1), 1, colors.black)])

    table1 = Table(portfolioHoldings)
    table1.setStyle(style)
    story.append(table1)

    story.append(FrameBreak())

    #Frame2
    chart = pie_chart_with_legend(doc, FI, Equity)
    story.append(chart)

    #Page 4
    story.append(PageBreak())
    story.append(Paragraph("Details of portfolio holdings", styleH))
    story.append(Paragraph("As of " + str(portfolioDate), styleContent))
    story.append(Spacer(0, 20))

    #style=[('BACKGROUND', (0,1), (-1,1), colors.whitesmoke),('ALIGN',(1,0),(-1,-1),'CENTER'),('FONTSIZE',(0,0),(-1,-1),8),('BODYTEXT',(0,0),(-1,-1),'TEXTWRAP'),('FONTNAME', (0,2), (-1,2), 'Helvetica-Bold')]
    style2 = [('ALIGN', (1, 0), (-1, -1), 'CENTER'),
              ('FONTSIZE', (0, 0), (-1, -1), 8),
              ('BODYTEXT', (0, 0), (-1, -1), 'TEXTWRAP'),
              ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
              ('LINEABOVE', (0, 0), (-1, 1), 1, colors.black)]
    style = [('ALIGN', (1, 0), (-1, -1), 'CENTER'),
             ('FONTSIZE', (0, 0), (-1, -1), 8),
             ('BODYTEXT', (0, 0), (-1, -1), 'TEXTWRAP'),
             ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
             ('LINEABOVE', (0, 0), (-1, 1), 1, colors.black),
             ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]

    data_len = len(equity_data)

    for each in range(3, data_len):
        bg_color = colors.white
        if each % 2 == 0:
            bg_color = colors.whitesmoke

        #style.append(('BACKGROUND', (0,each), (-1,each), bg_color))

    style2.append(
        ('FONTNAME', (0, data_len + 1), (-1, data_len + 1), 'Helvetica-Bold'))
    style2.append(
        ('LINEABOVE', (0, data_len + 1), (-1, data_len + 2), 1, colors.black))

    table = Table(portfolioDetails)
    table.setStyle(TableStyle(style2))
    story.append(table)

    story.append(Spacer(0, 50))

    #table=Table(bond_data)
    #table.setStyle(TableStyle(style2))
    #story.append(table)

    #page 5
    #story.append(PageBreak())
    story.append(Paragraph("Net Position", styleH))
    story.append(Paragraph("As of " + str(portfolioDate), styleContent))
    story.append(Spacer(0, 20))
    story.append(HRFlowable(width='100%', thickness=1, color=colors.black))
    story.append(Spacer(0, 20))

    table1 = Table(netPosition)
    table1.setStyle(style)
    story.append(table1)

    doc.addPageTemplates([
        coverPage,
        threeTemplate,
        columnTemplate,
    ])
    doc.build(story)
コード例 #39
0
def form_01(request_data):
    """
    форма Пасопрт здоровья Приказ Министерства здравоохранения и социального развития РФ от 12 апреля 2011 г. N 302н
    """
    ind_card = Card.objects.get(pk=request_data["card_pk"])
    ind = ind_card.individual
    ind_doc = Document.objects.filter(individual=ind, is_active=True)

    hospital_name = "ОГАУЗ \"Иркутская медикосанитарная часть № 2\""
    hospital_address = "г. Иркутс, ул. Байкальская 201"
    hospital_kod_ogrn = "1033801542576"
    health_passport_num = "1"  # номер id patient из базы

    individual_sex = ind.sex
    individual_fio = ind.fio()
    individual_date_born = ind.bd()

    documents = forms_func.get_all_doc(ind_doc)
    document_passport_num = documents['passport']['num']
    document_passport_serial = documents['passport']['serial']
    document_passport_date_start = documents['passport']['date_start']
    document_passport_issued = documents['passport']['issued']
    document_polis = documents['polis']['num']
    document_snils = documents['snils']['num']

    indivudual_insurance_org = "38014_ИРКУТСКИЙ ФИЛИАЛ АО \"СТРАХОВАЯ КОМПАНИЯ \"СОГАЗ-МЕД\" (Область Иркутская)"
    individual_benefit_code = "_________"

    # card_attr = forms_func.get_card_attr(ind_card)
    ind_card_address = ind_card.main_address

    individual_work_organization = "Управление Федераньной службы по ветеринарному и фитосанитрному надзору по Иркутской области" \
                                   "и Усть-Ордынскому бурятскому автономному округу"  # реест организаций
    work_organization_okved = "91.5 - Обслуживание и ремонт компютерной и оргтехники, заправка картриджей" \
                              "обслуживание принтеров"
    individual_department = "отдел информационных технология, ораганизаци ремонта и обслуживания медицинского оборудования"
    individual_profession = "старший государственный таможенный инспектор"  # реест профессий

    list_result = [
        'Общ. анализ крови', 'Общ.анализ мочи', 'Глюкоза крови', 'Холестерин',
        'RW', 'Флюорография', 'ЭКГ', 'Спирометрия', 'УЗИ м/желёз (маммогр.)',
        'Аудиометрия', 'УЗИ огр.м/таза', 'Исслед. вестибулярн. аппарата',
        'Исслед.вибрационн. чувствительности', 'Острота зрения',
        'Рефрактометрия', 'Объём аккомодации', 'Исслед.бинокулярн. зрения',
        'Цветоощущение', 'Офтальмотонометрия', 'Биомикроскопия сред глаза',
        'Поля зрения', 'Бактериоскопия мазка', 'Офтальмоскопия глазного дня',
        'Мазок из зева и носа', 'Ретикулоциты', 'АЛК или КП в моче',
        'Метгемоглобины', 'Базальн. Зернист. Эритроцитов'
    ]  # список лабораторных, инструментальных исследований
    list_doctor = [
        'Терапевт', 'Психиатр', 'Нарколог', 'Гинеколог', 'Офтальмолог', 'Лор',
        'Невролог', 'Дерматолог', 'Хирург', 'Стоматолог'
    ]  # список врачей-специалистов

    for i in range(0, 3):
        list_doctor.append('')

    if sys.platform == 'win32':
        locale.setlocale(locale.LC_ALL, 'rus_rus')
    else:
        locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')

    pdfmetrics.registerFont(
        TTFont('PTAstraSerifBold',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf')))
    pdfmetrics.registerFont(
        TTFont('PTAstraSerifReg',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf')))
    # http://www.cnews.ru/news/top/2018-12-10_rossijskim_chinovnikam_zapretili_ispolzovat
    # Причина PTAstraSerif использовать

    buffer = BytesIO()

    doc = SimpleDocTemplate(buffer,
                            pagesize=A4,
                            leftMargin=10 * mm,
                            rightMargin=10 * mm,
                            topMargin=10 * mm,
                            bottomMargin=10 * mm,
                            allowSplitting=1,
                            title="Форма {}".format("Паспорт здоровья"))
    width, height = landscape(A4)
    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "PTAstraSerifBold"
    style.fontSize = 9
    style.leading = 6
    styleBold = deepcopy(style)
    styleBold.fontName = "PTAstraSerifBold"
    styleCenter = deepcopy(style)
    styleCenter.alignment = TA_CENTER
    styleCenterBold = deepcopy(styleBold)
    styleCenterBold.alignment = TA_CENTER
    styleJustified = deepcopy(style)
    styleJustified.alignment = TA_JUSTIFY
    styleJustified.spaceAfter = 4.5 * mm
    styleJustified.fontSize = 12
    styleJustified.leading = 4.5 * mm

    righ_frame = Frame(148.5 * mm,
                       0 * mm,
                       width=148.5 * mm,
                       height=210 * mm,
                       leftPadding=10 * mm,
                       bottomPadding=6,
                       rightPadding=10 * mm,
                       topPadding=6,
                       showBoundary=1)
    left_frame = Frame(0 * mm,
                       0 * mm,
                       width=148.5 * mm,
                       height=210 * mm,
                       leftPadding=10 * mm,
                       bottomPadding=6,
                       rightPadding=10 * mm,
                       topPadding=6,
                       showBoundary=1)
    doc.addPageTemplates(
        PageTemplate(id='TwoCol',
                     frames=[righ_frame, left_frame],
                     pagesize=landscape(A4)))

    space = 5.5 * mm
    objs = [
        Spacer(1, 3 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold">Министерство здравоохранения Российской Федерации</font>',
            styleCenter),
        Spacer(1, 3 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold"><u>{}</u></font>'.format(
                hospital_name), styleCenter),
        Spacer(1, 2 * mm),
        Paragraph(
            '<font face="PTAstraSerifReg"><font size=9>(наименование медицинской организации)</font></font>',
            styleCenter),
        Spacer(1, 3 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold"><u>{}</u></font>'.format(
                hospital_address), styleCenter),
        Spacer(1, 5 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold" size=12>Код ОГРН {}</font>'.format(
                hospital_kod_ogrn), styleCenter),
        Spacer(1, 10 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold" size=12>ПАСПОРТ ЗДОРОВЬЯ РАБОТНИКА № <u>{}</u></font>'
            .format(health_passport_num), styleCenter),
        Spacer(1, space),
        Paragraph(
            '<font face="PTAstraSerifReg"size=10><u>{} года</u></font>'.format(
                pytils.dt.ru_strftime(u"%d %B %Y",
                                      inflected=True,
                                      date=datetime.datetime.now())),
            styleCenter),
        Spacer(1, 7),
        Paragraph(
            '<font face="PTAstraSerifReg" size=7>(дата оформления)</font>',
            styleCenter),
        Spacer(1, space),
        Paragraph(
            '<font face="PTAstraSerifReg">1.Фамилия, имя, отчество:'
            '<u>{}</u> </font>'.format(individual_fio), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">2.Пол: <u>{}</u> <img src="forms/img/FFFFFF-space.png" width="90" />'
            '3.Дата Рождения: <u>{}</u> </font>'.format(
                individual_sex, individual_date_born), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">4.Паспорт: серия <u>{}</u> <img src="forms/img/FFFFFF-space.png" width="25"/>'
            'номер: <u>{}</u></font>'.format(document_passport_serial,
                                             document_passport_num),
            styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">Дата выдачи: <u>{}</u></font>'.
            format(document_passport_date_start), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg"> Кем Выдан: <u>{}</u></font>'.format(
                document_passport_issued), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">5. Адрес регистрации по месту жительства (пребывания):'
            ' <u>{}</u></font>'.format(ind_card_address), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">6. Номер страхового полиса(ЕНП):'
            ' <u>{}</u></font>'.format(document_polis), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">7. Наименование работодателя:'
            ' <u>{}</u></font>'.format(individual_work_organization),
            styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">7.1 Форма собственности и вид экономической деятельности '
            'работодателя по ОКВЭД: <u>{}</u></font>'.format(
                work_organization_okved), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">7.2  Наименование структурного подразделения (цех, участок, отдел):'
            ' <u> {} </u></font>'.format(individual_department),
            styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">8. Профессия (должность) (в настоящее время):'
            ' <u>{}</u></font>'.format(individual_profession), styleJustified),
        FrameBreak(),
        Spacer(1, space),
        Paragraph('<font face="PTAstraSerifReg">12. Заключение:</font>',
                  styleJustified),
    ]
    styleT = deepcopy(style)
    styleT.alignment = TA_CENTER
    styleT.fontSize = 10
    styleT.leading = 4.5 * mm

    opinion = [
        [
            Paragraph(
                '<font face="PTAstraSerifReg">Заключение по результатам предварительного '
                'и периодического медицинского осмотра</font>', styleT),
            Paragraph(
                '<font face="PTAstraSerifReg">Дата получения заключения</font>',
                styleT),
            Paragraph(
                '<font face="PTAstraSerifReg"> Подпись профпатолога</font>',
                styleT)
        ],
    ]

    for i in range(0, 5):
        para = [
            Paragraph(
                '<font face="PTAstraSerifReg" size=11>Профпригоден/\nпрофнепригоден</font>',
                styleT)
        ]
        opinion.append(para)

    tbl = Table(opinion,
                colWidths=(48 * mm, 40 * mm, 40 * mm),
                hAlign='LEFT',
                style=[
                    ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('TOPPADDING', (0, 0), (-1, -1), 1.5 * mm),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm),
                ])

    objs.append(tbl)

    objs.append(Spacer(1, 10 * mm))
    objs.append(
        Paragraph('<font face="PTAstraSerifReg">Для заметок:</font>',
                  styleJustified))

    s = "___________________________________________________________"
    for i in range(0, 6):
        objs.append(Spacer(1, 1 * mm))
        objs.append(
            Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(s),
                      styleJustified))

    objs.append(NextPageTemplate("TwoCol"))
    objs.append(FrameBreak())
    objs.append(Spacer(1, 7 * mm))
    objs.append(
        Paragraph(
            '<font face="PTAstraSerifReg">11. Результаты лабораторных и инструментальных исследований'
            '</font>', styleJustified))

    tbl_result = [[
        Paragraph(
            '<font face="PTAstraSerifReg" size=11>Вид исследования</font>',
            styleT),
        Paragraph(
            '<font face="PTAstraSerifReg" size=11>Даты исследований</font>',
            styleT), '', '', '', ''
    ], ['', '', '', '', '', '']]

    styleTR = deepcopy(styleT)
    styleTR.alignment = TA_LEFT
    styleTR.fontSize = 11
    styleTR.spaceAfter = 12 * mm

    for i in list_result:
        para = [
            Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(i),
                      styleTR)
        ]
        tbl_result.append(para)

    tbl = Table(tbl_result,
                colWidths=(41 * mm, 22 * mm, 17 * mm, 17 * mm, 17 * mm,
                           17 * mm),
                hAlign='LEFT',
                style=[
                    ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('SPAN', (0, 0), (0, 1)),
                    ('SPAN', (1, 0), (-1, 0)),
                ])
    objs.append(tbl)

    objs.append(FrameBreak())
    objs.append(Spacer(1, 7 * mm))
    objs.append(
        Paragraph(
            '<font face="PTAstraSerifReg">9. Условия труда в настоящее время</font>',
            styleJustified))

    tbl_result = [[
        Paragraph(
            '<font face="PTAstraSerifReg" size=10>Наименование производственного фактора, вида работы с '
            'указанием пункта</font>', styleT),
        Paragraph(
            '<font face="PTAstraSerifReg" size=10>Стаж работы с фактором</font>',
            styleT),
    ]]
    for i in range(0, 4):
        para = ['', '']
        tbl_result.append(para)

    row_height = []
    for i in tbl_result:
        row_height.append(8 * mm)

    row_height[0] = None
    tbl = Table(tbl_result,
                colWidths=(75 * mm, 55 * mm),
                rowHeights=row_height,
                hAlign='LEFT',
                style=[
                    ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('LEFTPADDING ', (0, 2), (0, -1), 0.1 * mm),
                    ('SPAN', (1, 1), (1, -1)),
                ])

    objs.append(tbl)

    objs.append(Spacer(1, 5 * mm))

    styleDoc = deepcopy(styleJustified)
    styleDoc.spaceAfter = 1 * mm
    objs.append(
        Paragraph(
            '<font face="PTAstraSerifReg">10. Заключения врачей - специалистов:</font>',
            styleDoc,
        ))
    tbl_result = [[
        Paragraph(
            '<font face="PTAstraSerifReg" size=11>Врач-специалист</font>',
            styleT),
        Paragraph(
            '<font face="PTAstraSerifReg" size=11>Даты исследований</font>',
            styleT), '', '', '', ''
    ], ['', '', '', '', '', '']]

    for i in list_doctor:
        para = [
            Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(i),
                      styleTR)
        ]
        tbl_result.append(para)

    row_height = []
    for i in tbl_result:
        row_height.append(9 * mm)

    row_height[0] = None
    row_height[1] = None
    tbl = Table(tbl_result,
                colWidths=(41 * mm, 22 * mm, 17 * mm, 17 * mm, 17 * mm,
                           17 * mm),
                rowHeights=row_height,
                hAlign='LEFT',
                style=[
                    ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('LEFTPADDING ', (0, 2), (0, -1), 0.1 * mm),
                    ('SPAN', (0, 0), (0, 1)),
                    ('SPAN', (1, 0), (-1, 0)),
                ])
    objs.append(tbl)

    doc.build(objs)

    pdf = buffer.getvalue()
    buffer.close()
    return pdf
コード例 #40
0
class Documento(object):
    def __init__(self,
                 orientacion='landscape',
                 fichero='pictos.pdf',
                 compression=None,
                 texto=False):
        if orientacion == 'landscape':
            _pagesize = pagesize = landscape(A4)
        else:
            _pagesize = A4

        self.src = []
        '''
        self.author = 'Matronas y TCAE del H.U.Miguel Servet. Zaragoza'
        self.subject = 'Pictopartos'
        self.creator = 'https://pictopartos.es'
        self.keywords = ['pictos', 'matronas', 'auxiliares', 'partos', 'arasaac', 'HUMS', 'TCAE']
        '''
        '''
        if texto:
            self.doc = MiTemplate(fichero, pagesize=_pagesize,rightMargin=2*cm,
                leftMargin=1.5*cm,  topMargin=15 ,bottomMargin=15,
                showBoundary=1, pageCompression=compression)
        else:
        '''
        self.doc = SimpleDocTemplate(fichero,
                                     pagesize=_pagesize,
                                     rightMargin=2 * cm,
                                     leftMargin=1.5 * cm,
                                     topMargin=15,
                                     bottomMargin=15,
                                     showBoundary=1,
                                     pageCompression=compression)
        # container for the 'Flowable' objects
        #myframe = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.doc.width, self.doc.height, id='framepictos')
        #paginaTemplate = PageTemplate(id='Pagina', frames=[myframe]) #, onPage=self.add_default_info)
        # self.doc.addPageTemplates([paginaTemplate])
        self.elements = []  #[Spacer(1, 0)]
        self.padding_imagenes = 8
        self.get_stylesheet()
        self.alto = 0
        self.ancho = 0

        self._max_pictos = 0
        self.max_ancho = self.doc.width - 12
        self.max_alto = self.doc.height - 12

        #self.alto_imagen = self.max_ancho / 8 - self.padding_imagenes * 2

    def calc_alto_imagen(self):
        # espacios
        if self.num_lineas > 4:
            self.altura_espacio = 6
        else:
            self.altura_espacio = 12
        max_ancho_imagen = int(self.max_ancho / self.max_cols -
                               self.padding_imagenes * 2)
        max_alto_imagen = int((self.max_alto - self.num_titulos * 28 - \
            (self.num_lineas  - 1)  * self.altura_espacio * 2) / self.num_lineas - 24)
        self.alto_imagen = min(max_ancho_imagen, max_alto_imagen)

    def contar(self, datos):
        self.num_titulos = sum([1 for x in datos if x.get('titulo')])
        self.num_lineas = sum([1 for x in datos if x.get('linea')])
        lineas = [len(x.get('linea')) for x in datos if x.get('linea')]
        if lineas:
            self.max_cols = max(lineas)
        else:
            self.max_cols = 1

        self.calc_alto_imagen()

    def get_stylesheet(self):
        self.stylesheet = getSampleStyleSheet()
        self.stylesheet.byName['Normal'].fontName = 'Roboto'
        #self.stylesheet.byName['OrderedList'].fontName='Roboto'
        self.stylesheet.add(
            ParagraphStyle(name='titulo',
                           alignment=TA_CENTER,
                           parent=self.stylesheet['Normal'],
                           fontSize=18,
                           leading=24))
        self.stylesheet.add(
            ParagraphStyle(name='titulo_imagen',
                           alignment=TA_CENTER,
                           parent=self.stylesheet['Normal'],
                           fontSize=14,
                           fontName='Roboto'))
        self.stylesheet.add(
            ParagraphStyle(name="TituloPortada",
                           parent=self.stylesheet['Title'],
                           fontSize=42,
                           leading=52,
                           textColor=verde))
        self.stylesheet.add(
            ParagraphStyle(name="SubtituloPortada",
                           parent=self.stylesheet['Title'],
                           fontSize=20,
                           leading=28,
                           textColor=naranja))
        self.stylesheet.add(
            ParagraphStyle(name="EncabezaAutores",
                           parent=self.stylesheet['Normal'],
                           fontSize=12,
                           spaceAfter=6))
        self.stylesheet.add(
            ParagraphStyle(name="Lista",
                           parent=self.stylesheet['Normal'],
                           bulletColor=verde,
                           bulletFontSize=12,
                           bulletAnchor='start',
                           bulletIndent=4,
                           bulletOffsetY=0,
                           bulletType=1,
                           leftIndent=2,
                           rightIndent=0,
                           textColor=naranja))

    def parrafo(self, contenido, estilo=None, size='', add=True):
        if size:
            size = 'size={}'.format(size)
        if estilo:
            _estilo = self.stylesheet[estilo]
        else:
            _estilo = self.stylesheet['Normal']
        p = Paragraph('<font {}>{}</font>'.format(size, contenido),
                      style=_estilo)
        ancho, alto = p.wrap(self.doc.width, self.doc.height)
        if add:
            self.alto += alto + p.getSpaceAfter()
            self.elements.append(p)
        else:
            return p

    def espacio(self, ancho=100, alto=24):
        s = Spacer(ancho, alto)
        ancho, alto = s.wrap(self.doc.width, self.doc.height)
        self.alto += alto
        self.elements.append(s)

    def num_titulos(self):
        return len([x for x in self.elements if isinstance(x, Paragraph)])

    def num_filas_pictos(self):
        return len([x for x in self.elements if isinstance(x, Table)])

    def ajustar(self):
        #frame = self.doc.pageTemplate.frames[0]
        #self.max_ancho = self.doc.width - frame._leftPadding - frame._rightPadding
        #self.max_alto = self.doc.height - frame._topPadding - frame._bottomPadding
        self.max_ancho = self.doc.width - 12
        self.max_alto = self.doc.height - 12

        titulos = self.num_titulos()
        lineas = self.num_filas_pictos()
        altura = self.calc_altura()

        if altura > max_alto:
            pass
        else:
            pass

    def calc_altura(self, elements=None, ancho=None):
        if not ancho:
            ancho = self.doc.width - 12
        if not elements:
            elements = self.elements
        total = sum([x.wrap(ancho, self.doc.height)[1] for x in elements])
        total += sum(6 for x in elements if isinstance(x, Paragraph))
        return total

    def alturas(self):
        print([
            x.wrap(self.doc.width - 12, self.doc.height)[1]
            for x in self.elements
        ])

    def anchuras(self):
        print([
            x.wrap(self.doc.width, self.doc.height)[0] for x in self.elements
        ])

    def imagen_max(self):
        pass

    def quita_espacios(self):
        self.elements = [e for e in self.elements if not isinstance(e, Spacer)]

    def construir(self):
        #self.quita_espacios()
        if self.elements and isinstance(self.elements[-1], Spacer):
            self.elements.pop()
        espacios = [e for e in self.elements if isinstance(e, Spacer)]
        #altura = self.doc.height - self.alto - 24
        #altura = altura/(len(espacios)+1)
        # altura = 3
        altura = self.calc_altura()
        if espacios:
            nespacios = len(espacios)
            alto_espacio = int((self.max_alto - altura) / nespacios)
            if nespacios < 3 and alto_espacio > 32:
                alto_espacio = int(alto_espacio * 0.7)
            # if self.altura_espacio > alto_espacio:
            self.altura_espacio = alto_espacio

        for e in espacios:
            e.height = self.altura_espacio
        altura = self.calc_altura()
        if altura < self.max_alto * 0.95:
            self.elements.insert(0, Spacer(1, int(self.max_alto - altura) / 2))

    def generar(self):
        self.doc.build(
            self.elements,
            onFirstPage=partial(self._vheader,
                                titulo=self.titulo,
                                logo1=BASE_PDF + "logos/salud.png",
                                logo2=BASE_PDF + "logos/arasaac.png"),
            onLaterPages=partial(self._vheader,
                                 titulo=self.titulo,
                                 logo1=BASE_PDF + "logos/salud.png",
                                 logo2=BASE_PDF + "logos/arasaac.png"))

    def generarwm(self, wm):
        #print('1 -> ', wm)
        self.doc.build(
            self.elements,
            onFirstPage=partial(self._vheader,
                                titulo=self.titulo,
                                marcadeagua='',
                                logo1=BASE_PDF + "logos/salud.png",
                                logo2=BASE_PDF + "logos/arasaac.png"),
            onLaterPages=partial(self._vheader,
                                 titulo=self.titulo,
                                 logo1=BASE_PDF + "logos/salud.png",
                                 logo2=BASE_PDF + "logos/arasaac.png"))
        #water=wm ))

    def generar_tapa(self):
        self.doc.build(
            self.elements,
            onFirstPage=partial(self._tapa,
                                logo1=BASE_PDF + "logos/salud.png",
                                logo2=BASE_PDF + "logos/arasaac.png"),
        )

    def linea(self, data):
        wim = data[0][0].drawWidth
        #print('ancho im -> ', wim, data[0][0].drawHeight )
        # colWidths = [wim + wim*0.4 ] * len(data)
        colWidths = [wim + self.padding_imagenes * 2] * len(
            data)  # imagen + padding
        #print ('col widths -> ', colWidths)
        t = Table(
            [data],
            colWidths=colWidths,
            style=[
                ('BOX', (0, 0), (-1, -1), 0.5, verde),  #colors.purple),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('FONTSIZE', (0, 0), (-1, -1), 10),
                #('FONTNAME', (0,0), (-1,0), 'Times-Bold'),
                #('BACKGROUND', (0,0), (-1,-1), colors.lightgrey)
                ('BOTTOMPADDING', (0, 0), (-1, -1), 9),
                ('TOPPADDING', (0, 0), (-1, -1), 3),
                ('LEFTPADDING', (0, 0), (-1, -1), self.padding_imagenes),
                ('RIGHTPADDING', (0, 0), (-1, -1), self.padding_imagenes),
            ])
        ancho, alto = t.wrap(self.doc.width, self.doc.height)
        self.alto += alto
        self.ancho = max(ancho, self.ancho)
        if self.elements and not isinstance(self.elements[-1], Paragraph):
            self.espacio(alto=0)
        self.elements.append(t)
        self.espacio(alto=0)

        return t

    def crea_titulo(self, texto):
        self.parrafo(texto, 'Title')

    @staticmethod
    def _vheader(canvas, doc, titulo, logo1=None, logo2=None, marcadeagua=''):
        #print('water en vheader', marcadeagua)
        # Save the state of our canvas so we can draw on it
        #canvas.setStrokeColor(lightgreen)
        canvas.setPageCompression(1)
        #canvas.setStrokeColorCMYK(1, 31, 0, 0)
        #canvas.setStrokeColorRGB(0, 0.7333333333333333, 0.6549019607843137 , 0.7)
        canvas.setStrokeColor(naranja)
        canvas.setLineWidth(1)
        canvas.saveState()
        canvas.setTitle(titulo)
        canvas.setSubject('Pictopartos')
        canvas.setAuthor('Matronas y TCAE del H.U.Miguel Servet. Zaragoza')
        canvas.setCreator('https://pictopartos.es')
        canvas.setKeywords([
            'pictos', 'matronas', 'auxiliares', 'partos', 'arasaac', 'HUMS',
            'TCAE'
        ])
        #canvas.translate(0,doc.height)
        canvas.rotate(-90)
        if logo1:
            #logo_salud = imagen(settings.STATICFILES_DIRS[0]+'/logos/salud.png', 28)
            logo_salud = imagen(logo1, 28)
            logo_salud.drawOn(canvas, -doc.height - doc.topMargin,
                              doc.width + doc.leftMargin + 16)
        if logo2:
            #logo_arasaac = imagen(settings.STATICFILES_DIRS[0]+'/logos/arasaac.png', 28)
            logo_arasaac = imagen(logo2, 28)
            logo_arasaac.drawOn(canvas,
                                -doc.topMargin - logo_arasaac.drawWidth,
                                doc.width + doc.leftMargin + 16)
        styles = getSampleStyleSheet()
        header = Paragraph(titulo, styles['Title'])
        header2 = Paragraph(
            'Pictopartos - Matronas y TCAE del HUMS. Pictogramas de @arasaac',
            styles['Italic'])
        w, h = header.wrap(doc.height, doc.leftMargin)
        header.drawOn(
            canvas, -doc.height - doc.topMargin, doc.width + doc.leftMargin +
            24)  #doc.leftMargin, doc.height + doc.topMargin - h + 12)
        w2, h2 = header2.wrap(doc.height, doc.leftMargin)
        header2.drawOn(
            canvas, -doc.height - doc.topMargin, doc.width + doc.leftMargin +
            4)  #doc.leftMargin, doc.height + doc.topMargin - h + 12)
        hr = HRFlowable(width='100%', thickness=0.2, color=naranja)
        hr.wrap(doc.height, doc.topMargin)
        hr.drawOn(canvas, -doc.height - doc.topMargin,
                  doc.width + doc.leftMargin)

        if marcadeagua:
            #print ('EStoy letra a 50')
            canvas.rotate(90)
            canvas.setFont("Courier-Bold", 46)
            canvas.setFillColor(naranja, 0.25)
            #This next setting with make the text of our
            #watermark gray, nice touch for a watermark.
            #canvas.setFillGray(0.2,0.2)
            #Set up our watermark document. Our watermark
            #will be rotated 45 degrees from the direction
            #of our underlying document.
            canvas.translate(500, 100)
            canvas.rotate(35)
            canvas.drawCentredString(45, 200, marcadeagua)
        canvas.restoreState()

    @staticmethod
    def _tapa(canvas, doc, logo1=None, logo2=None):
        # Save the state of our canvas so we can draw on it
        canvas.setStrokeColor(naranja)
        canvas.setLineWidth(1)
        canvas.saveState()
        canvas.setSubject('Pictopartos')
        canvas.setAuthor('Matronas y TCAE del H.U.Miguel Servet. Zaragoza')
        canvas.setCreator('https://pictopartos.es')
        canvas.setKeywords([
            'pictos', 'matronas', 'auxiliares', 'partos', 'arasaac', 'HUMS',
            'TCAE'
        ])
        if logo1:
            #logo_salud = imagen(settings.STATICFILES_DIRS[0]+'/logos/salud.png', 28)
            logo_salud = imagen(logo1, 52)
            logo_salud.drawOn(
                canvas, doc.leftMargin + 4,
                doc.height + doc.bottomMargin - logo_salud.drawHeight - 4)

        if logo2:
            #logo_arasaac = imagen(settings.STATICFILES_DIRS[0]+'/logos/arasaac.png', 28)
            logo_arasaac = imagen(logo2, 52)
            logo_arasaac.drawOn(
                canvas,
                doc.width + doc.leftMargin - logo_arasaac.drawWidth - 4,
                doc.height + doc.bottomMargin - logo_arasaac.drawHeight - 4)
        canvas.restoreState()

    def _vheaderp(canvas, doc, titulo, logo1=None, logo2=None):
        # Save the state of our canvas so we can draw on it
        canvas.setStrokeColor(verde)
        canvas.setLineWidth(1)
        canvas.saveState()
        canvas.setTitle(titulo)
        canvas.setSubject('Pictopartos')
        canvas.setAuthor('Matronas y TCAE del H.U.Miguel Servet. Zaragoza')
        canvas.setCreator('https://pictopartos.es')
        canvas.setKeywords([
            'pictos', 'matronas', 'auxiliares', 'partos', 'arasaac', 'HUMS',
            'TCAE'
        ])

        if logo1:
            #logo_salud = imagen(settings.STATICFILES_DIRS[0]+'/logos/salud.png', 28)
            logo_salud = imagen(logo1, 52)
            logo_salud.drawOn(canvas, doc.rightMargin, doc.height)
        if logo2:
            #logo_arasaac = imagen(settings.STATICFILES_DIRS[0]+'/logos/arasaac.png', 28)
            logo_arasaac = imagen(logo2, 52)
            logo_arasaac.drawOn(canvas, doc.width, doc.bottomMargin)
        #canvas.setFont("Courier", 20)
        #canvas.drawCentredString(300, -50, "Encabezado del documento")
        canvas.restoreState()

    def vertical(self):
        titleFrame_1 = Frame(0.5 * inch,
                             0.75 * inch,
                             7 * inch,
                             9 * inch,
                             id='col1',
                             showBoundary=0)
        titleTemplate_1 = PageTemplate(id='OneCol', frames=titleFrame_1)
        document.addPageTemplates([titleTemplate_1])

    def portada(self,
                titulo='Título del cuaderno',
                subtitulo='subtítulo del cuaderno',
                participantes=[]):
        encabezado = 'Pictogramas para la comunicación. Proyecto de mejora. 2017.'
        espacio = self.doc.height / 2 - 64
        _lineas = []
        _lineas.append(Spacer(1, espacio / 2))
        _lineas.append(Paragraph(encabezado, self.stylesheet['Title']))
        _lineas.append(Spacer(1, espacio / 2))
        _lineas.append(Paragraph(titulo, self.stylesheet['TituloPortada']))
        _lineas.append(Spacer(1, 32))
        _lineas.append(
            Paragraph(subtitulo, self.stylesheet['SubtituloPortada']))
        altura = self.calc_altura(_lineas)
        alto_autores = len(participantes) * 14 + 16
        alto_espacio = self.doc.height - altura - 12 - alto_autores
        _lineas.append(Spacer(1, alto_espacio))
        _lineas.append(
            Paragraph('Elaborado por:', self.stylesheet['EncabezaAutores']))
        for p in participantes:
            _lineas.append(
                Paragraph(p, self.stylesheet['Lista'], bulletText='•'))

        #_lineas.append(PageBreak())
        self.elements = _lineas  #+ self.elements

    def pagina_de_texto(self, texto):
        frame = Frame(self.doc.leftMargin + 3 * cm,
                      self.doc.bottomMargin + 7 * cm,
                      self.doc.width - 6 * cm,
                      12.5 * cm,
                      id='normal',
                      leftPadding=12,
                      bottomPadding=12,
                      rightPadding=12,
                      topPadding=12)
        frame2 = Frame(self.doc.leftMargin + 3 * cm,
                       self.doc.bottomMargin,
                       self.doc.width - 6 * cm,
                       6 * cm,
                       id='autores',
                       leftPadding=12,
                       bottomPadding=12,
                       rightPadding=12,
                       topPadding=12)

        template = PageTemplate(
            id='texto',
            frames=[frame, frame2],
            onPage=partial(self._vheader,
                           titulo=self.titulo,
                           logo1=BASE_PDF + "logos/salud.png",
                           logo2=BASE_PDF + "logos/arasaac.png",
                           marcadeagua="Servicio de Obstetricia H.U.M.S."))

        self.doc.addPageTemplates([template])
        self.elements.append(
            Paragraph('Nuestras metas', self.stylesheet['Heading2']))
        estilo_texto = self.stylesheet['Normal']
        estilo_texto.spaceAfter = 6
        for t in texto.split('\n'):
            p = Paragraph(t, self.stylesheet['Normal'])
            self.elements.append(p)

    def pagina_mejoras(self):
        self.titulo = 'Observaciones y mejoras'
        self.elements.append(
            Paragraph('Observaciones y mejoras', self.stylesheet['titulo']))
        self.elements.append(
            Paragraph(
                '<para align="center"><i>Espacio para anotar lo que pienses que no funciona bien o que se puede mejorar.</i></para>',
                self.stylesheet['Normal']))
        self.elements.append(HRFlowable())
        self.elements.append(Spacer(10, 36))
        for x in range(18):
            self.elements.append(HRFlowable())
            self.elements.append(Spacer(10, 24))
        self.elements.pop()