Example #1
0
        def prepare_first_page(canvas, document):
            p1 = Paragraph(presentation.title, styles['Heading'])
            p2 = Paragraph(
                presentation.owner.get_full_name(), styles['SubHeading'])
            avail_width = width - inch
            avail_height = height - inch
            w1, h1 = p1.wrap(avail_width, avail_height)
            w2, h2 = p2.wrap(avail_width, avail_height)
            f = Frame(
                inch / 2,
                inch / 2,
                width - inch,
                height - inch,
                leftPadding=0,
                bottomPadding=0,
                rightPadding=0,
                topPadding=0
            )
            f.addFromList([p1, p2], canvas)

            document.pageTemplate.frames[0].height -= h1 + h2 + inch / 2
            document.pageTemplate.frames[1].height -= h1 + h2 + inch / 2

            canvas.saveState()
            canvas.setStrokeColorRGB(0, 0, 0)
            canvas.line(
                width / 2, inch / 2, width / 2, height - inch - h1 - h2)
            canvas.restoreState()
Example #2
0
        def drawCard(index, item):
            p.saveState()
            p.translate(0, height / 3 * (2 - index % 3))

            # retrieve record while making sure it's accessible to presentation owner
            record = Record.filter_one_by_access(presentation.owner, item.record.id)

            if record:
                image = get_image_for_record(record, presentation.owner, 800, 800, passwords)
                if image:
                    p.drawImage(image, inch / 2, inch / 2, width=width / 2 - inch, height=height / 3 - inch,
                                preserveAspectRatio=True)
                f = Frame(width / 2 + inch / 2, inch / 2,
                          width=width / 2 - inch, height=height / 3 - inch,
                          leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0)
                data = []
                data.append(getParagraph('%s/%s' % (index + 1, len(items)), styles['SlideNumber']))
                values = item.get_fieldvalues(owner=request.user)
                for value in values:
                    v = value.value if len(value.value) < 100 else value.value[:100] + '...'

                    v = remove_rels_from_a_tags(v)

                    data.append(getParagraph('<b>%s:</b> %s' % (value.resolved_label, v), styles['Data']))
                annotation = item.annotation
                if annotation:
                    data.append(getParagraph('<b>%s:</b> %s' % ('Annotation', annotation), styles['Data']))
                data = filter(None, data)
                f.addFromList(data, p)
                if data:
                    p.setFont('Helvetica', 8)
                    p.setFillColorRGB(0, 0, 0)
                    p.drawRightString(width - inch / 2, inch / 2, '...')

            p.restoreState()
Example #3
0
def run():
    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styleH = styles['Heading1']
    story = []

    #for codeNames in code
    story.append(Paragraph('I2of5', styleN))
    story.append(I2of5(1234, barWidth = inch*0.02, checksum=0))
    story.append(Paragraph('MSI', styleN))
    story.append(MSI(1234))
    story.append(Paragraph('Codabar', styleN))
    story.append(Codabar("A012345B", barWidth = inch*0.02))
    story.append(Paragraph('Code 11', styleN))
    story.append(Code11("01234545634563"))
    story.append(Paragraph('Code 39', styleN))
    story.append(Standard39("A012345B%R"))
    story.append(Paragraph('Extended Code 39', styleN))
    story.append(Extended39("A012345B}"))
    story.append(Paragraph('Code93', styleN))
    story.append(Standard93("CODE 93"))
    story.append(Paragraph('Extended Code93', styleN))
    story.append(Extended93("L@@K! Code 93 :-)")) #, barWidth=0.005 * inch))
    story.append(Paragraph('Code 128', styleN))
    c=Code128("AB-12345678") #, barWidth=0.005 * inch)
    #print 'WIDTH =', (c.width / inch), 'barWidth =', (c.barWidth / inch)
    #print 'LQ =', (c.lquiet / inch), 'RQ =', (c.rquiet / inch)
    story.append(c)
    story.append(Paragraph('USPS FIM', styleN))
    story.append(FIM("A"))
    story.append(Paragraph('USPS POSTNET', styleN))
    story.append(POSTNET('78247-1043'))
    story.append(Paragraph('USPS 4 State', styleN))
    story.append(USPS_4State('01234567094987654321','01234567891'))

    from reportlab.graphics.barcode import createBarcodeDrawing
    story.append(Paragraph('EAN13', styleN))
    bcd = createBarcodeDrawing('EAN13', value='123456789012')
    story.append(bcd)
    story.append(Paragraph('EAN8', styleN))
    bcd = createBarcodeDrawing('EAN8', value='1234567')
    story.append(bcd)
    story.append(Paragraph('UPCA', styleN))
    bcd = createBarcodeDrawing('UPCA', value='03600029145')
    story.append(bcd)
    story.append(Paragraph('USPS_4State', styleN))
    bcd = createBarcodeDrawing('USPS_4State', value='01234567094987654321',routing='01234567891')
    story.append(bcd)

    story.append(Paragraph('Label Size', styleN))
    story.append(XBox((2.0 + 5.0/8.0)*inch, 1 * inch, '1x2-5/8"'))
    story.append(Paragraph('Label Size', styleN))
    story.append(XBox((1.75)*inch, .5 * inch, '1/2x1-3/4"'))
    c = Canvas('out.pdf')
    f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1)
    f.addFromList(story, c)
    c.save()
    print('saved out.pdf')
Example #4
0
    def __init__(self, filename, context, **kw):
        BaseDocTemplate.__init__(self, filename, **kw)
        self.toc_index = 0
        self.main_frame_attr = {'x1': self.leftMargin,
                                'y1': self.bottomMargin,
                                'width': self.width,
                                'height': self.height,
                                'id':'normal',
                                'showBoundary': self.showBoundary}

        # We keep the main frame reference to resize it during the build
        self.main_frame = Frame(**self.main_frame_attr)
        self.main_frame_change = False
        template_attrs = {'id': 'now', 'frames': [self.main_frame],
                          'pagesize': kw['pagesize']}
        page_template = PageTemplate(**template_attrs)
        self.platypus_header_calculate = False
        self.platypus_header_height = None
        self.platypus_footer = None
        self.context = context
        self.addPageTemplates([page_template])
        self.toc_high_level = self.context.toc_high_level

        self.frame_attr = {'leftPadding': 0, 'bottomPadding': 6,
                           'rightPadding': 0, 'topPadding': 6,
                           'showBoundary': 0}
        self.context = context
        # calculate width available
        self.width_available = self.width
        self.width_available -= self.frame_attr['leftPadding']
        self.width_available -= self.frame_attr['rightPadding']
    def write(self, canvas):
        """Writes the frame to the
        given canvas.

        @param canvas: reportlab.pdfgen.canvas.Canvas
        object that represents the canvas that the
        container should write the frame to.

        @return: None
        """
        self._check_canvas(canvas)
        self._check_start_point()

        frame = Frame(self._x, self._y, self._width, self._height,
                      topPadding=0, bottomPadding=0)
        frame.addFromList(self._components, canvas)
Example #6
0
    def __init__(self, pageSize=A3):
        id = 'simplepage'
        #frames = Frame(0, 0, pageSize[0], pageSize[1])
        pw = pageSize[0]
        ph = pageSize[1]
        frames = Frame(page_margin_left, page_margin_bottom,
                       pw - page_margin_left - page_margin_right,
                       ph - page_margin_top - page_margin_bottom)

        PageTemplate.__init__(self, id=id, frames=frames, pagesize=pageSize)
 def __init__(self, filename, **kw):
     self.allowSplitting = 0
     kw['showBoundary']=1
     BaseDocTemplate.__init__(self, filename, **kw)
     self.addPageTemplates(
             [
             PageTemplate('normal',
                     [Frame(inch, inch, 6.27*inch, 9.69*inch, id='first',topPadding=0,rightPadding=0,leftPadding=0,bottomPadding=0,showBoundary=ShowBoundaryValue(color="red"))],
                     ),
             ])
Example #8
0
 def __init__(
     self,
     container,
     x1,
     y1,
     width,
     height,
     leftPadding=6,
     bottomPadding=6,
     rightPadding=6,
     topPadding=6,
     id=None,
     showBoundary=0,
     overlapAttachedSpace=None,
     _debug=None,
 ):
     self.container = container
     self.onSidebar = False
     self.__s = '[%s, %s, %s, %s, %s, %s, %s, %s,]' % (
         x1,
         y1,
         width,
         height,
         leftPadding,
         bottomPadding,
         rightPadding,
         topPadding,
     )
     Frame.__init__(
         self,
         x1,
         y1,
         width,
         height,
         leftPadding,
         bottomPadding,
         rightPadding,
         topPadding,
         id,
         showBoundary,
         overlapAttachedSpace,
         _debug,
     )
 def __init__(self, filename, **kw):
     self.allowSplitting = 0
     BaseDocTemplate.__init__(self, filename, **kw)
     self.addPageTemplates(
             [
             PageTemplate('normal',
                     [Frame(inch, inch, 6.27*inch, 9.69*inch, id='first',topPadding=0,rightPadding=0,leftPadding=0,bottomPadding=0,showBoundary=ShowBoundaryValue(color="red"))],
                     onPage = onPage('normal'),
                     ),
             PageTemplate('auto',
                     [Frame(inch, inch, 6.27*inch, 9.69*inch, id='first',topPadding=0,rightPadding=0,leftPadding=0,bottomPadding=0,showBoundary=ShowBoundaryValue(color="red"))],
                     onPage = onPage('auto'),
                     autoNextPageTemplate = 'autoFollow',
                     ),
             PageTemplate('autoFollow',
                     [Frame(inch, inch, 6.27*inch, 9.69*inch, id='first',topPadding=0,rightPadding=0,leftPadding=0,bottomPadding=0,showBoundary=ShowBoundaryValue(color="red"))],
                     onPage = onPage('autoFollow'),
                     ),
             ])
Example #10
0
    def _build(self, doc, positions, component, meta):

        n = len(positions)
        idx = int(round(n / 2.))

        p1 = positions[:idx]
        p2 = positions[idx:]
        #
        m = self._make_meta_table(meta)
        t1 = self._make_table(p1)
        t2 = self._make_table(p2)

        t3 = self._make_notes_table(component)

        flowables = [
            m,
            Spacer(0, 5 * mm),
            ComponentFlowable(component=component),
            FrameBreak(),
            Spacer(0, 5 * mm), t1,
            FrameBreak(),
            Spacer(0, 5 * mm), t2,
            FrameBreak(), t3
        ]

        # make 3 frames top, lower-left, lower-right
        lm = doc.leftMargin
        bm = doc.bottomMargin + doc.height * .333

        fw = doc.width
        fh = doc.height * 0.666
        top = Frame(lm, bm, fw, fh)

        fw = doc.width / 2.
        fh = doc.height * 0.333
        bm = doc.bottomMargin
        lbottom = Frame(lm, bm, fw, fh)
        rbottom = Frame(lm + doc.width / 2., bm, fw, fh)

        frames = [top, lbottom, rbottom]
        template = self._new_page_template(frames)

        return flowables, (template, )
Example #11
0
 def __init__(self, filename, **kw):
     frame1 = Frame(1 * cm,
                    1 * cm,
                    18.5 * cm,
                    27 * cm,
                    id='F1',
                    showBoundary=False)
     self.allowSplitting = 0
     apply(BaseDocTemplate.__init__, (self, filename), kw)
     self.addPageTemplates(PageTemplate('normal', [frame1]))
Example #12
0
 def column_frame(left):
     return Frame(left,
                  inch / 2,
                  width=width / 2 - 0.75 * inch,
                  height=height - inch,
                  leftPadding=0,
                  bottomPadding=0,
                  rightPadding=0,
                  topPadding=0,
                  showBoundary=False)
Example #13
0
def make_doc_template(page_size,
                      filename,
                      document_title,
                      title: str,
                      supervisor: str,
                      document_header: str,
                      client: str,
                      document_subheader: str,
                      left_margin=0.5 * inch,
                      fonts: List[TTFont] = []) -> ADRDocTemplate:
    right_margin = top_margin = bottom_margin = 0.5 * inch
    page_box = GRect(0., 0., page_size[0], page_size[1])
    _, page_box = page_box.split_x(left_margin, direction='l')
    _, page_box = page_box.split_x(right_margin, direction='r')
    _, page_box = page_box.split_y(bottom_margin, direction='u')
    _, page_box = page_box.split_y(top_margin, direction='d')

    footer_box, page_box = page_box.split_y(0.25 * inch, direction='u')
    header_box, page_box = page_box.split_y(0.75 * inch, direction='d')
    title_box, report_box = header_box.split_x(3.5 * inch, direction='r')

    on_page_lambda = (
        lambda c, _: draw_header_footer(c,
                                        report_box,
                                        title_box,
                                        footer_box,
                                        title=title,
                                        supervisor=supervisor,
                                        document_subheader=document_subheader,
                                        client=client,
                                        doc_title=document_header))

    frames = [
        Frame(page_box.min_x, page_box.min_y, page_box.width, page_box.height)
    ]

    page_template = PageTemplate(id="Main",
                                 frames=frames,
                                 onPage=on_page_lambda)

    for font in fonts:
        pdfmetrics.registerFont(font)

    doc = ADRDocTemplate(filename,
                         title=document_title,
                         author=supervisor,
                         pagesize=page_size,
                         leftMargin=left_margin,
                         rightMargin=right_margin,
                         topMargin=top_margin,
                         bottomMargin=bottom_margin)

    doc.addPageTemplates([page_template])

    return doc
Example #14
0
    def draw(self):
        # set position for the frame
        self.pos_x, self.pos_y = self._get_current_position(self.canv)
        # XXX This is false, height=drawHeigh and drawHeight should take into
        # account the frame padding
        height = (self.drawHeight + self.frame_attrs['leftPadding'] +
                  self.frame_attrs['rightPadding'])
        width = (self.drawWidth + self.frame_attrs['topPadding'] +
                 self.frame_attrs['bottomPadding'])

        self.frame = Frame(self.pos_x, self.pos_y, width, height,
                           **self.frame_attrs)
        if self.overflow:
            # Hack, We lie by setting the new created frame as default frame
            # of the doc template
            # To avoid problems when calling keep_in_frame.wrap
            # See platypus.flowables "def _listWrapOn"
            _doctemplate = self.canv._doctemplate
            # save state
            current_frame = getattr(_doctemplate, 'frame', None)
            _doctemplate.frame = self.frame

            # Check if PTO is defined
            if self.pto_trailer or self.pto_header:
                ptocontainer = PTOContainer(self.div_story[:],
                                            self.pto_trailer, self.pto_header)
                ptocontainer.canv = self.canv
                pto_size = ptocontainer.wrap(self.drawWidth, self.drawHeight)
                # XXX Round the height to avoid problems with decimal
                if int(pto_size[1]) > int(self.drawHeight):
                    pto_story = ptocontainer.split(self.drawWidth,
                                                   self.drawHeight)
                    self.frame.addFromList(pto_story, self.canv)
                else:
                    self.frame.addFromList([self.keep_in_frame], self.canv)
            else:
                self.frame.addFromList([self.keep_in_frame], self.canv)
            # restore state
            if current_frame:
                _doctemplate.frame = current_frame
        else:
            self.frame.addFromList(self.div_story[:], self.canv)
Example #15
0
        def prepare_first_page(canvas, document):
            p1 = Paragraph(presentation.title, styles['Heading'])
            p2 = Paragraph(presentation.owner.get_full_name(), styles['SubHeading'])
            avail_width = width - inch
            # TODO: determine if the complaint about height being undeclared is just pycharm or if its a problem
            # if it is possibly a problem "it's better to be explicit" so refactor
            avail_height = height - inch
            w1, h1 = p1.wrap(avail_width, avail_height)
            w2, h2 = p2.wrap(avail_width, avail_height)
            f = Frame(inch / 2, inch / 2, width - inch, height - inch,
                      leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0)
            f.addFromList([p1, p2], canvas)

            document.pageTemplate.frames[0].height -= h1 + h2 + inch / 2
            document.pageTemplate.frames[1].height -= h1 + h2 + inch / 2

            canvas.saveState()
            canvas.setStrokeColorRGB(0, 0, 0)
            canvas.line(width / 2, inch / 2, width / 2, height - inch - h1 - h2)
            canvas.restoreState()
 def __init__(self, filename, **kw):
     BaseDocTemplate.__init__(self, filename, **kw)
     self.addPageTemplates(
         [
          PageTemplate(id='plain',
                       frames=[Frame(2.5*cm, 2.5*cm, 16*cm, 25*cm, id='F1')]
                       ),
          LeftPageTemplate(),
          RightPageTemplate()
         ]
         )
Example #17
0
    def multiBuild(self,
                   flowables,
                   onFirstPage=_doNothing,
                   onLaterPages=_doNothing):
        self._calc()  #in case we changed margins sizes etc
        frameFirst = Frame(2 * cm, 2 * cm, 17 * cm, 23 * cm, id='F1')
        frameLater = Frame(2.5 * cm, 2 * cm, 16 * cm, 24.5 * cm, id='F2')

        self.addPageTemplates([
            PageTemplate(id='First',
                         frames=frameFirst,
                         onPage=onFirstPage,
                         pagesize=self.pagesize),
            PageTemplate(id='Later',
                         frames=frameLater,
                         onPage=onLaterPages,
                         pagesize=self.pagesize)
        ])

        BaseDocTemplate.multiBuild(self, flowables)
Example #18
0
def HeaderFooter(canvas, doc):
    canvas.saveState()
    styleN = PS('nomal', fontName='Times-Roman', leading=9, fontSize=9)
    P = Paragraph("This is a multi-line footer or header", styleN)
    w, h = P.wrap(doc.width, doc.bottomMargin)
    #print doc.width, doc.bottomMargin
    #print w, h
    #print dir(doc)
    #print dir(canvas)
    global pageNum
    if doc.page < pageNum:
        global ChapterName
        ChapterName = 'Table of contents'

    #print doc.page
    #print ChapterName
    pageNum = doc.page

    if doc.page == 1:
        footerMsg = []
        footerMsg.append(Paragraph("Lei Yang", styleN))
        footerMsg.append(Paragraph("Wei Gao", styleN))
        footerMsg.append(Paragraph("XiangYu Dong", styleN))
        footerMsg.append(Paragraph("Liang Chi", styleN))
        footerMsg.append(Paragraph("Beijing ChaoYang, China", styleN))
        canvas.line(2.5*cm, h+50, w+2.5*cm, h+50)
        f = Frame(70, 2, 16*cm, 2.1*cm, showBoundary=0)
        f.addFromList(footerMsg,canvas)
    else:
        P = Paragraph("User Guide", styleN)
        w, h = P.wrap(doc.width, doc.bottomMargin)
        P.drawOn(canvas, doc.leftMargin, h+789)
        P = Paragraph(ChapterName, PS('nomal', fontName='Times-Roman', fontSize=9, alignment = TA_RIGHT, leading=9))
        w, h = P.wrap(doc.width, doc.bottomMargin)
        P.drawOn(canvas, doc.rightMargin, h+789)

        P = Paragraph("Page %d" % doc.page, PS('nomal', fontName='Times-Roman', fontSize=9, alignment = 1))
        w, h = P.wrap(doc.width, doc.bottomMargin)
        P.drawOn(canvas, doc.leftMargin, h)
        canvas.line(2.5*cm, h+780, w+2.5*cm, h+780)
    canvas.restoreState()
def myFirstPage(canvas, doc):
    canvas.saveState()
    canvas.setFont('Times-Bold', 16)
    canvas.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT-108, title)
    canvas.setFont('Times-Roman', 9)
    canvas.drawString(inch, 0.75 * inch, "Page %d - %s" % (doc.page, title))
    
    frame_width = PAGE_WIDTH-200
    hr = HRFlowable()
    space = Spacer(frame_width, 20)
    style = styles["Normal"]
    qr_info = """<para rightIndent=10 leftIndent=20 alignment=right>This document is signed with the QR code shown on the right. Validate it using a Barcode Scanner."""
    par = Paragraph(qr_info, style)
    im = Image("qrcode.png", 101, 101)
    pandi = ParagraphAndImage(par, im, xpad=3, ypad=30, side='right')
    
    frame = Frame(100, 0, frame_width, 200, showBoundary=1)
    frame.add(hr, canvas)
    frame.add(space, canvas)
    frame.add(pandi, canvas)
    canvas.restoreState()
Example #20
0
    def __init__(self, filename, **kw):
        frame1 = Frame(inch, inch, A4[0] - 2 * inch, A4[1] - 2 * inch, id='F1')
        self.allowSplitting = 0
        BaseDocTemplate.__init__(self, filename, **kw)
        template = PageTemplate('normal', [frame1], myMainPageFrame)
        self.addPageTemplates(template)

        top_margin = A4[1] - inch
        bottom_margin = inch
        left_margin = inch
        right_margin = A4[0] - inch
        frame_width = right_margin - left_margin
Example #21
0
    def __init__(self, filename, **kw):
        frame1 = Frame(2.5 * cm, 2.5 * cm, 15 * cm, 25 * cm, id='F1')
        self.allowSplitting = 0
        BaseDocTemplate.__init__(self, filename, **kw)
        template1 = PageTemplate('normal', [frame1], myMainPageFrame)

        frame2 = Frame(2.5 * cm,
                       16 * cm,
                       15 * cm,
                       10 * cm,
                       id='F2',
                       showBoundary=1)
        frame3 = Frame(2.5 * cm,
                       2.5 * cm,
                       15 * cm,
                       10 * cm,
                       id='F3',
                       showBoundary=1)

        template2 = PageTemplate('updown', [frame2, frame3])
        self.addPageTemplates([template1, template2])
Example #22
0
    def drawHeader(self):
        self.drawLogo()
        styles = getSampleStyleSheet()
        sN = styles['Normal']
        sH = styles['Heading1']

        sH.fontName = "OldEngMT"
        sH.textColor = red
        sH.leading = 18
        sH.fontSize = 16

        sN.fontSize = 9
        sN.leading = 10

        sN.alignment = sH.alignment = TA_CENTER
        sN.spaceBefore = sH.spaceBefore = 0
        sN.spaceAfter = sH.spaceAfter = 0

        story = []
        story.append(Paragraph("Holy Child Colleges of Butuan - Hospital", sH))
        story.append(Paragraph("<b>(JP Esteves Clinical Laboratory)</b>", sN))
        story.append(
            Paragraph("2nd St., Guingona Subd., " + "Butuan City, Philippines",
                      sN))
        story.append(Paragraph("Tel. No.: +63 (85) 342-5186", sN))
        story.append(Paragraph("Telefax No.: +63 (95) 342-397/225-6872", sN))
        story.append(Paragraph("email: [email protected]", sN))

        w, h = self.pagesize
        f = Frame(0, h - self.topMargin, w, self.topMargin, showBoundary=False)
        f.addFromList(story, self.canv)

        self.canv.setStrokeColor(red)
        self.canv.setLineWidth(3)
        self.canv.line(
            0.15 * cm,
            h - self.topMargin,
            w - 0.15 * cm,
            h - self.topMargin,
        )
Example #23
0
    def __init__(self, filename, context, **kw):
        BaseDocTemplate.__init__(self, filename, **kw)
        self.toc_index = 0
        self.main_frame_attr = {
            'x1': self.leftMargin,
            'y1': self.bottomMargin,
            'width': self.width,
            'height': self.height,
            'id': 'normal',
            'showBoundary': self.showBoundary
        }

        # We keep the main frame reference to resize it during the build
        self.main_frame = Frame(**self.main_frame_attr)
        self.main_frame_change = False
        template_attrs = {
            'id': 'now',
            'frames': [self.main_frame],
            'pagesize': kw['pagesize']
        }
        page_template = PageTemplate(**template_attrs)
        self.platypus_header_calculate = False
        self.platypus_header_height = None
        self.platypus_footer = None
        self.context = context
        self.addPageTemplates([page_template])
        self.toc_high_level = self.context.toc_high_level

        self.frame_attr = {
            'leftPadding': 0,
            'bottomPadding': 6,
            'rightPadding': 0,
            'topPadding': 6,
            'showBoundary': 0
        }
        self.context = context
        # calculate width available
        self.width_available = self.width
        self.width_available -= self.frame_attr['leftPadding']
        self.width_available -= self.frame_attr['rightPadding']
Example #24
0
def set_basic_templates(doc):
    from reportlab.platypus.frames import Frame
    from reportlab.platypus.doctemplate import PageTemplate
    from reportlab.lib.units import cm

    doc._calc()  #taken from reportlab source code (magic)

    templates = []

    #the front page framing
    cover_frame = Frame(doc.leftMargin,
                        doc.bottomMargin,
                        doc.width,
                        doc.height,
                        leftPadding=0,
                        rightPadding=10,
                        topPadding=3 * cm,
                        bottomPadding=5 * cm)
    templates.append(
        PageTemplate(id='Cover',
                     frames=cover_frame,
                     onPage=_cover_page,
                     pagesize=doc.pagesize))

    #normal frame, for the TOC
    frame = Frame(doc.leftMargin,
                  doc.bottomMargin,
                  doc.width,
                  doc.height,
                  id='normal',
                  rightPadding=0,
                  leftPadding=0)
    templates.append(
        PageTemplate(id='TOC',
                     frames=frame,
                     onPage=toc_page,
                     pagesize=doc.pagesize))

    doc.addPageTemplates(templates)
    def __init__(self, id=-1, pageSize=TAILLE_PAGE, doc=None):
        self.pageWidth = pageSize[0]
        self.pageHeight = pageSize[1]
        
##        # Récupère les coordonnées du cadre principal
##        cadre_principal = doc.modeleDoc.FindObjet("cadre_principal")
##        x, y, l, h = doc.modeleDoc.GetCoordsObjet(cadre_principal)
##        global CADRE_CONTENU
##        CADRE_CONTENU = (x, y, l, h)
        
        x, y, l, h = 0, 0, self.pageWidth, self.pageHeight
        frame1 = Frame(x, y, l, h, id='F1', leftPadding=0, topPadding=0, rightPadding=0, bottomPadding=0)
        PageTemplate.__init__(self, id, [frame1], Template) 
Example #26
0
    def __init__(self, filename, **kw):
        frame1 = Frame(2.5 * cm, 2.5 * cm, 15 * cm, 25 * cm, id='F1')
        self.allowSplitting = 0
        BaseDocTemplate.__init__(self, filename, **kw)
        template1 = PageTemplate('normal', [frame1], myMainPageFrame)

        frame2 = Frame(2.5 * cm,
                       16 * cm,
                       15 * cm,
                       10 * cm,
                       id='F2',
                       showBoundary=1)
        frame3 = Frame(2.5 * cm,
                       2.5 * cm,
                       15 * cm,
                       10 * cm,
                       id='F3',
                       showBoundary=1)

        greenBoundary = ShowBoundaryValue(color=toColor('darkgreen'),
                                          width=0.5)
        templateX = PageTemplate('templateX', [
            Frame(3 * cm,
                  7.5 * cm,
                  14 * cm,
                  4 * cm,
                  id='XF4',
                  showBoundary=greenBoundary),
            Frame(3 * cm,
                  2.5 * cm,
                  14 * cm,
                  4 * cm,
                  id='XF5',
                  showBoundary=greenBoundary)
        ])

        template2 = PageTemplate('updown', [frame2, frame3])
        self.addPageTemplates([template1, template2, templateX])
Example #27
0
    def build(self,
              flowables,
              onFirstPage=_doNothing,
              onLaterPages=_doNothing,
              canvasmaker=Canvas):
        #Override the build method
        self._calc()  #in case we changed margins sizes etc
        self.canvas = canvasmaker
        firstFrame = Frame(
            10,  # X
            0,  # Y
            A4[0] - 20,  # width
            A4[1] - 106,  # height
            id='normal')

        secondFrame = Frame(
            10,  # X
            0,  # Y
            A4[0] - 20,  # width
            A4[1] - 46,  # height
            #showBoundary=True,
            id='normal')

        self.addPageTemplates([
            PageTemplate(id='First',
                         frames=[firstFrame],
                         pagesize=self.pagesize,
                         onPage=onFirstPage),
            PageTemplate(id='Later',
                         frames=[secondFrame],
                         pagesize=self.pagesize,
                         onPage=onLaterPages),
        ])
        if onFirstPage is _doNothing and hasattr(self, 'onFirstPage'):
            self.pageTemplates[0].beforeDrawPage = self.onFirstPage
        if onLaterPages is _doNothing and hasattr(self, 'onLaterPages'):
            self.pageTemplates[1].beforeDrawPage = self.onLaterPages
        BaseDocTemplate.build(self, flowables, canvasmaker=canvasmaker)
Example #28
0
 def build(self, flowables):
     self._calc()  #in case we changed margins sizes etc
     frameT = Frame(self.leftMargin,
                    self.bottomMargin,
                    self.width,
                    self.height,
                    id='normal',
                    leftPadding=0,
                    bottomPadding=0,
                    rightPadding=0,
                    topPadding=0)
     self.addPageTemplates(
         [PageTemplate(id='First', frames=frameT, pagesize=self.pagesize)])
     BaseDocTemplate.build(self, flowables, canvasmaker=self._canvasMaker)
Example #29
0
 def multiBuild(self,
                story,
                filename=None,
                canvasMaker=Canvas,
                maxPasses=10,
                onFirstPage=_doNothing,
                onLaterPages=_doNothing):
     self._calc()  #in case we changed margins sizes etc
     frameT = Frame(self.leftMargin,
                    self.bottomMargin,
                    self.width,
                    self.height,
                    id='normal')
     self.addPageTemplates([
         PageTemplate(id='Later',
                      frames=frameT,
                      onPageEnd=onLaterPages,
                      pagesize=self.pagesize)
     ])
     if onLaterPages is _doNothing and hasattr(self, 'onLaterPages'):
         self.pageTemplates[0].beforeDrawPage = self.onLaterPages
     SimpleDocTemplate.multiBuild(self,
                                  story,
                                  maxPasses,
                                  canvasmaker=canvasMaker)
     self._prepareTOC()
     contentFile = self.filename
     self.filename = FileDummy()
     self.pageTemplates = []
     self.addPageTemplates([
         PageTemplate(id='First',
                      frames=frameT,
                      onPage=onFirstPage,
                      pagesize=self.pagesize)
     ])
     if onFirstPage is _doNothing and hasattr(self, 'onFirstPage'):
         self.pageTemplates[0].beforeDrawPage = self.onFirstPage
     self.addPageTemplates([
         PageTemplate(id='Later',
                      frames=frameT,
                      onPageEnd=self.laterPages,
                      pagesize=self.pagesize)
     ])
     if onLaterPages is _doNothing and hasattr(self, 'onLaterPages'):
         self.pageTemplates[1].beforeDrawPage = self.onLaterPages
     SimpleDocTemplate.multiBuild(self,
                                  self._tocStory,
                                  maxPasses,
                                  canvasmaker=canvasMaker)
     self.mergePDFs(self.filename, contentFile)
Example #30
0
    def drawHeader(self):
        self.drawLogo()
        styles = getSampleStyleSheet()
        sN = styles['Normal']
        sH = styles['Heading1']

        sH.fontName = "OldEngMT"
        sH.textColor = red
        sH.leading = 18
        sH.fontSize = 16

        sN.fontSize = 9
        sN.leading = 10

        sN.alignment = sH.alignment = TA_CENTER
        sN.spaceBefore = sH.spaceBefore = 0
        sN.spaceAfter = sH.spaceAfter = 0

        story = []
        story.append(Paragraph("Holy Child Colleges of Butuan - Hospital", sH))
        story.append(Paragraph("<b>(JP Esteves Clinical Laboratory)</b>", sN))
        story.append(Paragraph("2nd St., Guingona Subd., " +
                               "Butuan City, Philippines", sN))
        story.append(Paragraph("Tel. No.: +63 (85) 342-5186", sN))
        story.append(Paragraph("Telefax No.: +63 (95) 342-397/225-6872", sN))
        story.append(Paragraph("email: [email protected]", sN))

        w, h = self.pagesize
        f = Frame(0, h-self.topMargin, w, self.topMargin,
                  showBoundary=False)
        f.addFromList(story, self.canv)

        self.canv.setStrokeColor(red)
        self.canv.setLineWidth(3)
        self.canv.line(0.15*cm, h-self.topMargin,
                       w-0.15*cm, h-self.topMargin,
                       )
Example #31
0
    def createFrame(self,
                    frame_id="Portrait",
                    x1=0.,
                    y1=0.,
                    width=0.,
                    height=0.,
                    left_padding=0.,
                    bottom_padding=0.,
                    right_padding=0.,
                    top_padding=0.,
                    overlap=None):
        """
        Frame reportlab internal signature::

                        width                    x2,y2
                +---------------------------------+
                | l  top_padding                r | h
                | e +-------------------------+ i | e
                | f |                         | g | i
                | t |                         | h | g
                |   |                         | t | h
                | p |                         |   | t
                | a |                         | p |
                | d |                         | a |
                |   |                         | d |
                |   +-------------------------+   |
                |    bottom padding               |
                +---------------------------------+
                (x1,y1) <-- lower left corner

        """
        def makeRandomId(length=3, chars=string.ascii_lowercase):
            """
            create a file id of lower case ascii characters with length
            """
            return ''.join(random.choice(chars) for _ in range(length))

        return Frame(x1,
                     y1,
                     width,
                     height,
                     leftPadding=left_padding,
                     bottomPadding=bottom_padding,
                     rightPadding=right_padding,
                     topPadding=top_padding,
                     id=f"{frame_id}_{makeRandomId()}",
                     showBoundary=self.showBoundary,
                     overlapAttachedSpace=overlap,
                     _debug=None)
Example #32
0
 def __init__(self, filename, **kw):
     BaseDocTemplate.__init__(self, filename, **kw)
     template = PageTemplate('normal', [
         Frame(0,
               0,
               A4[0],
               A4[1],
               leftPadding=31.8 * mm,
               bottomPadding=25.4 * mm,
               rightPadding=31.8 * mm,
               topPadding=25.4 * mm)
     ],
                             onPageEnd=self.footer)
     # 定义页面模版,页脚可有可无
     self.addPageTemplates(template)  # 加入页面模版
 def __init__(self, filename, **kw):
     self.allowSplitting = 0
     BaseDocTemplate.__init__(self, filename, **kw)
     frameT = Frame(self.leftMargin,
                    self.bottomMargin,
                    self.width,
                    self.height,
                    id='F1')
     template_title_page = PageTemplate('title_page',
                                        frames=frameT,
                                        onPage=title_page)
     template_later_pages = PageTemplate('later_pages',
                                         frames=frameT,
                                         onPage=later_pages)
     self.addPageTemplates(template_title_page)
     self.addPageTemplates(template_later_pages)
Example #34
0
    def __init__(self,
                 cover=None,
                 id=None,
                 onPage=_doNothing,
                 onPageEnd=_doNothing,
                 pagesize=(page_width, page_height)):

        id = 'TitlePage'
        frames = Frame(page_margin_left, page_margin_bottom, print_width,
                       print_height)
        PageTemplate.__init__(self,
                              id=id,
                              frames=frames,
                              onPage=onPage,
                              onPageEnd=onPageEnd,
                              pagesize=pagesize)
        self.cover = cover
Example #35
0
 def test5(self):
     '''extreme test inspired by Moritz Pfeiffer https://bitbucket.org/moritzpfeiffer/'''
     with self.assertRaises(LayoutError):
         text = """
         Clearly, the natural general principle that will subsume this case is
         not subject to a parasitic gap construction.  Presumably, most of the
         methodological work in modern linguistics can be defined in such a way
         as to impose the system of base rules exclusive of the lexicon.  In the
         discussion of resumptive pronouns following (81), the fundamental error
         of regarding functional notions as categorial is to be regarded as a
         descriptive <span color="red">fact</span>.<br/>So far, the earlier discussion of deviance is not
         quite equivalent to a parasitic gap construction.  To characterize a
         linguistic level L, a case of semigrammaticalness of a different sort
         may remedy and, at the same time, eliminate irrelevant intervening
         contexts in selectional <span color="red">rules</span>.<br/>
         Summarizing, then, we assume that the descriptive power of the base
         component can be defined in such a way as to impose nondistinctness in
         the sense of distinctive feature theory.
         """
         styleSheet = getSampleStyleSheet()
         story = []
         story.append(Paragraph(text, styleSheet['Normal']))
         doc = BaseDocTemplate(
             outputfile('test_platypus_much_too_large.pdf'),
             pagesize=portrait(A4),
             pageTemplates=[
                 PageTemplate(
                     'page_template',
                     [
                         Frame(0,
                               0,
                               0,
                               0,
                               leftPadding=0,
                               rightPadding=0,
                               topPadding=0,
                               bottomPadding=0,
                               id='DUMMY_FRAME')
                     ],
                 )
             ],
         )
         doc.build(story)
Example #36
0
    def draw(self):
        # set position for the frame
        self.pos_x, self.pos_y = self._get_current_position(self.canv)
        # XXX This is false, height=drawHeigh and drawHeight should take into
        # account the frame padding
        height = (self.drawHeight + self.frame_attrs['leftPadding'] +
                  self.frame_attrs['rightPadding'])
        width = (self.drawWidth + self.frame_attrs['topPadding'] +
                 self.frame_attrs['bottomPadding'])

        self.frame = Frame(self.pos_x, self.pos_y, width, height,
                           **self.frame_attrs)
        if self.overflow:
            # Hack, We lie by setting the new created frame as default frame
            # of the doc template
            # To avoid problems when calling keep_in_frame.wrap
            # See platypus.flowables "def _listWrapOn"
            _doctemplate = self.canv._doctemplate
            # save state
            current_frame = getattr(_doctemplate, 'frame', None)
            _doctemplate.frame = self.frame

            # Check if PTO is defined
            if self.pto_trailer or self.pto_header:
                ptocontainer = PTOContainer(self.div_story[:],
                                            self.pto_trailer, self.pto_header)
                ptocontainer.canv = self.canv
                pto_size = ptocontainer.wrap(self.drawWidth, self.drawHeight)
                # XXX Round the height to avoid problems with decimal
                if int(pto_size[1]) > int(self.drawHeight):
                    pto_story = ptocontainer.split(self.drawWidth,
                                                   self.drawHeight)
                    self.frame.addFromList(pto_story, self.canv)
                else:
                    self.frame.addFromList([self.keep_in_frame], self.canv)
            else:
                self.frame.addFromList([self.keep_in_frame], self.canv)
            # restore state
            if current_frame:
                _doctemplate.frame = current_frame
        else:
            self.frame.addFromList(self.div_story[:], self.canv)
Example #37
0
    def __init__(self, filename, cfgparser, **kw):
        self.allowSplitting = 0
        # Inch graph size (width, height)
        self.graph_size = (float(cfgparser.get("page", "graph_width")),
                           float(cfgparser.get("page", "graph_height")))
        self.x_axis = ('Time', 12, '%m-%d %H:%M', 20)
        self.tablestyle = [
            ('ROWBACKGROUNDS', (0, 0), (-1, -1), (colors.lightgrey, colors.white)),
            ('GRID', (0, 0), (-1, -1), 1, colors.toColor(cfgparser.get("string_table", "color"))),
            ('ALIGN', (0, 0), (-1, -1), cfgparser.get("string_table", "align")),
            ('LEFTPADDING', (0, 0), (-1, -1), int(cfgparser.get("string_table", "leftPadding"))),
            ('RIGHTPADDING', (0, 0), (-1, -1), int(cfgparser.get("string_table", "rightPadding"))),
            ('FONTSIZE', (0, 0), (-1, -1), int(cfgparser.get("string_table", "fontSize"))),
            ('FONTNAME', (0, 0), (-1, 0), cfgparser.get("string_table", "font")), ]
        BaseDocTemplate.__init__(self, filename, **kw)
        template = PageTemplate('normal', [Frame(
            float(cfgparser.get("page", "x1")) * inch,
            float(cfgparser.get("page", "y1")) * inch,
            float(cfgparser.get("page", "width")) * inch,
            float(cfgparser.get("page", "height")) * inch,
            id='F1')])
        self.addPageTemplates(template)

        font_list = ["centered", "centered_index", "small_centered",
                     "heading1", "heading1_centered", "heading1_invisible",
                     "heading2", "heading2_centered", "heading2_invisible",
                     "mono", "mono_centered", "normal", "front_title", "axes"]
        int_fields = ["fontSize", "leading", "alignment", "spaceAfter"]
        self.fonts = {}
        for font in font_list:
            sheet = getSampleStyleSheet()
            text = sheet['BodyText']
            section = "font_%s" % font
            items = dict(cfgparser.items(section))
            for i in int_fields:
                if i in items:
                    items[i] = int(items[i])

            tmp_ps = PS(font, parent=text)
            tmp_ps.__dict__.update(items)
            self.fonts[font] = tmp_ps
Example #38
0
    def __init__(self,
                 cover=None,
                 id=None,
                 onPage=_doNothing,
                 onPageEnd=_doNothing,
                 pagesize=(page_width, page_height)):

        id = 'TitlePage'
        p = pdfstyles
        frames = Frame(
            p.title_margin_left, p.title_margin_bottom,
            p.page_width - p.title_margin_left - p.title_margin_right,
            p.page_height - p.title_margin_top - p.title_margin_bottom)

        PageTemplate.__init__(self,
                              id=id,
                              frames=frames,
                              onPage=onPage,
                              onPageEnd=onPageEnd,
                              pagesize=pagesize)
        self.cover = cover
Example #39
0
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)
Example #40
0
    def build(self,flowables,onFirstPage=_doNothing, onLaterPages=_doNothing, canvasmaker=canvas.Canvas):
        """build the document using the flowables.  Annotate the first page using the onFirstPage
               function and later pages using the onLaterPages function.  The onXXX pages should follow
               the signature

                  def myOnFirstPage(canvas, document):
                      # do annotations and modify the document
                      ...

               The functions can do things like draw logos, page numbers,
               footers, etcetera. They can use external variables to vary
               the look (for example providing page numbering or section names).
        """
        self._calc()    #in case we changed margins sizes etc
        frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal')
        self.addPageTemplates([PageTemplate(id='First',frames=frameT, onPage=onFirstPage,pagesize=self.pagesize),
                        PageTemplate(id='Later',frames=frameT, onPage=onLaterPages,pagesize=self.pagesize)])
        if onFirstPage is _doNothing and hasattr(self,'onFirstPage'):
            self.pageTemplates[0].beforeDrawPage = self.onFirstPage
        if onLaterPages is _doNothing and hasattr(self,'onLaterPages'):
            self.pageTemplates[1].beforeDrawPage = self.onLaterPages
        BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker)
Example #41
0
    def build_pdf(self, response):

        cleaned_data = self.filterset.form.cleaned_data

        impresso = cleaned_data['impresso']

        fs = int(impresso.fontsize)
        if cleaned_data['fontsize']:
            fs = int(cleaned_data['fontsize'])

        stylesheet = StyleSheet1()
        stylesheet.add(ParagraphStyle(name='pronome_style',
                                      fontName="Helvetica",
                                      fontSize=fs * 0.8,
                                      leading=fs))
        stylesheet.add(ParagraphStyle(name='nome_style',
                                      fontName="Helvetica-Bold",
                                      fontSize=fs,
                                      leading=fs * 1.3))
        stylesheet.add(ParagraphStyle(name='endereco_style',
                                      fontName="Helvetica",
                                      fontSize=fs * 0.9,
                                      leading=fs))

        pagesize = (float(impresso.largura_pagina) * cm,
                    float(impresso.altura_pagina) * cm)

        ms = pagesize[1] - float(impresso.margem_superior) * cm
        me = float(impresso.margem_esquerda) * cm

        ae = float(impresso.alturaetiqueta) * cm
        le = float(impresso.larguraetiqueta) * cm

        el = float(impresso.entre_linhas) * cm
        ec = float(impresso.entre_colunas) * cm

        col = float(impresso.colunasfolha)
        row = float(impresso.linhasfolha)
        cr = int(col * row)

        p = canvas.Canvas(response, pagesize=pagesize)

        if impresso.rotate:
            p.translate(pagesize[1], 0)
            p.rotate(90)

        i = -1
        for contato in self.object_list.all():
            i += 1
            if i != 0 and i % cr == 0:
                p.showPage()

                if impresso.rotate:
                    p.translate(pagesize[1], 0)
                    p.rotate(90)

            q = floor(i / col) % row
            r = i % int(col)

            l = me + r * ec + r * le
            b = ms - (q + 1) * ae - q * el

            f = Frame(l, b, le, ae,
                      leftPadding=fs / 3,
                      bottomPadding=fs / 3,
                      topPadding=fs / 3,
                      rightPadding=fs / 3,
                      showBoundary=0)
            # f.drawBoundary(p)
            f.addFromList(self.createParagraphs(contato, stylesheet), p)

        p.showPage()
        p.save()
Example #42
0
    def atPage(self, name, pseudopage, declarations):
        c = self.c
        data = {}
        name = name or "body"
        pageBorder = None

        if declarations:
            result = self.ruleset([self.selector('*')], declarations)

            if declarations:
                data = list(result[0].values())[0]
                pageBorder = data.get("-pdf-frame-border", None)

        if name in c.templateList:
            log.warning(self.c.warning("template '%s' has already been defined", name))

        if "-pdf-page-size" in data:
            c.pageSize = xhtml2pdf.default.PML_PAGESIZES.get(str(data["-pdf-page-size"]).lower(), c.pageSize)

        isLandscape = False
        if "size" in data:
            size = data["size"]
            if type(size) is not list:
                size = [size]
            sizeList = []
            for value in size:
                valueStr = str(value).lower()
                if type(value) is tuple:
                    sizeList.append(getSize(value))
                elif valueStr == "landscape":
                    isLandscape = True
                elif valueStr in xhtml2pdf.default.PML_PAGESIZES:
                    c.pageSize = xhtml2pdf.default.PML_PAGESIZES[valueStr]
                else:
                    log.warning(c.warning("Unknown size value for @page"))

            if len(sizeList) == 2:
                c.pageSize = tuple(sizeList)
            if isLandscape:
                c.pageSize = landscape(c.pageSize)

        padding_top = self._getFromData(data, 'padding-top', 0, getSize)
        padding_left = self._getFromData(data, 'padding-left', 0, getSize)
        padding_right = self._getFromData(data, 'padding-right', 0, getSize)
        padding_bottom = self._getFromData(data, 'padding-bottom', 0, getSize)
        border_color = self._getFromData(data, ('border-top-color', 'border-bottom-color',\
                                                'border-left-color', 'border-right-color'), None, getColor)
        border_width = self._getFromData(data, ('border-top-width', 'border-bottom-width',\
                                                'border-left-width', 'border-right-width'), 0, getSize)

        for prop in ("margin-top", "margin-left", "margin-right", "margin-bottom",
                     "top", "left", "right", "bottom", "width", "height"):
            if prop in data:
                c.frameList.append(self._pisaAddFrame(name, data, first=True, border=pageBorder, size=c.pageSize))
                break

        # Frames have to be calculated after we know the pagesize
        frameList = []
        staticList = []
        for fname, static, border, x, y, w, h, fdata in c.frameList:
            fpadding_top = self._getFromData(fdata, 'padding-top', padding_top, getSize)
            fpadding_left = self._getFromData(fdata, 'padding-left', padding_left, getSize)
            fpadding_right = self._getFromData(fdata, 'padding-right', padding_right, getSize)
            fpadding_bottom = self._getFromData(fdata, 'padding-bottom', padding_bottom, getSize)
            fborder_color = self._getFromData(fdata, ('border-top-color', 'border-bottom-color',\
                                                      'border-left-color', 'border-right-color'), border_color, getColor)
            fborder_width = self._getFromData(fdata, ('border-top-width', 'border-bottom-width',\
                                                      'border-left-width', 'border-right-width'), border_width, getSize)

            if border or pageBorder:
                frame_border = ShowBoundaryValue()
            else:
                frame_border = ShowBoundaryValue(color=fborder_color, width=fborder_width)

            #fix frame sizing problem.
            if static:
                x, y, w, h = getFrameDimensions(fdata, c.pageSize[0], c.pageSize[1])
            x, y, w, h = getCoords(x, y, w, h, c.pageSize)
            if w <= 0 or h <= 0:
                log.warning(self.c.warning("Negative width or height of frame. Check @frame definitions."))

            frame = Frame(
                x, y, w, h,
                id=fname,
                leftPadding=fpadding_left,
                rightPadding=fpadding_right,
                bottomPadding=fpadding_bottom,
                topPadding=fpadding_top,
                showBoundary=frame_border)

            if static:
                frame.pisaStaticStory = []
                c.frameStatic[static] = [frame] + c.frameStatic.get(static, [])
                staticList.append(frame)
            else:
                frameList.append(frame)

        background = data.get("background-image", None)
        if background:
            #should be relative to the css file
            background = self.c.getFile(background, relative=self.c.cssParser.rootPath)

        if not frameList:
            log.warning(c.warning("missing explicit frame definition for content or just static frames"))
            fname, static, border, x, y, w, h, data = self._pisaAddFrame(name, data, first=True, border=pageBorder,
                                                                         size=c.pageSize)
            x, y, w, h = getCoords(x, y, w, h, c.pageSize)
            if w <= 0 or h <= 0:
                log.warning(c.warning("Negative width or height of frame. Check @page definitions."))

            if border or pageBorder:
                frame_border = ShowBoundaryValue()
            else:
                frame_border = ShowBoundaryValue(color=border_color, width=border_width)

            frameList.append(Frame(
                x, y, w, h,
                id=fname,
                leftPadding=padding_left,
                rightPadding=padding_right,
                bottomPadding=padding_bottom,
                topPadding=padding_top,
                showBoundary=frame_border))

        pt = PmlPageTemplate(
            id=name,
            frames=frameList,
            pagesize=c.pageSize,
        )
        pt.pisaStaticList = staticList
        pt.pisaBackground = background
        pt.pisaBackgroundList = c.pisaBackgroundList

        if isLandscape:
            pt.pageorientation = pt.LANDSCAPE

        c.templateList[name] = pt
        c.template = None
        c.frameList = []
        c.frameStaticList = []

        return {}, {}
Example #43
0
    def beforePage(self):
        self.context.current_page += 1
        if self.context.has_header():
            # HEADER
            header = self.context.get_header()
            self.canv.saveState()

            # calculate height
            if self.platypus_header_calculate is False:
                element = header[0]
                height = element.wrap(self.width_available, self.pagesize[1])[1]
                height += self.frame_attr['topPadding']
                height += self.frame_attr['bottomPadding']
                self.platypus_header_height = height

            height = self.platypus_header_height
            # calculate coordinates
            x = self.leftMargin
            y = self.pagesize[1] - height

            # resize margin if the frame is too big
            if self.platypus_header_calculate is False:
                if self.topMargin < height:
                    self.platypus_header_calculate = True
                    self.topMargin = height
                    # calculate self.width and self.height
                    self._calc()
                    # reset the main frame with new margin
                    self.main_frame_attr['x1'] = self.leftMargin
                    self.main_frame_attr['y1'] = self.bottomMargin
                    self.main_frame_attr['width'] = self.width
                    self.main_frame_attr['height'] = self.height
                    self.main_frame.__init__(**self.main_frame_attr)
                else:
                    # frame is centered in top margin
                    y -= (self.topMargin - height) / 2
            else:
                # frame is centered in top margin
                y -= (self.topMargin - height) / 2

            # create a frame which will contain all platypus objects defined
            # in the footer
            fh = Frame(x, y, self.width_available, height, **self.frame_attr)
            fh.addFromList(self.context.get_header_copy(), self.canv)
            self.canv.restoreState()

        if self.context.has_footer():
            # FOOTER
            footer = self.context.get_footer()
            self.canv.saveState()

            # calculate height
            element = footer[0]
            height = element.wrap(self.width_available, self.pagesize[1])[1]
            height += self.frame_attr['topPadding']
            height += self.frame_attr['bottomPadding']

            # calculate coordinates
            x = self.leftMargin
            y = 0

            # resize margin if the frame is too big
            if self.bottomMargin < height:
                self.bottomMargin = height
                # calculate self.width and self.height
                self._calc()
                # reset the main frame with new margin
                self.main_frame_attr['x1'] = self.leftMargin
                self.main_frame_attr['y1'] = self.bottomMargin
                self.main_frame_attr['width'] = self.width
                self.main_frame_attr['height'] = self.height
                self.main_frame.__init__(**self.main_frame_attr)
            else:
                # frame is centered in bottom margin
                y = (self.bottomMargin - height) / 2

            # create a frame which will contain all platypus objects defined
            # in the footer
            ff = Frame(x, y, self.width_available, height, **self.frame_attr)
            ff.addFromList(self.context.get_footer_copy(), self.canv)
            self.canv.restoreState()
Example #44
0
class MySimpleDocTemplate(BaseDocTemplate):
    """
        The document template used for all PDF documents.
    """


    def __init__(self, filename, context, **kw):
        BaseDocTemplate.__init__(self, filename, **kw)
        self.toc_index = 0
        self.main_frame_attr = {'x1': self.leftMargin,
                                'y1': self.bottomMargin,
                                'width': self.width,
                                'height': self.height,
                                'id':'normal',
                                'showBoundary': self.showBoundary}

        # We keep the main frame reference to resize it during the build
        self.main_frame = Frame(**self.main_frame_attr)
        self.main_frame_change = False
        template_attrs = {'id': 'now', 'frames': [self.main_frame],
                          'pagesize': kw['pagesize']}
        page_template = PageTemplate(**template_attrs)
        self.platypus_header_calculate = False
        self.platypus_header_height = None
        self.platypus_footer = None
        self.context = context
        self.addPageTemplates([page_template])
        self.toc_high_level = self.context.toc_high_level

        self.frame_attr = {'leftPadding': 0, 'bottomPadding': 6,
                           'rightPadding': 0, 'topPadding': 6,
                           'showBoundary': 0}
        self.context = context
        # calculate width available
        self.width_available = self.width
        self.width_available -= self.frame_attr['leftPadding']
        self.width_available -= self.frame_attr['rightPadding']


    def beforePage(self):
        self.context.current_page += 1
        if self.context.has_header():
            # HEADER
            header = self.context.get_header()
            self.canv.saveState()

            # calculate height
            if self.platypus_header_calculate is False:
                element = header[0]
                height = element.wrap(self.width_available, self.pagesize[1])[1]
                height += self.frame_attr['topPadding']
                height += self.frame_attr['bottomPadding']
                self.platypus_header_height = height

            height = self.platypus_header_height
            # calculate coordinates
            x = self.leftMargin
            y = self.pagesize[1] - height

            # resize margin if the frame is too big
            if self.platypus_header_calculate is False:
                if self.topMargin < height:
                    self.platypus_header_calculate = True
                    self.topMargin = height
                    # calculate self.width and self.height
                    self._calc()
                    # reset the main frame with new margin
                    self.main_frame_attr['x1'] = self.leftMargin
                    self.main_frame_attr['y1'] = self.bottomMargin
                    self.main_frame_attr['width'] = self.width
                    self.main_frame_attr['height'] = self.height
                    self.main_frame.__init__(**self.main_frame_attr)
                else:
                    # frame is centered in top margin
                    y -= (self.topMargin - height) / 2
            else:
                # frame is centered in top margin
                y -= (self.topMargin - height) / 2

            # create a frame which will contain all platypus objects defined
            # in the footer
            fh = Frame(x, y, self.width_available, height, **self.frame_attr)
            fh.addFromList(self.context.get_header_copy(), self.canv)
            self.canv.restoreState()

        if self.context.has_footer():
            # FOOTER
            footer = self.context.get_footer()
            self.canv.saveState()

            # calculate height
            element = footer[0]
            height = element.wrap(self.width_available, self.pagesize[1])[1]
            height += self.frame_attr['topPadding']
            height += self.frame_attr['bottomPadding']

            # calculate coordinates
            x = self.leftMargin
            y = 0

            # resize margin if the frame is too big
            if self.bottomMargin < height:
                self.bottomMargin = height
                # calculate self.width and self.height
                self._calc()
                # reset the main frame with new margin
                self.main_frame_attr['x1'] = self.leftMargin
                self.main_frame_attr['y1'] = self.bottomMargin
                self.main_frame_attr['width'] = self.width
                self.main_frame_attr['height'] = self.height
                self.main_frame.__init__(**self.main_frame_attr)
            else:
                # frame is centered in bottom margin
                y = (self.bottomMargin - height) / 2

            # create a frame which will contain all platypus objects defined
            # in the footer
            ff = Frame(x, y, self.width_available, height, **self.frame_attr)
            ff.addFromList(self.context.get_footer_copy(), self.canv)
            self.canv.restoreState()
Example #45
0
    def atPage(self, name, pseudopage, declarations):
        c = self.c
        data = {}
        name = name or "body"
        pageBorder = None

        if declarations:
            result = self.ruleset([self.selector('*')], declarations)
            # print "@PAGE", name, pseudopage, declarations, result

            if declarations:
                data = result[0].values()[0]
                pageBorder = data.get("-pdf-frame-border", None)

        if name in c.templateList:
            log.warn(self.c.warning("template '%s' has already been defined", name))

        if "-pdf-page-size" in data:
            c.pageSize = xhtml2pdf.default.PML_PAGESIZES.get(str(data["-pdf-page-size"]).lower(), c.pageSize)

        isLandscape = False
        if "size" in data:
            size = data["size"]
            # print size, c.pageSize
            if type(size) is not types.ListType:
                size = [size]
            sizeList = []
            for value in size:
                valueStr = str(value).lower()
                if type(value) is types.TupleType:
                    sizeList.append(getSize(value))
                elif valueStr == "landscape":
                    isLandscape = True
                elif valueStr in xhtml2pdf.default.PML_PAGESIZES:
                    c.pageSize = xhtml2pdf.default.PML_PAGESIZES[valueStr]
                else:
                    log.warn(c.warning("Unknown size value for @page"))

            if len(sizeList) == 2:
                c.pageSize = sizeList
            if isLandscape:
                c.pageSize = landscape(c.pageSize)

        for prop in ("margin-top", "margin-left", "margin-right", "margin-bottom",
                     "top", "left", "right", "bottom", "width", "height"):
            if prop in data:
                c.frameList.append(self._pisaAddFrame(name, data, first=True, border=pageBorder, size=c.pageSize))
                break
        # self._drawing = PmlPageDrawing(self._pagesize)

        #if not c.frameList:
        #    c.warning("missing frame definitions for template")
        #    return {}, {}

        # Frames have to be calculated after we know the pagesize
        frameList = []
        staticList = []
        for fname, static, border, x, y, w, h, fdata in c.frameList:
            #fix frame sizing problem.
            if static:
                x, y, w, h = getFrameDimensions(fdata, c.pageSize[0], c.pageSize[1])
            x, y, w, h = getCoords(x, y, w, h, c.pageSize)
            if w <= 0 or h <= 0:
                log.warn(self.c.warning("Negative width or height of frame. Check @frame definitions."))
            frame = Frame(
                x, y, w, h,
                id=fname,
                leftPadding=0,
                rightPadding=0,
                bottomPadding=0,
                topPadding=0,
                showBoundary=border or pageBorder)
            if static:
                frame.pisaStaticStory = []
                c.frameStatic[static] = [frame] + c.frameStatic.get(static, [])
                staticList.append(frame)
            else:
                frameList.append(frame)

        background = data.get("background-image", None)
        if background:
            background = self.c.getFile(background)
        # print background

        # print frameList
        if not frameList:
            # print 999
            log.warn(c.warning("missing explicit frame definition for content or just static frames"))
            fname, static, border, x, y, w, h, data = self._pisaAddFrame(name, data, first=True, border=pageBorder, size=c.pageSize)
            x, y, w, h = getCoords(x, y, w, h, c.pageSize)
            if w <= 0 or h <= 0:
                log.warn(c.warning("Negative width or height of frame. Check @page definitions."))
            frameList.append(Frame(
                x, y, w, h,
                id=fname,
                leftPadding=0,
                rightPadding=0,
                bottomPadding=0,
                topPadding=0,
                showBoundary=border or pageBorder))

        pt = PmlPageTemplate(
            id=name,
            frames=frameList,
            pagesize=c.pageSize,
            )
        pt.pisaStaticList = staticList
        pt.pisaBackground = background
        pt.pisaBackgroundList = c.pisaBackgroundList

        if isLandscape:
            pt.pageorientation = pt.LANDSCAPE

        # self._pagesize)
        # pt.pml_statics = self._statics
        # pt.pml_draw = self._draw
        # pt.pml_drawing = self._drawing
        # pt.pml_background = attrs.background
        # pt.pml_bgstory = self._bgstory

        c.templateList[name] = pt
        c.template = None
        c.frameList = []
        c.frameStaticList = []

        return {}, {}
Example #46
0
class Div(Flowable):

    def __init__(self, story, height=None, width=None, pos_x=None, pos_y=None,
                 frame_attrs=freeze({}), attributes=freeze({}), pto_trailer=None,
                 pto_header=None):
        Flowable.__init__(self)
        # get on story
        self.div_story = story
        # set frame style
        self.frame_attrs = {'leftPadding': 0, 'bottomPadding': 0,
                           'rightPadding': 0, 'topPadding': 0,
                           'showBoundary': 0}
        # PTO initialisation
        self.pto_trailer = pto_trailer
        self.pto_header = pto_header

        if frame_attrs is not None:
            self.frame_attrs.update(frame_attrs)

        for margin in ('topMargin', 'bottomMargin', 'leftMargin',
                       'rightMargin'):
            if margin in self.frame_attrs:
                del self.frame_attrs[margin]

        border = self.frame_attrs['showBoundary']
        if isinstance(border, ShowBoundaryValue):
            border = border.width
        if border:
            for padding_attr in FRAME_PADDINGS_KEYS:
                self.frame_attrs[padding_attr] += border
        self.frame_width = width

        # Overflow
        # TODO to improve
        self.keep_in_frame = None
        style = attribute_style_to_dict(attributes.get((None, 'style'), ''))
        self.overflow = style.get('overflow-y', None)
        if self.overflow == 'hidden':
            self.overflow = 'truncate'
        else:
            self.overflow = None


    def draw(self):
        # set position for the frame
        self.pos_x, self.pos_y = self._get_current_position(self.canv)
        # XXX This is false, height=drawHeigh and drawHeight should take into
        # account the frame padding
        height = (self.drawHeight + self.frame_attrs['leftPadding'] +
                  self.frame_attrs['rightPadding'])
        width = (self.drawWidth + self.frame_attrs['topPadding'] +
                 self.frame_attrs['bottomPadding'])

        self.frame = Frame(self.pos_x, self.pos_y, width, height,
                           **self.frame_attrs)
        if self.overflow:
            # Hack, We lie by setting the new created frame as default frame
            # of the doc template
            # To avoid problems when calling keep_in_frame.wrap
            # See platypus.flowables "def _listWrapOn"
            _doctemplate = self.canv._doctemplate
            # save state
            current_frame = getattr(_doctemplate, 'frame', None)
            _doctemplate.frame = self.frame

            # Check if PTO is defined
            if self.pto_trailer or self.pto_header:
                ptocontainer = PTOContainer(self.div_story[:],
                                            self.pto_trailer, self.pto_header)
                ptocontainer.canv = self.canv
                pto_size = ptocontainer.wrap(self.drawWidth, self.drawHeight)
                # XXX Round the height to avoid problems with decimal
                if int(pto_size[1]) > int(self.drawHeight):
                    pto_story = ptocontainer.split(self.drawWidth,
                                                   self.drawHeight)
                    self.frame.addFromList(pto_story, self.canv)
                else:
                    self.frame.addFromList([self.keep_in_frame], self.canv)
            else:
                self.frame.addFromList([self.keep_in_frame], self.canv)
            # restore state
            if current_frame:
                _doctemplate.frame = current_frame
        else:
            self.frame.addFromList(self.div_story[:], self.canv)


    def wrap(self, availWidth, availHeight):
        canv = self.canv
        if self.overflow:
            if self.keep_in_frame is None:
                # FIXME if the availHeight is very small
                # We consider that there is no enough space
                # and we calculate the real size of the flowables
                if availHeight <= 0:
                    width, height = self._get_real_size(availWidth)
                else:
                    width, height = availWidth, availHeight

                # Dirty hack, get the current frame height and use it
                # if height is too small
                main_frame_height = self._get_main_frame_height(availHeight,
                                                                0.8)
                if height == -1e-06:
                    height = main_frame_height
                else:
                    height = min(height, main_frame_height)

                self.keep_in_frame = KeepInFrame(width, height,
                                                 self.div_story[:],
                                                 mode=self.overflow)
            else:
                width, height = availWidth, availHeight
                # FIXME Usefull ?
                # Dirty hack, get the current frame height and use it
                # if height is too small
                main_frame_height = self._get_main_frame_height(availHeight,
                                                                0.8)
                if height == -1e-06:
                    height = main_frame_height
                else:
                    height = min(height, main_frame_height)

            # Set the canva
            self.keep_in_frame.canv = canv

            # Hack, We remove the attribute _doctemplate of the canv
            # To avoid problems when calling keep_in_frame.wrap
            # See platypus.flowables "def _listWrapOn"
            if hasattr(canv, '_doctemplate'):
                _doctemplate = canv._doctemplate
                # Remove _doctemplate
                canv._doctemplate = None
            w, h = self.keep_in_frame.wrap(width, height)
            if hasattr(canv, '_doctemplate'):
                # Restore _doctemplate
                canv._doctemplate = _doctemplate

            self.drawWidth, self.drawHeight = w, h
        else:
            width, height = self._get_real_size(availWidth)
            self.drawWidth, self.drawHeight = width, height

        return self.drawWidth, self.drawHeight


    def getSpaceBefore(self):
        if self.overflow and self.keep_in_frame:
            return self.keep_in_frame.getSpaceBefore()

        # XXX default value
        return 0


    def getSpaceAfter(self):
        if self.overflow and self.keep_in_frame:
            return self.keep_in_frame.getSpaceAfter()

        # XXX default value
        return 0


    def _get_real_size(self, availWidth, availHeight=10000000):
        """By default we use a fake height to calculate the real
        height of the flowables"""
        self.drawWidth = self.width or availWidth
        self.drawWidth -= self.frame_attrs['leftPadding']
        self.drawWidth -= self.frame_attrs['rightPadding']
        self.drawHeight = 0
        at_top = True
        for element in self.div_story[:]:
            if at_top:
                at_top = False
            else:
                self.drawHeight += element.getSpaceBefore()
            flowHeight = element.wrap(availWidth,
                                      availHeight-self.drawHeight)[1]
            self.drawHeight += flowHeight
            self.drawHeight += element.getSpaceAfter()
        self.drawHeight += self.frame_attrs['topPadding']
        self.drawHeight += self.frame_attrs['bottomPadding']
        return (self.drawWidth, self.drawHeight)


    def _align_frame(self, available_width, hAlign):
        if hAlign == 'CENTER':
            self.pox_x = (available_width - self.frame_width) / 2 + self.pos_x
        elif hAlign == 'RIGHT':
            self.pos_x = available_width - self.frame_width + self.pox_x


    def _get_current_position(self, canv):
        return (canv._x, canv._y)


    def _get_current_absolute_position(self, canv):
        return canv.absolutePosition(canv._x, canv._y)


    def _get_main_frame_height(self, default, ratio=0.9):
        if self.canv is None:
            return default
        value = self.canv._doctemplate.main_frame_attr.get('height', default)
        return value * ratio
def run():
    styles = getSampleStyleSheet()
    styleN = styles["Normal"]
    styleH = styles["Heading1"]
    story = []

    # for codeNames in code
    story.append(Paragraph("I2of5", styleN))
    story.append(I2of5(1234, barWidth=inch * 0.02, checksum=0))
    story.append(Paragraph("MSI", styleN))
    story.append(MSI(1234))
    story.append(Paragraph("Codabar", styleN))
    story.append(Codabar("A012345B", barWidth=inch * 0.02))
    story.append(Paragraph("Code 11", styleN))
    story.append(Code11("01234545634563"))
    story.append(Paragraph("Code 39", styleN))
    story.append(Standard39("A012345B%R"))
    story.append(Paragraph("Extended Code 39", styleN))
    story.append(Extended39("A012345B}"))
    story.append(Paragraph("Code93", styleN))
    story.append(Standard93("CODE 93"))
    story.append(Paragraph("Extended Code93", styleN))
    story.append(Extended93("L@@K! Code 93 :-)"))  # , barWidth=0.005 * inch))
    story.append(Paragraph("Code 128", styleN))
    c = Code128("AB-12345678")  # , barWidth=0.005 * inch)
    # print 'WIDTH =', (c.width / inch), 'barWidth =', (c.barWidth / inch)
    # print 'LQ =', (c.lquiet / inch), 'RQ =', (c.rquiet / inch)
    story.append(c)
    story.append(Paragraph("USPS FIM", styleN))
    story.append(FIM("A"))
    story.append(Paragraph("USPS POSTNET", styleN))
    story.append(POSTNET("78247-1043"))
    story.append(Paragraph("USPS 4 State", styleN))
    story.append(USPS_4State("01234567094987654321", "01234567891"))

    from reportlab.graphics.barcode import createBarcodeDrawing

    story.append(Paragraph("EAN13", styleN))
    bcd = createBarcodeDrawing("EAN13", value="123456789012")
    story.append(bcd)
    story.append(Paragraph("EAN8", styleN))
    bcd = createBarcodeDrawing("EAN8", value="1234567")
    story.append(bcd)
    story.append(Paragraph("UPCA", styleN))
    bcd = createBarcodeDrawing("UPCA", value="03600029145")
    story.append(bcd)
    story.append(Paragraph("USPS_4State", styleN))
    bcd = createBarcodeDrawing("USPS_4State", value="01234567094987654321", routing="01234567891")
    story.append(bcd)

    story.append(Paragraph("Label Size", styleN))
    story.append(XBox((2.0 + 5.0 / 8.0) * inch, 1 * inch, '1x2-5/8"'))
    story.append(Paragraph("Label Size", styleN))
    story.append(XBox((1.75) * inch, 0.5 * inch, '1/2x1-3/4"'))
    c = Canvas("out.pdf")
    f = Frame(inch, inch, 6 * inch, 9 * inch, showBoundary=1)
    f.addFromList(story, c)
    c.save()
    print "saved out.pdf"