Example #1
0
def changing_headers_PDF(name="form_letter.pdf"):
    ladderDoc = platypus.BaseDocTemplate(filename=name,
                                         pagesize=A4,
                                         rightMargin=72,
                                         leftMargin=72,
                                         topMargin=72,
                                         bottomMargin=18,
                                         showBoundary=0)

    margin = 0.2 * inch
    header_frame = platypus.Frame(margin, A4[1] - 0.15 * inch - margin,
                                  A4[0] - 0.4 * inch, 1.2 * inch)
    subheader_frame = platypus.Frame(
        margin, A4[1] - 0.15 * inch - margin - 0.45 * inch, A4[0] - 0.4 * inch,
        1.2 * inch)

    body_frame = platypus.Frame(0.2 * inch, 0.2 * inch, A4[0] - 0.4 * inch,
                                A4[1] - 1.2 * inch)

    page_template = platypus.PageTemplate(
        id='begin_section',
        frames=[header_frame, subheader_frame, body_frame],
        onPage=simple_background)
    # page_template_content = platypus.PageTemplate(id='content',frames=[body_frame],onPage=simple_background)

    ladderDoc.addPageTemplates(page_template)
    # ladderDoc.addPageTemplates([page_template,page_template_content])
    return ladderDoc
Example #2
0
def flow_and_dividends_block(df: pd.DataFrame, block_position: BlockPosition):
    """Формирует блок pdf-файла с информацией движении средств и дивидендах.

    В левой части располагается табличка движения средств, а в правой - таблица дивидендов.
    """
    left_block_header = platypus.Paragraph("Last Month Change and Inflow", BLOCK_HEADER_STYLE)
    left_table = make_pdf_flow(df)
    left_frame = platypus.Frame(
        block_position.x,
        block_position.y,
        block_position.width * LEFT_PART_OF_BLOCK,
        block_position.height,
        leftPadding=0,
        bottomPadding=0,
        rightPadding=0,
        topPadding=6,
        showBoundary=0,
    )
    left_frame.addFromList([left_block_header, left_table], block_position.canvas)
    right_block_header = platypus.Paragraph("Portfolio Dividends", BLOCK_HEADER_STYLE)
    right_table = make_pdf_dividends(df)
    right_frame = platypus.Frame(
        block_position.x + block_position.width * LEFT_PART_OF_BLOCK,
        block_position.y,
        block_position.width * (1 - LEFT_PART_OF_BLOCK),
        block_position.height,
        leftPadding=0,
        bottomPadding=0,
        rightPadding=0,
        topPadding=6,
        showBoundary=0,
    )
    right_frame.addFromList([right_block_header, right_table], block_position.canvas)
Example #3
0
def customer_PDF(name="form_letter.pdf"):
    ladderDoc = MultiPageDocument(filename=name,
                                  pagesize=A4,
                                  rightMargin=72,
                                  leftMargin=72,
                                  topMargin=72,
                                  bottomMargin=18,
                                  showBoundary=0,
                                  allowSplitting=1,
                                  _pageBreakQuick=0)

    address_header_frame = platypus.Frame(A4[0] - 4 * inch,
                                          A4[1] - 4 * inch - 2.1 * inch,
                                          3 * inch,
                                          4 * inch + 1.5 * inch,
                                          showBoundary=False)

    document_reference_frame = platypus.Frame(1 * cm,
                                              23 * cm,
                                              A4[0] - 2 * cm,
                                              5 * cm,
                                              showBoundary=True)

    # left_header_frame2 = platypus.Frame(1*cm,23*cm, 7.5*cm, 1*cm,showBoundary=False,leftPadding=0, bottomPadding=0,rightPadding=0, topPadding=0)
    # header2_frame_right = platypus.Frame(12*cm,23*cm, 7.5*cm, 1*cm,showBoundary=True)

    body_frame = platypus.Frame(1 * cm,
                                3 * cm,
                                A4[0] - 2 * cm,
                                21 * cm,
                                id='body',
                                showBoundary=False)
    page_template = platypus.PageTemplate(
        id='First',
        frames=[address_header_frame, body_frame],
        onPage=simple_customer_background)

    body_frame = platypus.Frame(1 * cm,
                                3 * cm,
                                A4[0] - 2 * cm,
                                21 * cm,
                                id='body',
                                showBoundary=False)
    page_template2 = platypus.PageTemplate(id='Later',
                                           frames=[body_frame],
                                           onPage=simple_customer_background)

    ladderDoc.addPageTemplates([page_template, page_template2])

    return ladderDoc
Example #4
0
    def build(self,
              flowables,
              onTitle=_do_nothing,
              onPortrait=_do_nothing,
              onLandscape=_do_nothing,
              canvasmaker=canvas.Canvas):

        # Recalculate in case we changed margins, sizes, etc
        self._calc()

        # Portrait frame
        frame_portrait = p.Frame(self.leftMargin,
                                 self.bottomMargin,
                                 self.width,
                                 self.height,
                                 id='portraitFrame')

        # Landscape frame
        frame_landscape = p.Frame(0.75 * u.inch,
                                  0.5 * u.inch,
                                  9.5 * u.inch,
                                  7.4 * u.inch,
                                  id='landscapeFrame')

        # Add page templates to this document template
        self.addPageTemplates([
            p.PageTemplate(id='title',
                           frames=frame_portrait,
                           onPage=onTitle,
                           pagesize=pagesizes.portrait(pagesizes.letter)),
            p.PageTemplate(id='portrait',
                           frames=frame_portrait,
                           onPage=onPortrait,
                           pagesize=pagesizes.portrait(pagesizes.letter)),
            p.PageTemplate(id='landscape',
                           frames=frame_landscape,
                           onPage=onLandscape,
                           pagesize=pagesizes.landscape(pagesizes.letter))
        ])

        if onTitle is _do_nothing and hasattr(self, 'onTitle'):
            self.pageTemplates[0].beforeDrawPage = self.onTitle
        if onPortrait is _do_nothing and hasattr(self, 'onPortrait'):
            self.pageTemplates[1].beforeDrawPage = self.onPortrait
        if onLandscape is _do_nothing and hasattr(self, 'onLandscape'):
            self.pageTemplates[2].beforeDrawPage = self.onLandscape

        # Use the base class to call build
        p.BaseDocTemplate.build(self, flowables, canvasmaker=canvasmaker)
Example #5
0
def portfolio_return_block(df: pd.DataFrame, block_position: BlockPosition):
    """Формирует блок pdf-файла с информацией доходности портфеля и индекса.

    В левой части располагается табличка, а в правой части диаграмма.
    """
    block_header = platypus.Paragraph("Portfolio Return", BLOCK_HEADER_STYLE)
    table = make_pdf_table(df)
    frame = platypus.Frame(
        block_position.x,
        block_position.y,
        block_position.width * LEFT_PART_OF_BLOCK,
        block_position.height,
        leftPadding=0,
        bottomPadding=0,
        rightPadding=0,
        topPadding=6,
        showBoundary=0,
    )
    frame.addFromList([block_header, table], block_position.canvas)
    image = make_plot(df, block_position.width * (1 - LEFT_PART_OF_BLOCK),
                      block_position.height)
    image.drawOn(
        block_position.canvas,
        block_position.x + block_position.width * LEFT_PART_OF_BLOCK,
        block_position.y,
    )
Example #6
0
 def setup_multiple_index_cards(self, card_size):
     leftM, rightM, topM, bottomM = self.margins
     MINIMUM_SPACING = 0.1 * inch
     drawable_x = self.pagesize[0] - leftM - rightM
     drawable_y = self.pagesize[1] - topM - bottomM
     fittable_x = int(drawable_x / (card_size[0] + MINIMUM_SPACING))
     fittable_y = int(drawable_y / (card_size[1] + MINIMUM_SPACING))
     # Raise a ValueError if we can't actually fit multiple index cards on this page.
     if (not fittable_x) or (not fittable_y):
         raise ValueError(
             "Card size %s does not fit on page %s with margins %s" %
             (card_size, self.pagesize, self.margins))
     x_spacer = (
         # Extra space =
         fittable_x *  # Number of cards times
         ((drawable_x / fittable_x)  # space per card
          - card_size[0])  # - space occupied by card
         /  # Divide extra space by n+1, so we get [   CARD    ], [  CARD  CARD  ], etc.
         (fittable_x + 1))
     y_spacer = (fittable_y * ((drawable_y / fittable_y) - (card_size[1])) /
                 (fittable_y + 1))
     frames = []
     for x in range(fittable_x):
         x_start = leftM + (x_spacer * (x + 1)) + (card_size[0] * x)
         for y in range(fittable_y - 1, -1, -1):
             # Count down for the y, since we start from the bottom
             # and move up
             y_start = bottomM + (y_spacer * (y + 1)) + (card_size[1] * y)
             frames.append(
                 platypus.Frame(x_start,
                                y_start,
                                width=card_size[0],
                                height=card_size[1],
                                showBoundary=1))
     return frames
 def __init__(self, filename, **kw):
     frame1 = platypus.Frame(inch,
                             5.6 * inch,
                             6 * inch,
                             5.2 * inch,
                             id='F1')
     frame2 = platypus.Frame(inch,
                             inch,
                             6 * inch,
                             4.5 * inch,
                             showBoundary=1,
                             id='F2')
     self.allowSplitting = 0
     BaseDocTemplate.__init__(self, filename, **kw)
     self.addPageTemplates(
         PageTemplate('normal', [frame1, frame2], framePage))
Example #8
0
 def __init__(self, out, node, doc):
     if not node.hasAttribute('pageSize'):
         pageSize = (utils.unit_get('21cm'), utils.unit_get('29.7cm'))
     else:
         ps = [x.strip() for x in node.getAttribute('pageSize').replace(')', '').replace(
             '(', '').split(',')]
         pageSize = (utils.unit_get(ps[0]), utils.unit_get(ps[1]))
     cm = reportlab.lib.units.cm
     self.doc_tmpl = platypus.BaseDocTemplate(out, pagesize=pageSize, **utils.attr_get(node, ['leftMargin', 'rightMargin', 'topMargin', 'bottomMargin'], {
                                              'allowSplitting': 'int', 'showBoundary': 'bool', 'title': 'str', 'author': 'str', 'rotation': 'int'}))
     self.page_templates = []
     self.styles = doc.styles
     self.doc = doc
     pts = node.getElementsByTagName('pageTemplate')
     for pt in pts:
         frames = []
         for frame_el in pt.getElementsByTagName('frame'):
             frame = platypus.Frame(
                 **(utils.attr_get(frame_el, ['x1', 'y1', 'width', 'height', 'leftPadding', 'rightPadding', 'bottomPadding', 'topPadding'], {'id': 'text', 'showBoundary': 'bool'})))
             frames.append(frame)
         gr = pt.getElementsByTagName('pageGraphics')
         if len(gr):
             drw = _rml_draw(gr[0], self.doc)
             self.page_templates.append(platypus.PageTemplate(
                 frames=frames, onPage=drw.render, **utils.attr_get(pt, [], {'id': 'str'})))
         else:
             self.page_templates.append(
                 platypus.PageTemplate(frames=frames, **utils.attr_get(pt, [], {'id': 'str'})))
     self.doc_tmpl.addPageTemplates(self.page_templates)
Example #9
0
    def drawFrame(self, canvas, func, x, y, textWidth, availableHeight, style):
        if func is None:
            return
        story = self.createStory()
        func(story)
        #story = self.makeStory(func, textWidth)
        #if story is not None:
        pdfstory = []
        for e in story.content:
            pdfstory += self.elem2flow(e, self.getElementStyle(e), textWidth)

        height = 0
        for e in pdfstory:
            unused, h = e.wrap(textWidth, availableHeight)
            height += h
            availableHeight -= h

        if style.valign == styles.VA_BOTTOM:
            pass
        elif style.valign == styles.VA_MIDDLE:
            y -= (height / 2)
        elif style.valign == styles.VA_TOP:
            y -= height

        canvas.saveState()
        f = platypus.Frame(x,
                           y,
                           textWidth,
                           height,
                           leftPadding=0,
                           rightPadding=0,
                           bottomPadding=0,
                           topPadding=0)  #showBoundary=True)
        f.addFromList(pdfstory, canvas)
        canvas.restoreState()
Example #10
0
def portfolio_structure_block(portfolio: Portfolio,
                              block_position: BlockPosition):
    """Формирует блок pdf-файла с информацией о структуре портфеля.

    В левой части располагается табличка структуры, а в правой части диаграмма.
    """
    block_header = platypus.Paragraph("Portfolio Structure",
                                      BLOCK_HEADER_STYLE)
    table = make_pdf_table(portfolio)
    frame = platypus.Frame(
        block_position.x,
        block_position.y,
        block_position.width * LEFT_PART_OF_BLOCK,
        block_position.height,
        leftPadding=0,
        bottomPadding=0,
        rightPadding=0,
        topPadding=6,
        showBoundary=0,
    )
    frame.addFromList([block_header, table], block_position.canvas)
    image = make_plot(
        portfolio,
        block_position.width * (1 - LEFT_PART_OF_BLOCK),
        block_position.height,
    )
    image.drawOn(
        block_position.canvas,
        block_position.x + block_position.width * LEFT_PART_OF_BLOCK,
        block_position.y,
    )
Example #11
0
    def init_layout(self):

        self.unit = reportlab.lib.units.inch

        self.init_fonts()
        self.init_styles()

        self.document = platypus.BaseDocTemplate(self.file_name, \
                        pagesize=reportlab.lib.pagesizes.A4, leftMargin=20, \
                        rightMargin=20, topMargin=40, bottomMargin=10, \
                        allowSplitting=0, title=self.get_title(), \
                        author="Kunnafoni")
        frameCount = 2
        frameWidth = self.document.width / frameCount
        frameHeight = self.document.height - .05 * self.unit
        frames = []
        #construct a frame for each column
        for frame in range(frameCount):

            leftMargin = self.document.leftMargin + frame * frameWidth
            column = platypus.Frame(leftMargin, self.document.bottomMargin, \
                                    frameWidth, frameHeight)
            frames.append(column)

        template = platypus.PageTemplate(frames=frames, onPage=self.addHeader)
        self.document.addPageTemplates(template)
Example #12
0
 def __init__(self, papersize, title):
     self.title = title
     frames = [
         platypus.Frame(
             PADDING, papersize[1] / 2,
             papersize[0] - 2*PADDING, papersize[1] / 6,
             showBoundary=0
         ),
         platypus.Frame(
             PADDING, PADDING,
             papersize[0] - 2*PADDING, papersize[1] / 2 - PADDING,
             showBoundary=0
         ),
     ]
     platypus.PageTemplate.__init__(
         self,
         id='Title',
         frames=frames,
     )
Example #13
0
 def process(self):
     # get the page size
     size = self.parent.pt.pagesize
     if size is None:
         size = self.parent.parent.parent.doc.pagesize
     # Get the arguments
     args = dict(self.getAttributeValues())
     # Deal with percentages
     for name, dir in (('x1', 0), ('y1', 1), ('width', 0), ('height', 1)):
         if isinstance(args[name], basestring) and args[name].endswith('%'):
             args[name] = float(args[name][:-1]) / 100 * size[dir]
     frame = platypus.Frame(**args)
     self.parent.frames.append(frame)
Example #14
0
 def __init__(self, papersize):
     frames = [
         platypus.Frame(
             PADDING, PADDING,
             papersize[0] - 2*PADDING, papersize[1] - 2*PADDING,
             showBoundary=0
         )
     ]
     platypus.PageTemplate.__init__(
         self,
         id='Normal',
         frames=frames,
     )
     self.frames
Example #15
0
File: rlab.py Project: wiz21b/koi
def letter_PDF(name="form_letter.pdf"):
    ladderDoc = platypus.BaseDocTemplate(filename=name,
                                         pagesize=A4,
                                         rightMargin=72,
                                         leftMargin=72,
                                         topMargin=72,
                                         bottomMargin=18,
                                         showBoundary=0,
                                         allowSplitting=0,
                                         _pageBreakQuick=0)

    address_header_frame = platypus.Frame(A4[0] - 4 * inch,
                                          A4[1] - 4 * inch - 2.1 * inch,
                                          3 * inch,
                                          4 * inch + 1.5 * inch,
                                          showBoundary=False)

    left_header_frame2 = platypus.Frame(1 * cm,
                                        23 * cm,
                                        7.5 * cm,
                                        1 * cm,
                                        showBoundary=False,
                                        leftPadding=0,
                                        bottomPadding=0,
                                        rightPadding=0,
                                        topPadding=0)
    header2_frame_right = platypus.Frame(12 * cm,
                                         23 * cm,
                                         7.5 * cm,
                                         1 * cm,
                                         showBoundary=False)

    body_frame = platypus.Frame(1 * cm,
                                6 * cm,
                                A4[0] - 2 * cm, (17 - 1) * cm,
                                showBoundary=False)

    bottom_left_frame = platypus.Frame(1 * cm,
                                       3 * cm, (A4[0] - 2 * cm) / 2,
                                       5 * cm,
                                       showBoundary=False)
    bottom_right_frame = platypus.Frame(1 * cm + (A4[0] - 2 * cm) / 2,
                                        3 * cm, (A4[0] - 2 * cm) / 2,
                                        5 * cm,
                                        showBoundary=False)

    page_template = platypus.PageTemplate(id='AllPages',
                                          frames=[
                                              address_header_frame,
                                              left_header_frame2,
                                              header2_frame_right, body_frame,
                                              bottom_left_frame,
                                              bottom_right_frame
                                          ],
                                          onPage=simple_customer_background)
    ladderDoc.addPageTemplates([page_template])
    return ladderDoc
    def paste(self, x=None, y=None, height=None):
        if x is None: x = self.x
        else: x += x_margin

        if y is None: y = self.y
        else: y += y_margin

        paragraph = self.paragraph
        if height is None:
            height = self.height

        # paragraph must be wrapped in Frame object before pasting
        frame = platypus.Frame(x, y, self.width, height, showBoundary=self.border, leftPadding=self.padding,
            rightPadding=self.padding, topPadding=self.padding, bottomPadding=self.padding)
        frame.addFromList([paragraph], self.canvas)
Example #17
0
    def _draw_user(self, user):
        barcode_frame = platypus.Frame(x1=0,
                                       y1=0,
                                       width=user_width / 2,
                                       height=user_height,
                                       showBoundary=1)
        mybarcode = code128.Code128(barWidth=units.inch * 0.015,
                                    value=user.get_barcode())
        mybarcode.humanReadable = 1
        barcode_frame.add(mybarcode, self.canvas)

        name_frame = platypus.Frame(x1=user_width / 2,
                                    y1=0,
                                    width=user_width / 2,
                                    height=user_height,
                                    showBoundary=1)
        style = styles.ParagraphStyle(name='Normal',
                                      fontName='Helvetica',
                                      fontSize=10,
                                      leading=12,
                                      allowOrphan=1)
        name_paragraph = platypus.Paragraph(u'<b>%s</b>' % user.get_name(),
                                            style)
        name_frame.add(name_paragraph, self.canvas)
Example #18
0
File: rlab.py Project: wiz21b/koi
def start_PDF(name="form_letter.pdf"):
    ladderDoc = platypus.BaseDocTemplate(filename=name,
                                         pagesize=A4,
                                         rightMargin=72,
                                         leftMargin=72,
                                         topMargin=72,
                                         bottomMargin=18,
                                         showBoundary=0)
    body_frame = platypus.Frame(0.2 * inch, 0.2 * inch, A4[0] - 0.4 * inch,
                                A4[1] - 1.2 * inch)
    page_template = platypus.PageTemplate(id='AllPages',
                                          frames=[body_frame],
                                          onPage=funcy)
    ladderDoc.addPageTemplates([page_template])
    return ladderDoc
Example #19
0
 def __init__(self, filename):
     frame = platypus.Frame(20 * mm,
                            20 * mm,
                            170 * mm,
                            227 * mm,
                            showBoundary=0,
                            topPadding=0,
                            bottomPadding=0,
                            leftPadding=0,
                            rightPadding=0)
     page = platypus.PageTemplate("main",
                                  frames=[frame],
                                  onPage=self._decorate_page)
     self.doc = platypus.BaseDocTemplate(filename, pageTemplates=[page])
     self.story = []
     self.address = None
Example #20
0
    def __init__(self, localcontext, out, node, doc, images=None, path='.', 
            title=None, page_limit=None):
        if localcontext is None:
            localcontext={'internal_header':True}
        self.localcontext = localcontext
        if images is None:
            self.images = {}
        else:
            self.images = images
        self.path = path
        self.title = title
        self.page_limit = page_limit

        if not node.get('pageSize'):
            pageSize = (utils.unit_get('21cm'), utils.unit_get('29.7cm'))
        else:
            ps = map(lambda x:x.strip(), node.get('pageSize').replace(')', '').replace('(', '').split(','))
            pageSize = ( utils.unit_get(ps[0]),utils.unit_get(ps[1]) )

        self.doc_tmpl = TinyDocTemplate(out, pagesize=pageSize, **utils.attr_get(node, ['leftMargin','rightMargin','topMargin','bottomMargin'], {'allowSplitting':'int','showBoundary':'bool','rotation':'int','title':'str','author':'str'}))
        if self.page_limit is not None:
            self.doc_tmpl.set_page_limit(self.page_limit)
        self.page_templates = []
        self.styles = doc.styles
        self.doc = doc
        self.image=[]
        pts = node.findall('pageTemplate')
        for pt in pts:
            frames = []
            for frame_el in pt.findall('frame'):
                frame = platypus.Frame( **(utils.attr_get(frame_el, ['x1','y1', 'width','height', 'leftPadding', 'rightPadding', 'bottomPadding', 'topPadding'], {'id':'str', 'showBoundary':'bool'})) )
                if utils.attr_get(frame_el, ['last']):
                    frame.lastFrame = True
                frames.append( frame )
            try :
                gr = pt.findall('pageGraphics')\
                    or pt[1].findall('pageGraphics')
            except Exception: # FIXME: be even more specific, perhaps?
                gr=''
            if len(gr):
#                self.image=[ n for n in utils._child_get(gr[0], self) if n.tag=='image' or not self.localcontext]
                drw = _rml_draw(self.localcontext,gr[0], self.doc, images=images, path=self.path, title=self.title)
                self.page_templates.append( platypus.PageTemplate(frames=frames, onPage=drw.render, **utils.attr_get(pt, [], {'id':'str'}) ))
            else:
                drw = _rml_draw(self.localcontext,node,self.doc,title=self.title)
                self.page_templates.append( platypus.PageTemplate(frames=frames,onPage=drw.render, **utils.attr_get(pt, [], {'id':'str'}) ))
        self.doc_tmpl.addPageTemplates(self.page_templates)
Example #21
0
 def setup_column_frames(self, n):
     COLUMN_SEPARATOR = 0.5 * inch
     x = self.pagesize[0]
     y = self.pagesize[1]
     leftM, rightM, topM, bottomM = self.margins
     FRAME_Y = bottomM
     FRAME_HEIGHT = y - topM - bottomM
     FRAME_WIDTH = (x - (COLUMN_SEPARATOR * (n - 1)) - leftM - rightM) / n
     frames = []
     for i in range(n):
         left_start = leftM + (FRAME_WIDTH + COLUMN_SEPARATOR) * i
         frames.append(
             platypus.Frame(left_start,
                            FRAME_Y,
                            width=FRAME_WIDTH,
                            height=FRAME_HEIGHT))
     return frames
Example #22
0
def basic_PDF(name="form_letter.pdf", body_frame=None):
    ladderDoc = platypus.BaseDocTemplate(filename=name,
                                         pagesize=A4,
                                         rightMargin=72,
                                         leftMargin=72,
                                         topMargin=72,
                                         bottomMargin=18,
                                         showBoundary=0)
    if not body_frame:
        body_frame = platypus.Frame(0.2 * inch, 0.2 * inch, A4[0] - 0.4 * inch,
                                    A4[1] - 1.2 * inch)
    else:
        mainlog.debug("Using given body frame : {}".format(body_frame))

    page_template = platypus.PageTemplate(id='AllPages',
                                          frames=[body_frame],
                                          onPage=simple_background)
    ladderDoc.addPageTemplates([page_template])
    return ladderDoc
    def fillWith(self, story):
        '''this template with the content given in story. Then return the pdf content as it must be returned by the method "create" of the report object'''
        self._calc()

        # only one frame in one template
        frame = platypus.Frame(self.get_content_left_pos(),
                               self.get_content_bottom_pos(),
                               self.get_content_width(),
                               self.get_content_height(),
                               0,
                               0,
                               0,
                               0,
                               id='mainFrame')
        template = PageTemplate('mainTemplate', [frame],
                                lambda c, doc: self._drawPageTemplate(c, doc),
                                pagesize=(self.PAGE_WIDTH, self.PAGE_HEIGHT))
        self.addPageTemplates(template)
        self._callParentBuild(story)
        return (self.io.getvalue(), 'pdf')
Example #24
0
    def __init__(self, localcontext, out, node, doc, images=None, path='.', title=None):
        if images is None:
            images = {}
        if not localcontext:
            localcontext={'internal_header':True}
        self.localcontext = localcontext
        self.images= images
        self.path = path
        self.title = title

        pagesize_map = {'a4': A4,
                    'us_letter': letter
                    }
        pageSize = (841.8897637795275, 595.275590551181)
        self.doc_tmpl = TinyDocTemplate(out, pagesize=pageSize, **utils.attr_get(node, ['leftMargin','rightMargin','topMargin','bottomMargin'], {'allowSplitting':'int','showBoundary':'bool','rotation':'int','title':'str','author':'str'}))
        self.page_templates = []
        self.styles = doc.styles
        self.doc = doc
        self.image=[]
        pts = node.findall('pageTemplate')
        for pt in pts:
            frames = []
            for frame_el in pt.findall('frame'):
                frame = platypus.Frame( **(utils.attr_get(frame_el, ['x1','y1', 'width','height', 'leftPadding', 'rightPadding', 'bottomPadding', 'topPadding'], {'id':'str', 'showBoundary':'bool'})) )
                if utils.attr_get(frame_el, ['last']):
                    frame.lastFrame = True
                frames.append( frame )
            try :
                gr = pt.findall('pageGraphics')\
                    or pt[1].findall('pageGraphics')
            except Exception: # FIXME: be even more specific, perhaps?
                gr=''
            if len(gr):
#                self.image=[ n for n in utils._child_get(gr[0], self) if n.tag=='image' or not self.localcontext]
                drw = _rml_draw(self.localcontext,gr[0], self.doc, images=images, path=self.path, title=self.title)
                self.page_templates.append( platypus.PageTemplate(frames=frames, onPage=drw.render, **utils.attr_get(pt, [], {'id':'str'}) ))
            else:
                drw = _rml_draw(self.localcontext,node,self.doc,title=self.title)
                self.page_templates.append( platypus.PageTemplate(frames=frames,onPage=drw.render, **utils.attr_get(pt, [], {'id':'str'}) ))
        self.doc_tmpl.addPageTemplates(self.page_templates)
def main():
    args = parseArgs()
    inbam = args.bam
    infasta = args.fasta
    invcf = args.vcf
    numsites = args.numsites
    output = args.output
    rows = args.rows

    SNPs, INDELs = get_vcf(invcf)
    vcfSNPs = len(SNPs)
    print 'Identified %s putative SNPs' % vcfSNPs
    #print 'Identified %s putative INDEL bases' % len(INDELs)

    # enable explicitly given positions (e.g., -p '89,3969181,44,123456') to investigate
    if args.positions:
        posList = [int(n) for n in args.positions.split(',')]
        listWantSitesVCF = []
        for i in posList:
            if any(i in x for x in SNPs):
                for SNP in SNPs:
                    if SNP[1] == i:
                        listWantSitesVCF.append(SNP)
            else:
                sys.exit('ERROR: specified position %s not a SNP' % i)
        quantityWantSites = len(listWantSitesVCF)
        listWantSitesVCF.reverse()

    # randomly select SNP sites if positions (-p) unspecified
    else:
        quantityWantSites = int(numsites)
        if quantityWantSites > vcfSNPs:
            print 'Number of requested SNP sites to investigate exceeds number of identified SNPs'
            print 'Selecting all %s putative SNP sites to print...' % vcfSNPs
            quantityWantSites = vcfSNPs

        randSitesUnsorted = random.sample(
            SNPs, quantityWantSites)  #randomly selected sites to investigate
        listWantSitesVCF = sorted(randSitesUnsorted,
                                  key=itemgetter(1),
                                  reverse=True)

    #calculate page and frames
    doc = Platypus.BaseDocTemplate(output,
                                   topMargin=0,
                                   bottomMargin=0,
                                   leftMargin=10,
                                   rightMargin=0)
    doc.pagesize = landscape(A4)  #ISO Code A4
    # A4 Dimensions: 297 mm x 210 mm ; 11.69 in x 8.27 in ; 842 pt x 595 pt

    frameCount = 2  #(numsites + (-numsites%6)) // 6
    frameWidth = doc.height / frameCount
    frameHeight = doc.width - .05 * inch
    frames = []

    #construct a frame for each column
    for frame in range(frameCount):
        leftMargin = doc.leftMargin + frame * frameWidth
        column = Platypus.Frame(leftMargin, doc.bottomMargin, frameWidth,
                                frameHeight)
        frames.append(column)
    template = Platypus.PageTemplate(frames=frames)
    doc.addPageTemplates(template)

    PAGE_HEIGHT = defaultPageSize[0]  #size in points
    PAGE_WIDTH = defaultPageSize[1]
    styles = getSampleStyleSheet()
    style = styles['Normal']
    style.fontName = 'Courier'
    style.fontSize = 6.5

    Title = ('Report containing ' + str(quantityWantSites) + ' of ' +
             str(vcfSNPs) + ' putative SNPs for ' + os.path.basename(invcf))
    report = [Paragraph(Title, styles['Heading2'])]

    while quantityWantSites > 0:
        posMinusFitty = (listWantSitesVCF[quantityWantSites - 1][1] - 50)
        centeredPos = max(
            posMinusFitty,
            0)  #handles SNP sites at beginning of chrom (<50 bases in)

        pileup = Platypus.Preformatted(
            get_ttview(inbam, infasta,
                       listWantSitesVCF[quantityWantSites - 1][0], centeredPos,
                       rows), style)
        pos = str(listWantSitesVCF[quantityWantSites - 1][1])
        QUAL = str(listWantSitesVCF[quantityWantSites - 1][2])
        DP = str(listWantSitesVCF[quantityWantSites - 1][3])
        MQ = str(listWantSitesVCF[quantityWantSites - 1][4])
        SNP = str(listWantSitesVCF[quantityWantSites - 1][5])
        header = Paragraph(
            SNP + ' at position ' + pos + ' with a QUAL of ' + QUAL +
            ', MQ of ' + MQ + ', and raw read depth (DP) of ' + DP,
            styles['Heading6'])
        gap = Platypus.Spacer(0.25, 0.05 * inch)
        report.append(Platypus.KeepTogether([gap, header, pileup]))
        quantityWantSites -= 1
    doc.build(report)
Example #26
0
    def prepareReport(self, session):
        #this is the report lab set up stuff
        OutputElements = []

        output = platypus.BaseDocTemplate('/tmp/temp.pdf')

        #A4 page size setup with margins
        output.pagesize = (8.3 * inch, 11.7 * inch)
        output.leftMargin = 0.5 * inch
        output.rightMargin = 0.5 * inch
        output.topMargin = 0.5 * inch
        output.bottomMargin = 0.5 * inch
        output.width = output.pagesize[
            0] - output.leftMargin - output.rightMargin
        output.height = output.pagesize[
            1] - output.topMargin - output.bottomMargin

        if self.columns == 1:
            #set up the columns
            interFrameMargin = 0.5 * inch
            frameWidth = output.width / 2 - interFrameMargin / 2
            frameHeight = output.height - inch * 0.6
            framePadding = 0 * inch

            # create a frameset called withHeader
            withHeader = []
            # append header settings and 2 columns
            leftMargin = output.leftMargin
            titlebar = platypus.Frame(leftMargin,
                                      output.height,
                                      output.width,
                                      0.75 * inch,
                                      leftPadding=0,
                                      rightPadding=0,
                                      topPadding=0,
                                      bottomPadding=0,
                                      showBoundary=0)
            withHeader.append(titlebar)

            column = platypus.Frame(leftMargin, output.bottomMargin,
                                    frameWidth, frameHeight)
            withHeader.append(column)

            leftMargin = output.leftMargin + frameWidth + interFrameMargin
            column = platypus.Frame(leftMargin, output.bottomMargin,
                                    frameWidth, frameHeight)
            withHeader.append(column)

            #create frameset called withoutHeader
            withoutHeader = []

            #change the frame height because no header here
            frameHeight = output.height - inch * 0.2
            #add two columns
            leftMargin = output.leftMargin
            column = platypus.Frame(leftMargin, output.bottomMargin,
                                    frameWidth, frameHeight)
            withoutHeader.append(column)

            leftMargin = output.leftMargin + frameWidth + interFrameMargin
            column = platypus.Frame(leftMargin, output.bottomMargin,
                                    frameWidth, frameHeight)
            withoutHeader.append(column)
        else:
            #set up the full page stuff
            frameWidth = output.width
            frameHeight = output.height - inch * 0.6
            framePadding = 0 * inch

            withHeader = []

            #append header and single column (full page)
            leftMargin = output.leftMargin
            titlebar = platypus.Frame(leftMargin,
                                      output.height,
                                      output.width,
                                      0.75 * inch,
                                      leftPadding=0,
                                      rightPadding=0,
                                      topPadding=0,
                                      bottomPadding=0,
                                      showBoundary=0)
            withHeader.append(titlebar)

            column = platypus.Frame(leftMargin, output.bottomMargin,
                                    frameWidth, frameHeight)
            withHeader.append(column)

            withoutHeader = []

            frameHeight = output.height - inch * 0.2
            column = platypus.Frame(leftMargin, output.bottomMargin,
                                    frameWidth, frameHeight)
            withoutHeader.append(column)

        def header(Elements, txt, style=HeaderStyle):
            s = platypus.Spacer(0.2 * inch, 0.2 * inch)
            Elements.append(s)
            style.alignment = 1
            style.fontName = self.psfont
            style.fontSize = 18
            style.borderWidth = 0
            para = platypus.Paragraph(txt, style)
            Elements.append(para)

        headerPage = platypus.PageTemplate(id='Header', frames=withHeader)
        normalPage = platypus.PageTemplate(id='noHeader', frames=withoutHeader)

        if self.headerString is not None:
            output.addPageTemplates([headerPage, normalPage])
            header(OutputElements, self.headerString)
            OutputElements.append(platypus.FrameBreak())
        else:
            output.addPageTemplates([normalPage])

        OutputElements.extend(self.getData(session))

        #numbered canvas does footer (including page numbers and date is requested)
        NumberedCanvas.setFooterText(self.footerString)
        output.build(OutputElements, canvasmaker=NumberedCanvas)
        output.showBoundary = True
        fileInput = open('/tmp/temp.pdf', 'r')
        doc = StringDocument(fileInput.read())
        os.remove('/tmp/temp.pdf')
        yield doc
def create_report(inbam1, invcf1, inbam2, invcf2, infasta, snpMatrix,
	quantityWantSites, rows, output):
	# Attempt to auto-detect sample names (experimental)
	S1Name = (get_prefix(inbam1, invcf1)).rstrip('.fastq-reference')
	S2Name = (get_prefix(inbam2, invcf2)).rstrip('.fastq-reference')

	pairwiseSNPs = get_pairwiseSNPlist(snpMatrix, S1Name, S2Name)
	pairwiseSNPpositions = pairwiseSNPs.keys()

	if quantityWantSites > len(pairwiseSNPpositions):
		print 'Selecting all {} putative SNP sites to print...'.format(len(pairwiseSNPpositions))
		quantityWantSites = len(pairwiseSNPpositions)
	randSitesUnsorted = random.sample(pairwiseSNPpositions, quantityWantSites)  #randomly selected sites to investigate
	randSitesUnsortedInts = [int(i) for i in randSitesUnsorted]  #convert strings to integers
	listWantSitesVCF = sorted(randSitesUnsortedInts, reverse=True)  #for pileup report building
	randSites = sorted(randSitesUnsortedInts)

	vcfData1, vcfData2 = get_vcf_data(randSites, invcf1, invcf2)

	if len(vcfData1) != len(vcfData2):
		print 'ERROR: unequal number of SNPs identified between {} and {}'.format(S1Name, S2Name)
		sys.exit('ERROR in VCF parsing')
	numSites = len(vcfData1)

	# Calculate page and frames
	doc = Platypus.BaseDocTemplate(output, topMargin=0, bottomMargin=0, leftMargin=10, rightMargin=0)
	doc.pagesize = landscape(A4) #ISO Code A4
	# A4 Dimensions: 297 mm x 210 mm ; 11.69 in x 8.27 in ; 842 pt x 595 pt

	frameCount = 2  #(numsites + (-numsites%6)) // 6
	frameWidth = doc.height / frameCount
	frameHeight = doc.width - .05 * inch
	frames = []

	# Construct a frame for each column
	for frame in range(frameCount):
		leftMargin = doc.leftMargin + frame * frameWidth
		column = Platypus.Frame(leftMargin, doc.bottomMargin, frameWidth, frameHeight)
		frames.append(column)
	template = Platypus.PageTemplate(frames=frames)
	doc.addPageTemplates(template)

	PAGE_HEIGHT = defaultPageSize[0] #size in points
	PAGE_WIDTH  = defaultPageSize[1]
	styles = getSampleStyleSheet()
	style  = styles['Normal']
	style.fontName = 'Courier'
	style.fontSize = 6.5

	Title = ('Report containing {} of {} putative SNPs for {} and {}'.format(
		str(quantityWantSites), str(len(pairwiseSNPpositions)),
		os.path.basename(invcf1), os.path.basename(invcf2)))
	report = [Paragraph(Title, styles['Heading2'])]

	while numSites > 0:
		# handle SNP sites at beginning of Chrom (<50 bases in)
		posMinusFitty = (listWantSitesVCF[numSites - 1] - 50)
		centeredPos = str(max(posMinusFitty, 0))

		pos = str(vcfData1[numSites-1][0])
		gap = Platypus.Spacer(0.25, 0.05*inch)

		# vcfData lists are ordered: [pos, chrom, qual, DP, MQ, alt]
		for sample in [[vcfData1, inbam1, S1Name], [vcfData2, inbam2, S2Name]]:
			pileup = Platypus.Preformatted(get_ttview(sample[1], infasta,
								(sample[0][1][1]), centeredPos, rows), style)

			qual = sample[0][numSites-1][2]
			DP   = sample[0][numSites-1][3]
			MQ   = sample[0][numSites-1][4]
			SNP  = str(sample[0][numSites-1][5])
			
			header = Paragraph('{} at position {} for {} with a QUAL of {}, MQ of {}, and raw read depth (DP) of {}'.format(
				SNP, pos, sample[2], qual, MQ, DP), styles['Heading6'])
			report.append(Platypus.KeepTogether([gap, header, pileup]))

		numSites -= 1

	doc.build(report)