def add_catalog_title(self, title):
        # self.obj.append(BookMark(title, level=0))
        self.obj.append(Paragraph('<b>' + title + '</b>', headstyle))

        toc = TableOfContents()
        toc.levelStyles = [
            PS(fontName='song',
               fontSize=10,
               name='TOCHeading1',
               leftIndent=10,
               firstLineIndent=-20,
               spaceBefore=0,
               leading=12),
            PS(fontName='song',
               fontSize=10,
               name='TOCHeading2',
               leftIndent=20,
               firstLineIndent=-20,
               spaceBefore=0,
               leading=12),
            PS(fontName='song',
               fontSize=10,
               name='TOCHeading3',
               leftIndent=30,
               firstLineIndent=-20,
               spaceBefore=0,
               leading=12),
        ]
        self.obj.append(toc)
Example #2
0
def main():
    with open(JSON_PATH) as file:
        # Read and parse JSON file
        data = json.loads(file.read())

        # Default pdf values
        doc = MyDocTemplate(PDF_PATH)
        toc = TableOfContents()
        toc.levelStyles = [
            ParagraphStyle(name="Heading1", fontSize=14, leading=16),
            ParagraphStyle(name="Heading2",
                           fontSize=12,
                           leading=14,
                           leftIndent=10),
            ParagraphStyle(name="Heading3",
                           fontSize=10,
                           leading=12,
                           leftIndent=20),
        ]

        elements = [
            Paragraph("PEAS Report", style=styles["Title"]),
            Spacer(0, 30), toc,
            PageBreak()
        ]

        # Iterate over all top level sections and build their elements.
        for title in data.keys():
            element_list = build_main_section(data[title], title)
            elements.extend(element_list)

        doc.multiBuild(elements)
Example #3
0
    def __init__(self,
                 story=None,
                 pagesize='A4',
                 fontsize='normal',
                 firstPageNumber=1):

        self._fontsize = fontsize
        self._indexedFlowable = []  #indexedFlowable
        self._toc = TableOfContents()
        self._story = story
        if story is None:
            self._story = []
            self._story.append(PageBreak())

        self._toc = TableOfContents()
        self._processTOCPage()
        self._indexedFlowable = {}
        self._fileDummy = FileDummy()

        self._doc = DocTemplateWithTOC(
            self._toc,
            self._indexedFlowable,
            self._fileDummy,
            firstPageNumber=firstPageNumber,
            pagesize=PDFSizes().PDFpagesizes[pagesize])

        self._PAGE_HEIGHT = PDFSizes().PDFpagesizes[pagesize][1]
        self._PAGE_WIDTH = PDFSizes().PDFpagesizes[pagesize][0]

        setTTFonts()
Example #4
0
    def __init__(self, output_file: str, **kwargs):
        """
        Constructor for the PDF Creator class
        """

        # Check for stray kwargs
        if kwargs:
            raise TypeError("got an unexpected keyword argument '%s'" % list(kwargs.keys())[0])

        # Define variables used during creation
        global doc, elements, styleSheet, doc_color
        global table_data_reg_list, table_data_field_list, toc

        # Create the document
        doc = MySimpleDocTemplate(output_file, pagesize=A4)

        # container for the 'Flowable' objects
        elements = []

        ## Table data
        table_data_reg_list = []
        table_data_field_list = []

        # Document color
        #doc_color = darkgrey
        #doc_color = dimgrey
        #doc_color = black
        doc_color  = colors.HexColor(0x24001e)

        # Create the style sheet
        styleSheet = getSampleStyleSheet()

        # Add more custom styles
        self.add_more_styles()

        # First page
        elements.append(PageBreak())

        # TOC
        h1 = ParagraphStyle(name = 'Heading1',
                            fontName=_baseFontNameB,
                            textColor=doc_color,
                            fontSize = 14,
                            spaceBefore=10,
                            leading = 16)

        h2 = ParagraphStyle(name = 'Heading2',
                            fontName=_baseFontName,
                            textColor=doc_color,
                            fontSize = 12,
                            leading = 14)

        # Table of contents 
        toc = TableOfContents()
        toc.levelStyles = [h1, h2]

        elements.append(Paragraph('Table of Contents', styleSheet["Header1Toc"]))
        elements.append(Spacer(1, 1*inch))
        elements.append(toc)
        elements.append(PageBreak())
Example #5
0
    def generate(self, report_elements=[]):
        elements = []
        h1 = ParagraphStyle(name='Heading1', fontSize=14, leading=16)
        h2 = ParagraphStyle(name='Heading2',
                            fontSize=12,
                            leading=14,
                            leftIndent=5)

        # First page
        elements.append(Paragraph("", self.styles['Normal']))
        elements.append(NextPageTemplate('OneCol'))
        elements.append(PageBreak())

        self.add_title(elements, "Table of contents")
        toc = TableOfContents()
        # For conciseness we use the same styles for headings and TOC entries
        toc.levelStyles = [h1, h2]
        elements.append(toc)
        elements.append(PageBreak())

        if len(report_elements) > 0:
            elements.extend(report_elements)

        self.add_title(elements, "Organisation")
        elements.append(self.last_page())
        elements.append(PageBreak())

        self.multiBuild(elements)
Example #6
0
def ReportGen(request, owner_name):
    buff=StringIO()      
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=ReportOnShaastra.pdf'
    sno=1
    elements=[]
    toc = TableOfContents()
   
    # For conciseness we use the same styles for headings and TOC entries
    toc.levelStyles = [h1, h2]
    elements.append(Paragraph('Shaastra Report',centered))
    elements.append(Paragraph('Table Of Contents',centered))
    elements.append(toc)
    elements.append(PageBreak())

    position_on_page=PAGE_HEIGHT-FRAME_BORDER
    
    users_in_department=userprofile.objects.filter(department = request.user.get_profile().department )
    if is_core(request.user):    
        tasks=Task.objects.filter(creator__in = users_in_department ).order_by('creation_date')
        elements.append(Paragraph('Tasks made by your Department',h1))
        elements.append(big_spacer)
        position_on_page = position_on_page - h1.fontSize - big_spacer_height
        for task in tasks:
            position_on_page,sno=ShowTask(request,elements,position_on_page,sno,task)
        elements.append(PageBreak())    
        position_on_page=PAGE_HEIGHT-FRAME_BORDER
        elements.append(Paragraph('SubTasks given to your Department',h1))
        elements.append(big_spacer)
        tasks=SubTask.objects.filter(department = request.user.get_profile().department ).order_by('creation_date')
        position_on_page = position_on_page - h1.fontSize - big_spacer_height
    
        for task in tasks:
            position_on_page,sno=ShowSubTask(request,elements,position_on_page,sno,task)
        elements.append(PageBreak())
    

    position_on_page=PAGE_HEIGHT-FRAME_BORDER
    
    sno=1
    if is_core(request.user):
        subtasks=SubTask.objects.filter(creator__in = users_in_department).order_by('creation_date')  
      
        elements.append(Paragraph('Sub-Tasks given to your coords',h1))
        elements.append(big_spacer)
        position_on_page = position_on_page - h1.fontSize - big_spacer_height          
        
    elif is_coord(request.user):         
        subtasks = request.user.subtask_set.all().order_by('creation_date')         
        elements.append(Paragraph('Sub-Tasks given to you',h1))
        elements.append(big_spacer)
        position_on_page = position_on_page - h1.fontSize - big_spacer_height
       
    for subtask in subtasks:
        position_on_page,sno=ShowSubTask(request,elements,position_on_page,sno,subtask)
            
    doc  = MyDocTemplate(buff)     
    doc.multiBuild(elements)
    response.write(buff.getvalue())
    return response
Example #7
0
def gen_pdf(generator, output, toc=True):
    addMapping(DEFAULT_FONT, 1, 1, DEFAULT_FONT)

    story = []

    if toc:
        title_style = ParagraphStyle(fontName=DEFAULT_FONT,
                                     fontSize=15,
                                     name='TOC',
                                     spaceAfter=10)
        story.append(Paragraph('目次', title_style))

        toc = TableOfContents()
        toc.levelStyles = [
            ParagraphStyle(fontName=DEFAULT_FONT,
                           fontSize=8,
                           name='body',
                           spaceAfter=4,
                           justifyBreaks=1)
        ]

        story.append(toc)
        story.append(PageBreak())

    story.extend(generator.convert())

    doc = DocTemplate(output)
    pdfmetrics.registerFont(TTFont(DEFAULT_FONT, DEFAULT_FONT_FILE))
    doc.multiBuild(story)
Example #8
0
 def appendToc(self):
     toc = TableOfContents()
     toc.levelStyles = [self.document.styles['TOCHeading1'],
                        self.document.styles['TOCHeading2'],
                        self.document.styles['TOCHeading3'],
                        self.document.styles['TOCHeading4']
                        ]
     self.document.append(toc)
Example #9
0
def create_toc():
    """Creates the table of contents"""
    table_of_contents = TableOfContents()
    table_of_contents.dotsMinLevel = 0
    header1 = ParagraphStyle(name='Heading1', fontSize=16, leading=16)
    header2 = ParagraphStyle(name='Heading2', fontSize=14, leading=14)
    table_of_contents.levelStyles = [header1, header2]
    return [table_of_contents, PageBreak()]
Example #10
0
    def __init__(self, doc):
        self.docname = doc
        self.page_counter = 2
        self.w, self.h = letter
        self.doc = BaseDocTemplate(self.docname, pagesize=letter)
        self.landscape = Frame(self.doc.leftMargin,
                               self.doc.bottomMargin,
                               self.doc.height,
                               self.doc.width,
                               id="Normal")

        self.portrait = Frame(self.doc.leftMargin,
                              self.doc.bottomMargin,
                              self.doc.width,
                              self.doc.height,
                              id="Normal")

        self.tportrait = Frame(self.doc.leftMargin,
                               self.doc.bottomMargin,
                               self.doc.width,
                               self.doc.height,
                               id="Normal")
        ttemplate = PageTemplate(id='tportrait',
                                 frames=self.tportrait,
                                 onPage=self.make_title_page)
        ptemplate = PageTemplate(id='portrait',
                                 frames=self.portrait,
                                 onPage=self.make_portrait)
        ltemplate = PageTemplate(id='landscape',
                                 frames=self.landscape,
                                 onPage=self.make_landscape)
        self.doc.addPageTemplates([ttemplate, ptemplate, ltemplate])
        self.styles = getSampleStyleSheet()

        self.start = ""
        self.end = ""
        self.story = []
        self.pgType = "Letter"
        self.image = ""
        self.cimage = ""
        self.client = ""

        self.toc = TableOfContents()
        self.toc.levelStyles = [
            PS(fontName='Times-Bold',
               fontSize=10,
               name='TOCHeading1',
               leftIndent=20,
               firstLineIndent=-20,
               spaceBefore=10,
               leading=16),
            PS(fontSize=10,
               name='TOCHeading2',
               leftIndent=40,
               firstLineIndent=-20,
               spaceBefore=5,
               leading=12),
        ]
Example #11
0
def add_toc():
    toc = TableOfContents()
    toc.levelStyles = [
        PS(fontName='Times-Bold', fontSize=20, name='TOCHeading1', leftIndent=20, firstLineIndent=-20, spaceBefore=10,
           leading=16),
        PS(fontSize=18, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, spaceBefore=5, leading=12),
    ]
    story.append(toc)
    story.append(Paragraph('<b>Table of contents</b>', centered))
    story.append(PageBreak())
Example #12
0
    def event_go(self):
        story = list()  # 报告内容存储结构
        story.append(PageBreak())
        # 目录
        toc = TableOfContents()
        toc.dotsMinLevel = 0
        toc.levelStyles = [H1, H2, H3]
        story.append(Paragraph('目录', toc1))
        story.append(toc)
        # 分页
        story.append(PageBreak())
        add_title(story, '1 前言', h1)
        add_title(story, '1.1 报告阅读说明', h2)
        story.append(
            Paragraph(
                '本报告是安全事件情况的统计,主要内容包含攻击源/目标TOP5,安全事件协议分布,安全事件来源分布,'
                '以及安全事件总数随时间分布趋势。', body))
        story.append(Paragraph('北京天地和兴科技有限公司感谢您对我们的信任和支持。现将安全事件报告呈上。', body))
        if self.report_method in [1, 2, 3]:
            add_title(story, '1.2 周期性报表', h2)
        else:
            add_title(story, '1.2 自定义报表', h2)
        self.base_info_table(story)
        story.append(PageBreak())
        story.append(Paragraph('2 安全事件概述', h1))
        add_title(story, '2.1 源地址top5', h2)
        self.src_table(story)
        add_title(story, '2.2 目的地址top5', h2)
        self.dst_table(story)
        story.append(PageBreak())
        add_title(story, '2.3 安全事件协议类型分布图', h2)
        self.event_proto_figure(story)
        story.append(PageBreak())
        add_title(story, '2.4 安全事件来源分布图', h2)
        self.event_src_figure(story)
        add_title(story, '2.5 事件时间分布趋势图', h2)
        self.event_time(story)

        story.append(PageBreak())
        # about_us_3(story)

        try:
            doc = MyDocTemplate(path + '/pdf_tmp/event_report.pdf')
            logger.info(
                "====================enter event report multiBuild............."
            )
            doc.multiBuild(story,
                           onFirstPage=firstPages,
                           onLaterPages=laterPages)
            os.system("rm -rf " + path + "/tmp/")
            os.system("mv " + path + "/pdf_tmp/event_report.pdf " +
                      "/data/report/alarm/")
        except:
            logger.error("MyDocTemplate build error.")
            logger.error(traceback.format_exc())
Example #13
0
    def process(self, block, context):
        toc = TableOfContents()
        toc.dotsMinLevel = 0
        toc.levelStyles = [
            context.styleSheet["Toc0"], context.styleSheet["Toc1"],
            context.styleSheet["Toc2"], context.styleSheet["Toc3"]
        ]

        content = []
        content.append(toc)
        return content
Example #14
0
def doTableOfContents():
    toc = TableOfContents()
    toc.levelStyles = [
        PS(fontName='Times-Bold', fontSize=14, name='TOCHeading1', leftIndent=20, firstLineIndent=-20, leading=14),
        PS(fontSize=12, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, leading=12),
    ]
    text = 'Table of contents'
    doHeading( text, PS(name = 'Heading1', fontName='Times-Bold', fontSize = 18, alignment = 1, leading = 16 ))
    story.append(Spacer(1,6))
    story.append(toc)
    story.append(PageBreak())
Example #15
0
def getTabelOfContents():
    """
    returns toc with 3 customized headings
    """
    toc = TableOfContents()
    toc.levelStyles = [
        PS(fontSize=12, name='TOCHeading1', leftIndent=20, firstLineIndent=-20, spaceBefore=6, leading=14), #fontName='Times-Bold', 
        PS(fontSize=10, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, spaceBefore=4, leading=12),
        PS(fontSize=8, name='TOCHeading3', leftIndent=50, firstLineIndent=-20, spaceBefore=2, leading=10),
        ]
    return toc
Example #16
0
def simple_toc():
    doc = SimpleDocTemplate("simple_toc.pdf")
    story = []
    styles = getSampleStyleSheet()

    toc = TableOfContents()
    toc.levelStyles = [
        ParagraphStyle(fontName='Helvetica',
                       fontSize=14,
                       name='Heading1',
                       leftIndent=20,
                       firstLineIndent=-20,
                       spaceBefore=5,
                       leading=16),
        ParagraphStyle(fontName='Times-Roman',
                       fontSize=14,
                       name='Heading2',
                       leftIndent=20,
                       firstLineIndent=-20,
                       spaceBefore=5,
                       leading=16),
    ]
    story.append(toc)

    ipsum = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
        nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
        reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
        culpa qui officia deserunt mollit anim id est laborum.'''

    para = Paragraph("The Beginning", style=styles['Heading1'])
    story.append(DelayedRef(toc, 0, 'The Beginning', 1))
    story.append(para)
    para = Paragraph(ipsum, style=styles['Normal'])
    story.append(para)
    story.append(PageBreak())

    para = Paragraph("The Middle", style=styles['Heading1'])
    story.append(DelayedRef(toc, 0, 'The Middle', 2))
    story.append(para)
    para = Paragraph("The Middle Sub-Header", style=styles['Heading2'])
    story.append(DelayedRef(toc, 1, 'The Middle Sub-Header', 2))
    story.append(para)
    para = Paragraph(ipsum, style=styles['Normal'])
    story.append(para)
    story.append(PageBreak())

    para = Paragraph("The End", style=styles['Heading1'])
    story.append(DelayedRef(toc, 0, 'The End', 3))
    story.append(para)

    doc.multiBuild(story)
def main():
    try:
        path_omd = Path("%s/git/check_mk/omd/" % Path.home())
        path_license_texts = path_omd / "license_sources/license_texts/"
        path_pdf = path_omd / "License_texts.pdf"
        path_cover = path_omd / "license_sources/licenses_cover.pdf"
    except:
        raise OSError

    registerFont(TTFont('Calibri', 'Calibri.ttf'))
    doc = SimpleDocTemplate(
        str(path_pdf),
        pagesize=letter,
        bottomMargin=.4 * inch,
        topMargin=.6 * inch,
        rightMargin=.8 * inch,
        leftMargin=.8 * inch)
    toc = TableOfContents()
    toc.levelStyles = [
        PS(fontName='Calibri',
           fontSize=14,
           name='TOCHeading1',
           leftIndent=20,
           firstLineIndent=-20,
           spaceBefore=5,
           leading=16),
        PS(fontSize=12, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, leading=12),
    ]
    title = PS(name='Title', fontSize=24, leading=16)
    h1 = PS(name='Heading1', fontSize=16, leading=16)
    normal = PS(name='Normal', fontSize=8)
    spacer = Spacer(width=0, height=2 * cm)

    story = []
    story.append(Paragraph('<b>Content</b>', title))
    story.append(spacer)
    story.append(toc)

    for file_path in sorted(path_license_texts.iterdir()):
        with file_path.open(encoding="utf-8") as txt_file:
            headline = "<b>%s</b>" % txt_file.readline().replace("\n", "<br /><br />\n")
            text_content = txt_file.read().replace("\n", "<br />\n")
        story.append(PageBreak())
        story.append(heading(headline, h1))
        story.append(Paragraph(text_content, normal))

    doc = MyDocTemplate(str(path_pdf))
    doc.multiBuild(story)

    pdf_merger = PdfFileMerger()
    pdf_merger.append(PdfFileReader(str(path_cover)))
    pdf_merger.append(PdfFileReader(str(path_pdf)))
    pdf_merger.write(str(path_pdf))
Example #18
0
    def test0(self):
        """Test story with TOC and a cascaded header hierarchy.

        The story should contain exactly one table of contents that is
        immediatly followed by a list of of cascaded levels of header
        lines, each nested one level deeper than the previous one.

        Features to be visually confirmed by a human being are:

            1. TOC lines are indented in multiples of 1 cm.
            2. Wrapped TOC lines continue with additional 0.5 cm indentation.
            3. ...
        """

        maxLevels = 12

        # Create styles to be used for document headers
        # on differnet levels.
        headerLevelStyles = []
        for i in range(maxLevels):
            headerLevelStyles.append(makeHeaderStyle(i))

        # Create styles to be used for TOC entry lines
        # for headers on differnet levels.
        tocLevelStyles = []
        d, e = tableofcontents.delta, tableofcontents.epsilon
        for i in range(maxLevels):
            tocLevelStyles.append(makeTocHeaderStyle(i, d, e))

        # Build story.
        story = []
        styleSheet = getSampleStyleSheet()
        bt = styleSheet['BodyText']

        description = '<font color=red>%s</font>' % self.test0.__doc__
        story.append(XPreformatted(description, bt))

        toc = TableOfContents()
        toc.levelStyles = tocLevelStyles
        story.append(toc)

        for i in range(maxLevels):
            story.append(Paragraph('HEADER, LEVEL %d' % i,
                                   headerLevelStyles[i]))
            #now put some body stuff in.
            txt = randomtext.randomText(randomtext.PYTHON, 5)
            para = Paragraph(txt, makeBodyStyle())
            story.append(para)

        path = outputfile('test_platypus_toc.pdf')
        doc = MyDocTemplate(path)
        doc.multiBuild(story)
Example #19
0
    def test0(self):
        """Test story with TOC and a cascaded header hierarchy.

        The story should contain exactly one table of contents that is
        immediatly followed by a list of of cascaded levels of header
        lines, each nested one level deeper than the previous one.

        Features to be visually confirmed by a human being are:

            1. TOC lines are indented in multiples of 1 cm.
            2. Wrapped TOC lines continue with additional 0.5 cm indentation.
            3. ...
        """

        maxLevels = 12

        # Create styles to be used for document headers
        # on differnet levels.
        headerLevelStyles = []
        for i in range(maxLevels):
            headerLevelStyles.append(makeHeaderStyle(i))

        # Create styles to be used for TOC entry lines
        # for headers on differnet levels.
        tocLevelStyles = []
        d, e = tableofcontents.delta, tableofcontents.epsilon
        for i in range(maxLevels):
            tocLevelStyles.append(makeTocHeaderStyle(i, d, e))

        # Build story.
        story = []
        styleSheet = getSampleStyleSheet()
        bt = styleSheet['BodyText']

        description = '<font color=red>%s</font>' % self.test0.__doc__
        story.append(XPreformatted(description, bt))

        toc = TableOfContents()
        toc.levelStyles = tocLevelStyles
        story.append(toc)

        for i in range(maxLevels):
            story.append(Paragraph('HEADER, LEVEL %d' % i,
                                   headerLevelStyles[i]))
            #now put some body stuff in.
            txt = randomtext.randomText(randomtext.PYTHON, 5)
            para = Paragraph(txt, makeBodyStyle())
            story.append(para)

        path = outputfile('test_platypus_toc.pdf')
        doc = MyDocTemplate(path)
        doc.multiBuild(story)
Example #20
0
    def proto_go(self):
        story = list()  # 报告内容存储结构
        story.append(PageBreak())
        # 目录
        toc = TableOfContents()
        toc.dotsMinLevel = 0
        toc.levelStyles = [H1, H2, H3]
        story.append(Paragraph('目录', toc1))
        story.append(toc)
        # 分页
        story.append(PageBreak())
        add_title(story, '1 前言', h1)
        add_title(story, '1.1 报告阅读说明', h2)
        story.append(
            Paragraph('本报告是协议审计情况的统计,主要内容包含协议类型分布,TOP特征值展示,'
                      '以及协议数随时间分布趋势。', body))
        story.append(Paragraph('北京天地和兴科技有限公司感谢您对我们的信任和支持。现将安全审计报告呈上。', body))
        if self.report_method in [1, 2, 3]:
            add_title(story, '1.2 周期性报表', h2)
        else:
            add_title(story, '1.2 自定义报表', h2)
        self.base_info_table(story)
        story.append(PageBreak())
        story.append(Paragraph('2 审计概述', h1))
        add_title(story, '2.1 协议类型分布图', h2)
        self.proto_figure(story)
        add_title(story, '2.2 源地址-目的地址top5', h2)
        self.src_dst_table(story)
        story.append(PageBreak())
        add_title(story, '2.3 协议时间分布趋势图', h2)
        self.proto_time(story)
        # add_title(story, '2.4 传输层分布', h2)
        # self.l2_figure(story)
        # story.append(PageBreak())
        # about_us_3(story)

        try:
            doc = MyDocTemplate(path + '/pdf_tmp/audit_report.pdf')
            logger.info(
                "====================enter proto report multiBuild............."
            )
            doc.multiBuild(story,
                           onFirstPage=firstPages,
                           onLaterPages=laterPages)
            os.system("rm -rf " + path + "/tmp/")
            os.system("mv " + path + "/pdf_tmp/audit_report.pdf " +
                      "/data/report/protocal/")
        except:
            logger.error("MyDocTemplate build error.")
            logger.error(traceback.format_exc())
Example #21
0
    def add_table_of_contents(self):
        """

        :param self:
        :return TOC :
        """
        self.add_heading('Table of Contents', htmltag='centered-bold')
        toc = TableOfContents()
        toc.levelStyles = [
            PS(fontName='Times-Bold', fontSize=18, name='TOCHeading1', leftIndent=10, firstLineIndent=-15, spaceBefore=10, leading=16),
            PS(fontName='Times-Italic',fontSize=16, name='TOCHeading2', leftIndent=22, firstLineIndent=-15, spaceBefore=5, leading=12),
            PS(fontName='Times-Italic',fontSize=14, name='TOCHeading3', leftIndent=34, firstLineIndent=-15, spaceBefore=5, leading=12),
            PS(fontName='Times-Italic',fontSize=12, name='TOCHeading4', leftIndent=46, firstLineIndent=-15, spaceBefore=5, leading=12)
        ]
        self.flowables.append(toc)
Example #22
0
 def set_toc(self):
     # Create an instance of TableOfContents. Override the level styles (optional)
     # and add the object to the story
     toc = TableOfContents()
     toc.levelStyles = [
         PS(fontSize=12, name='TOCHeading1', leftIndent=0, firstLineIndent=-20,  spaceBefore=0, leading=10),
         PS(fontSize=11, name='TOCHeading2', leftIndent=10, firstLineIndent=-20, spaceBefore=0, leading=10),
         PS(fontSize=10, name='TOCHeading3', leftIndent=20, firstLineIndent=-20, spaceBefore=0, leading=10),
         PS(fontSize=9, name='TOCHeading4', leftIndent=30, firstLineIndent=-20, spaceBefore=0, leading=10),
         PS(fontSize=8, name='TOCHeading5', leftIndent=40, firstLineIndent=-20, spaceBefore=0, leading=10),
     ]
     self.elements.append(Paragraph(self.title, self.style['centered']))
     #self.elements.append(Paragraph(_("Organization: <b>%s</b>") % self.org.name, self.style[1]))
     self.elements.append(toc)
     self.elements.append(PageBreak())
 def __init__(self, includeTOC=True):
     self.contents = []
     self.toc_included = includeTOC
     self.toc = TableOfContents()
     self.toc.levelStyles = [self.toc_h1, self.toc_h2]
     self.headingnumber = [0, 0, 0, 0]
     self.table_data = []
Example #24
0
    def begin(self, name='', typ=''):
        styleSheet = getSampleStyleSheet()
        self.code = styleSheet['Code']
        self.bt = styleSheet['BodyText']
        self.story = []

        # Cover page
        t = time.gmtime(time.time())
        timeString = time.strftime("%Y-%m-%d %H:%M", t)
        self.story.append(
            Paragraph(
                '<font size=18>Documentation for %s "%s"</font>' % (typ, name),
                self.bt))
        self.story.append(
            Paragraph(
                '<font size=18>Generated by: graphdocpy.py version %s</font>' %
                __version__, self.bt))
        self.story.append(
            Paragraph('<font size=18>Date generated: %s</font>' % timeString,
                      self.bt))
        self.story.append(
            Paragraph('<font size=18>Format: PDF</font>', self.bt))
        self.story.append(PageBreak())

        # Table of contents
        toc = TableOfContents()
        self.story.append(toc)
        self.story.append(PageBreak())
Example #25
0
def chordbook(filename, objects, title, subtitle, url, settings):
    """Generate the PDF version of the chordbook


  Parameters:

    filename (str): The complete path to the destination filename

    objects (list): An ordered list of song objects that will be inserted into
      this chordbook

    title (str): The title that will be shown in italics. This is normally
      something like "Collection"

    subtitle (str): The subtitle. This is normally the name of the collection

    url (str): The URL to this PDF, so people can download it

    settings (dict): Pelican settings


  Returns:

    SongBookTemplate: A ReportLab BaseDocTemplate with all the songs encoded
    inside.

  """

    from reportlab.platypus.tableofcontents import TableOfContents
    from reportlab.platypus import NextPageTemplate, PageBreak

    with pelican_locale(settings):
        doc = SongBookTemplate(filename)
        siteurl = settings.get('SITEURL', 'http://example.com')
        doc.author = settings.get('AUTHOR', 'Unknown Editor')
        doc.title = 'Cifras de %s' % siteurl
        doc.subject = 'Compilação de Letras e Cifras'
        dateformat = settings.get('DEFAULT_DATE_FORMAT', '%d/%m/%Y')

        story = cover_page(title, subtitle, url, siteurl, dateformat)

        #appends and prepares table of contents
        story.append(NextPageTemplate('TOC'))
        story.append(PageBreak())
        story.append(TableOfContents())
        story[-1].levelStyles[0] = style['toc-entry']
        story[-1].dotsMinLevel = 0  #connecting dots

        #adds the lyrics
        for o in objects:
            po = PdfSong(o, dateformat)
            po.add_page_template(doc)
            story.append(NextPageTemplate(po.template_id()))
            story.append(PageBreak())
            story += po.story(doc)

        #multi-pass builds are necessary to handle TOCs correctly
        doc.multiBuild(story)

        return doc
Example #26
0
    def _print_index(self, index, header):
        # Generate index page and TOC based on it
        story = self._story
        story.append(Spacer(self._get_page_width(), self.PAGE_HEIGHT / 4))
        story.append(RLParagraph(header, self._styles['title']))
        story.append(Spacer(self._get_page_width(), self.PAGE_HEIGHT / 5))
        story.append(RLParagraph(self.author, self._styles['title-author']))

        blocks = iter(index)
        for block in blocks:
            refs = [part.text for part in block if isinstance(part, Reference)]
            if '__endfrontpage__' in refs:
                story.append(PageBreak())
            if '__endbackpage__' in refs:
                break

            self._print_paragraph(block, root=True)

        self._find_page_info(blocks)

        # Print table of contents. index.md contains
        story.append(PageBreak())
        story.append(RLParagraph(self.TITLE_TOC, self._styles['h3']))
        self._add_toc(TableOfContents())

        # Generate list of sources
        if self.print_sources:
            story.append(PageBreak())
            for title, re_ext in self.SOURCE_INDEXES:
                story.append(RLParagraph(title, self._styles['h3']))
                self._add_toc(ListOfListings(re_ext))
Example #27
0
    def assets_go(self):
        story = list()  # 报告内容存储结构
        story.append(PageBreak())
        # 目录
        toc = TableOfContents()
        toc.dotsMinLevel = 0
        toc.levelStyles = [H1, H2, H3]
        story.append(Paragraph('目录', toc1))
        story.append(toc)
        # 分页
        story.append(PageBreak())
        add_title(story, '1 前言', h1)
        add_title(story, '1.1 报告阅读说明', h2)
        story.append(
            Paragraph('本报告是资产报告情况的统计,设备在线统计分布,设备类型统计分布,设备身份状态统计分布。', body))
        story.append(Paragraph('北京天地和兴科技有限公司感谢您对我们的信任和支持,现将资产报告呈上。', body))
        if self.report_method in [1, 2, 3]:
            add_title(story, '1.2 周期性报表', h2)
        else:
            add_title(story, '1.2 自定义报表', h2)
        self.base_info_table(story)
        story.append(PageBreak())
        story.append(Paragraph('2 资产报告概述', h1))
        add_title(story, '2.1 设备在线数量分布图', h2)
        self.assets_live(story)
        story.append(PageBreak())
        add_title(story, '2.2 设备类型分布图', h2)
        self.assets_type(story)
        story.append(PageBreak())
        add_title(story, '2.3 设备身份状态分布图', h2)
        self.assets_status(story)

        try:
            doc = MyDocTemplate(path + '/pdf_tmp/assets_report.pdf')
            logger.info(
                "====================enter assets report multiBuild............."
            )
            doc.multiBuild(story,
                           onFirstPage=firstPages,
                           onLaterPages=laterPages)
            os.system("rm -rf " + path + "/tmp/")
            os.system("mv " + path + "/pdf_tmp/assets_report.pdf " +
                      "/data/report/assets/")
        except:
            logger.error("MyDocTemplate build error.")
            logger.error(traceback.format_exc())
Example #28
0
def armar_pdf():
    centered = PS(name = 'centered',
        fontSize = 30,
        leading = 16,
        alignment = 1,
        spaceAfter = 20)
    
    h1 = PS(
        name = 'Heading1',
        fontSize = 14,
        leading = 16)
    
    
    h2 = PS(name = 'Heading2',
        fontSize = 12,
        leading = 14)
    
    
    # Build story.
    story = []
    
    # Create an instance of TableOfContents. Override the level styles (optional)
    # and add the object to the story
    
    toc = TableOfContents()
    toc.levelStyles = [
        PS(fontName='Times-Bold', fontSize=20, name='TOCHeading1', leftIndent=20, firstLineIndent=-20, spaceBefore=10, leading=16),
        PS(fontSize=18, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, spaceBefore=5, leading=12),
    ]
    story.append(toc)
    
    story.append(Paragraph('<b>Table of contents</b>', centered))
    story.append(PageBreak())
    story.append(Paragraph('First heading', h1))
    story.append(Paragraph('Text in first heading', PS('body')))
    story.append(Paragraph('First sub heading', h2))
    story.append(Paragraph('Text in first sub heading', PS('body')))
    story.append(PageBreak())
    story.append(Paragraph('Second sub heading', h2))
    story.append(Paragraph('Text in second sub heading', PS('body')))
    story.append(PageBreak())
    story.append(Paragraph('Last heading', h1))
    doc = MyDocTemplate('mintoc.pdf')
    doc.multiBuild(story)
Example #29
0
def pagecat(request):
    pdf1 = "pdf1.pdf"
    pdf2 = "pdf2.pdf"

    pdfs = [pdf1, pdf2]
    #

    Story = []

    centered = ParagraphStyle(name='centered',
                              fontSize=30,
                              leading=16,
                              alignment=1,
                              spaceAfter=20)

    h1 = ParagraphStyle(
        name='Heading1',
        fontSize=14,
        leading=16)

    h2 = ParagraphStyle(name='Heading2',
                        fontSize=12,
                        leading=14)

    toc = TableOfContents()
    toc.levelStyles = [
        ParagraphStyle(fontName='Times-Bold', fontSize=20, name='TOCHeading1', leftIndent=20,
                       firstLineIndent=-20, spaceBefore=10, leading=16),
        ParagraphStyle(fontSize=18, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, spaceBefore=5, leading=12),
    ]
    Story.append(toc)
    manual_toc = True
    if manual_toc:
        cpt = 0
        Story.append(Paragraph('<b>Table of contents</b>', centered))
        for fname in pdfs:
            Story.append(Paragraph('<includePdfPages filename="%s" pages="1" outlineText="crasher"/>' % fname, h1))

            Story.append(Paragraph('%s' % fname, h2))
            cpt = cpt + 1
    doc = MyDocTemplate('mintoc.pdf')

    doc.multiBuild(Story)
    return render(request, "test.html")
Example #30
0
    def create_table_of_contents (self) :
	self._bookmark_index = 0;
	h1 = ParagraphStyle(name = 'heading1', fontSize=22, leading=32, fontName='shoujinshu')
	self._toc = TableOfContents()
	self._toc.levelStyles = [h1]
	if len(self.story) == 1 :
	    item = self.story[0]
	    if item.__class__.__name__ == 'Image' :
		self.append_pagebreak()
	self.story.append(self._toc)
Example #31
0
      def __init__(self,doc):
          self.docname = doc
          self.page_counter = 2
          self.w,self.h = letter
          self.doc = BaseDocTemplate(self.docname,pagesize=letter)
          self.landscape = Frame(self.doc.leftMargin,
                                 self.doc.bottomMargin,
                                 self.doc.height,
                                 self.doc.width,
                                 id="Normal")

          self.portrait = Frame(self.doc.leftMargin,
                                self.doc.bottomMargin,
                                self.doc.width,
                                self.doc.height,
                                id="Normal")

          self.tportrait = Frame(self.doc.leftMargin,
                                self.doc.bottomMargin,
                                self.doc.width,
                                self.doc.height,
                                id="Normal")
          ttemplate = PageTemplate(id='tportrait',frames =self.tportrait, onPage=self.make_title_page)
          ptemplate = PageTemplate(id='portrait',frames =self.portrait, onPage=self.make_portrait)
          ltemplate = PageTemplate(id='landscape',frames =self.landscape, onPage=self.make_landscape)
          self.doc.addPageTemplates([ttemplate,ptemplate,ltemplate]) 
          self.styles = getSampleStyleSheet()
          self.toc = TableOfContents()
          self.start = ""
          self.end = ""
          self.story = []
          self.pgType = "Letter"
          self.image = ""
          self.cimage = ""
          self.client = ""


          self.toc = TableOfContents()
	  self.toc.levelStyles = [  
	            PS(fontName='Times-Bold', fontSize=14, name='TOCHeading1', leftIndent=20, firstLineIndent=-20, spaceBefore=10, leading=16),  
	            PS(fontSize=12, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, spaceBefore=5, leading=12),  
	            ]  
Example #32
0
    def __init__(self, *args, **kwargs):

        # The parent argument is to define the locality of
        # the TOC. If it's none, it's a global TOC and
        # any heading it's notified about is accepted.

        # If it's a node, then the heading needs to be "inside"
        # that node. This can be figured out because
        # the heading flowable keeps a reference to the title
        # node it was creatd from.
        #
        # Yes, this is gross.

        self.parent=kwargs.pop('parent')
        TableOfContents.__init__(self, *args, **kwargs)
        # reference ids for which this TOC should be notified
        self.refids = []
        # revese lookup table from (level, text) to refid
        self.refid_lut = {}
        self.linkColor = "#0000ff"
Example #33
0
    def __init__(self, *args, **kwargs):

        # The parent argument is to define the locality of
        # the TOC. If it's none, it's a global TOC and
        # any heading it's notified about is accepted.

        # If it's a node, then the heading needs to be "inside"
        # that node. This can be figured out because
        # the heading flowable keeps a reference to the title
        # node it was creatd from.
        #
        # Yes, this is gross.

        self.parent=kwargs.pop('parent')
        TableOfContents.__init__(self, *args, **kwargs)
        # reference ids for which this TOC should be notified
        self.refids = []
        # revese lookup table from (level, text) to refid
        self.refid_lut = {}
        self.linkColor = "#0000ff"
Example #34
0
 def __init__(self, includeTOC=True):
     self.contents = []
     self.toc_included = includeTOC
     self.toc = TableOfContents()
     self.toc.levelStyles = [self.toc_h1, self.toc_h2]
     self.headingnumber = [0, 0, 0, 0]
     self.table_data = []
     self.note_data = []
     self.table_validation = None
     # Set default configuration parameters
     rl_config.trustedHosts = ["localhost", "127.0.0.1"]
     rl_config.trustedSchemes = ["http", "https"]
    def __init__(self):
        RepTOC.__init__(self)

        self.toc_h1 = ParagraphStyle(name='Heading1',
                                     fontSize=14,
                                     fontName="Times-Bold",
                                     leftIndent=6)
        self.toc_h2 = ParagraphStyle(name='Heading2',
                                     fontSize=12,
                                     fontName="Times-Roman",
                                     leftIndent=12)
        self.toc_h3 = ParagraphStyle(name='Heading3',
                                     fontSize=11,
                                     fontName="Times-Roman",
                                     leftIndent=24)
        self.toc_h4 = ParagraphStyle(name='Heading4',
                                     fontSize=11,
                                     fontName="Times-Roman",
                                     leftIndent=32)

        self.levelStyles = [self.toc_h1, self.toc_h2, self.toc_h3, self.toc_h4]
Example #36
0
    def test0(self):

        h1 = PS(name='Heading1', fontSize=14, leading=16)
        h2 = PS(name='Heading2', fontSize=12, leading=14, leftIndent=2 * cm)

        # Build story.
        story = []
        toc = TableOfContents()
        # For conciseness we use the same styles for headings and TOC entries
        toc.levelStyles = [h1, h2]
        story.append(toc)
        story.append(PageBreak())
        story.append(Paragraph('First heading', h1))
        story.append(Paragraph('Text in first heading', PS('body')))
        story.append(Paragraph('First sub heading', h2))
        story.append(Paragraph('Text in first sub heading', PS('body')))
        story.append(PageBreak())
        story.append(Paragraph('Second sub heading', h2))
        story.append(Paragraph('Text in second sub heading', PS('body')))
        story.append(Paragraph('Last heading', h1))
        doc = MyDocTemplate(outputfile('test_multibuild.pdf'))
        doc.multiBuild(story)
Example #37
0
    def __init__(self, pdf):
        self.elements = []
        self.chapter_num = 1

        self.doc = TocDocTemplate(pdf)

        self.page_templates = OrderedDict()
        self.build_page_templates()

        self.toc = TableOfContents()

        self.footer_tag = "made with bookletpdf"
        self.footer_tag_link = "http://github.com/boscoh/bookletpdf"
        self.footer_font_size = 8
Example #38
0
		coverData.append(['MD5 check', 'failed'])
		log.info("MD5 check failed")

t=Table(coverData, colWidths=[200, 300])
t.setStyle(tableStyleStandard)                   
Story.append(t)

Story.append(NextPageTemplate('Later'))

Story.append(PageBreak())

# ----------- Table of Contents ----------------------------------------------------------------
Story.append(Paragraph("<font size=12>Table of Contents</font>", styles["Normal"]))
Story.append(Spacer(1, 6))

toc = TableOfContents()
toc.dotsMinLevel = 0
toc.levelStyles = [
    ParagraphStyle(
    	fontName='Times-Bold', 
    	fontSize=12, 
    	name='TOCHeading1', 
    	leftIndent=20, 
    	firstLineIndent=-20, 
    	spaceBefore=5, 
    	leading=6
    ),
    ParagraphStyle(
    	fontSize=10, 
    	name='TOCHeading2', 
    	leftIndent=40, 
Example #39
0
__version__ = '$Id$'
from tools.docco.rl_doc_utils import *
from reportlab.platypus.tableofcontents import TableOfContents
from datetime import datetime
import reportlab

title("ReportLab PDF Library")
title("User Guide")
centred('ReportLab Version ' + reportlab.Version)
centred(datetime.now().strftime('Document generated on %Y/%m/%d %H:%M:%S %Z'))

nextTemplate("TOC")

headingTOC()

toc = TableOfContents()
PS = ParagraphStyle
toc.levelStyles = [
    PS(fontName='Times-Bold', fontSize=14, name='TOCHeading1', leftIndent=20, firstLineIndent=-20, spaceBefore=5, leading=16),
    PS(fontSize=12, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, spaceBefore=0, leading=12),
    PS(fontSize=10, name='TOCHeading3', leftIndent=60, firstLineIndent=-20, spaceBefore=0, leading=12),
    PS(fontSize=10, name='TOCHeading4', leftIndent=100, firstLineIndent=-20, spaceBefore=0, leading=12),
]
getStory().append(toc)

nextTemplate("Normal")

########################################################################
#
#               Chapter 1
#
                print "- >" + text


if __name__ == '__main__':
    doc = WikiDocTemplate("manual.pdf", leftMargin= 0.5*inch, rightMargin= 0.5*inch,
                     topMargin= 0.5*inch, bottomMargin= 0.25*inch)

    story = []

    # Title Page
    story.append(Spacer(0, 3.5*inch))
    story.append(Paragraph(TITLE, styles['Title']))
    story.append(PageBreak())

    # Table of Contents
    toc = TableOfContents()
    toc.levelStyles = [styles['Normal']] * 6
    story.append(toc)
    story.append(PageBreak())

    parser = ContentParser(story)
    html = urllib2.urlopen(ROOT + "/knowledgebase").read().decode('utf8')
    parser.feed(html)
    parser.close()

    # crawl_page("/knowledgebase/articles/171592-how-to-print-your-tracks", story)

    print story
    print "Building PDF..."
    
    # Build PDF
Example #41
0
class hawkPDF:

      def __init__(self,doc):
          self.docname = doc
          self.page_counter = 2
          self.w,self.h = letter
          self.doc = BaseDocTemplate(self.docname,pagesize=letter)
          self.landscape = Frame(self.doc.leftMargin,
                                 self.doc.bottomMargin,
                                 self.doc.height,
                                 self.doc.width,
                                 id="Normal")

          self.portrait = Frame(self.doc.leftMargin,
                                self.doc.bottomMargin,
                                self.doc.width,
                                self.doc.height,
                                id="Normal")

          self.tportrait = Frame(self.doc.leftMargin,
                                self.doc.bottomMargin,
                                self.doc.width,
                                self.doc.height,
                                id="Normal")
          ttemplate = PageTemplate(id='tportrait',frames =self.tportrait, onPage=self.make_title_page)
          ptemplate = PageTemplate(id='portrait',frames =self.portrait, onPage=self.make_portrait)
          ltemplate = PageTemplate(id='landscape',frames =self.landscape, onPage=self.make_landscape)
          self.doc.addPageTemplates([ttemplate,ptemplate,ltemplate]) 
          self.styles = getSampleStyleSheet()
          self.toc = TableOfContents()
          self.start = ""
          self.end = ""
          self.story = []
          self.pgType = "Letter"
          self.image = ""
          self.cimage = ""
          self.client = ""


          self.toc = TableOfContents()
	  self.toc.levelStyles = [  
	            PS(fontName='Times-Bold', fontSize=14, name='TOCHeading1', leftIndent=20, firstLineIndent=-20, spaceBefore=10, leading=16),  
	            PS(fontSize=12, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, spaceBefore=5, leading=12),  
	            ]  


      def addTOC(self, page):
	  self.toc.beforeBuild()
          self.story.insert(page, NextPageTemplate('portrait'))
	  self.story.insert(page+1, self.toc);
          self.story.insert(page+2, PageBreak())

      def setCImage(self,image):
          self.cimage = image

      def setPImage(self,image):
          self.image = image

      def setTitle(self,text):
          self.title = text

      def setClient(self,text):
          self.client = text

      def setDates(self,start,end):
          self.startDate = start
          self.endDate = end

      def setClient(self,text):
          self.client = text

      def make_portrait(self,canvas,doc):
          canvas.saveState()
          canvas.setPageSize(letter)
          canvas.setFont("Times-Roman",10)
          canvas.drawString(6.25 * inch, self.h - 25,"Client Name: %s " % (self.client))
          canvas.line(.50 * inch, self.h - 50, 8 * inch, self.h - 50)
          canvas.line(.50 * inch,1 * inch, 8 * inch,1 * inch)
          canvas.drawString(inch, 0.75 * inch, "Page %d" % doc.page)
          canvas.drawString(inch * 1.5, 0.60 * inch, "Confidential Document.")
          canvas.restoreState()

      def make_landscape(self,canvas,doc):
          canvas.saveState()
          canvas.setFont("Times-Roman",10)
          canvas.setPageSize(landscape(letter))
          canvas.line(.50 * inch, self.w - 50, 10.75 * inch,self.w - 50)
          canvas.line(.50 * inch,1 * inch, 10.75 * inch,1 * inch)
          canvas.drawString(inch, 0.75 * inch, "Page %d" % doc.page)
          canvas.drawString(inch * 2.75, 0.60 * inch, "Confidential Document.")
          canvas.drawString(9.50 * inch,self.w - 25 ,"Client: %s" % self.client)
          canvas.restoreState()

      def make_title_page(self,canvas,doc):
          canvas.saveState()
          canvas.setFont("Times-Bold",30)
          canvas.drawString(1 * inch,9 * inch , self.title)
          canvas.setFont("Times-Bold",16)
          canvas.drawString(1 * inch,8.5 * inch,"Start (%s) - End (%s)" % (self.startDate,self.endDate))
          canvas.drawString(1 * inch,8.25 * inch,"Client: %s" % self.client)
          if self.image != "":
                aspect = self.get_aspect(self.image)
                canvas.drawImage(self.image,self.w-150,self.h-80,width=120,height=(120 * aspect))
          if self.cimage != "":
                aspect = self.get_aspect(self.cimage)
                canvas.drawImage(self.cimage,2.0625 * inch,self.h-400,width=self.w/2,height=(self.w/2 * aspect))
          canvas.restoreState()

      def get_aspect(self,path):
          img = utils.ImageReader(path)
          iw,ih = img.getSize()
          aspect = ih / float(iw)
          return aspect

      def setPortrait(self):
          self.story.append(NextPageTemplate('portrait'))
          self.addPageBreak()

      def setLandscape(self):
          self.story.append(NextPageTemplate('landscape'))
          self.addPageBreak()

      def setDates(self,start,end):
          self.startDate = start
          self.endDate = end

      def setCanvas(self,canvas):
          self.canvas = canvas  

      def addStory(self,text):
          t = Paragraph(text,self.styles["Normal"])
          self.story.append(t)
          self.story.append(Spacer(1,12))       

      def addStoryTitle(self,text):
          t = Paragraph(text,self.styles["Heading1"])
          self.story.append(t)
          self.story.append(Spacer(1,8))
          self.toc.addEntry(1, text, self.page_counter)

      def addTable(self,ndata,nkeys=None):
          data = []
          if not nkeys:
             keys = self.hlib.getKeys(ndata)
             data.append(keys)
          else:
             keys = nkeys 
             data.append(nkeys)
          for x in ndata:
              lister = [] 
              for b in range(len(keys)):
                  if keys[b] not in x:
                     outb = None
                  else:
                     outb = x[keys[b]]
                  t = Paragraph(str(outb),self.styles["Normal"])
                  lister.append(t)
              data.append(lister)

          tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),black),
                                 ('VALIGN',(0,0),(-1,-1),'TOP'),
                                 ('BOX',(0,0),(-1,-1),1,black),
                                 ('INNERGRID',(0,0),(-1,-1),1,black),
                                 ('BACKGROUND',(0,0),(-1,0),lightblue)])

          t = LongTable(data,repeatRows=1)
          t.setStyle(tblStyle)
          self.story.append(t)
          self.story.append(CondPageBreak(6))
 
      def addPageBreak(self):
          self.story.append(PageBreak())
          self.page_counter = self.page_counter + 1

      def addImage(self,image,w,h):
          self.story.append(Image(image,w,h))
          self.story.append(Spacer(1,12))

      def savePDF(self):
          self.addTOC(2)
          self.doc.build(self.story)
          self.story = []
Example #42
0
s_normal = styles['Normal']
s_right = ParagraphStyle(name='Right', parent=styles['Normal'], alignment=TA_RIGHT)
s_center = ParagraphStyle(name='Center', parent=styles['Normal'], alignment=TA_CENTER)
s_h1 = styles['Heading1']
s_h1_center = styles['Heading1']
s_h1_center.alignment = TA_CENTER
s_h1n = ParagraphStyle(name='Heading1n', parent=styles['Normal'], fontSize=18, leading=22, spaceAfter=6, alignment=TA_CENTER)
s_h1_toc = ParagraphStyle(name='Heading1toc', parent=styles['Heading1'], fontName='Helvetica', fontSize=16, leading=22, spaceBefore=4, spaceAfter=6, alignment=TA_LEFT)
s_h2_toc = ParagraphStyle(name='Heading2toc', parent=styles['Heading2'], fontName='Helvetica', fontSize=13, leading=22, spaceBefore=2, spaceAfter=4, alignment=TA_LEFT)
s_h2 = styles['Heading2']
s_code = styles['Code']

doc = None
story = []
toc = TableOfContents()
toc.levelStyles = [s_h1_toc, s_h2_toc]

global_alignment_generated = False
local_alignment_generated = False


def add_page_number(canvas, _):
    canvas.saveState()
    canvas.setFont('Helvetica', 9)
    text = "Page %s" % canvas.getPageNumber()
    canvas.drawRightString(A4[0] - 0.4 * inch, 0.25 * inch, text)
    canvas.restoreState()


def generate_splitline(width, height, color_a=chartreuse, color_b=coral):
Example #43
0
if flowable.__class__.__name__ == 'Paragraph':
    text = flowable.getPlainText()
    style = flowable.style.name
    if style == 'Heading1':
        self.notify('TOCEntry', (0, text, self.page))
        if style == 'Heading2':
            self.notify('TOCEntry', (1, text, self.page))
            h1 = PS(name = 'Heading1',
                    fontSize = 14,
                    leading = 16)
            h2 = PS(name = 'Heading2',
                    fontSize = 12,
                    leading = 14,
                    leftIndent = delta)
#
    story = []
    toc = TableOfContents()
# For conciseness we use the same styles for headings and TOC entries
    toc.levelStyles = [h1, h2]
    story.append(toc)
    story.append(PageBreak())
    story.append(Paragraph('First heading', h1))
    story.append(Paragraph('Text in first heading', PS('body')))
    story.append(Paragraph('First sub heading', h2))
    story.append(Paragraph('Text in first sub heading', PS('body')))
    story.append(PageBreak())
    story.append(Paragraph('Second sub heading', h2))
    story.append(Paragraph('Text in second sub heading', PS('body')))
    story.append(Paragraph('Last heading', h1))
    doc = MyDocTemplate('mintoc.pdf')
    doc.multiBuild(story)
Example #44
0
 def split(self, aW, aH):
     # Make sure _table exists before splitting.
     # This was only triggered in rare cases using sphinx.
     if not self._table:
         self.wrap(aW,aH)
     return TableOfContents.split(self, aW, aH)
Example #45
0
class cwPDF:

      def __init__(self,doc):
          self.docname = doc
          self.page_counter = 2
          self.w,self.h = letter
          self.doc = BaseDocTemplate(self.docname,pagesize=letter)
          self.landscape = Frame(self.doc.leftMargin,
                                 self.doc.bottomMargin,
                                 self.doc.height,
                                 self.doc.width,
                                 id="Normal")

          self.portrait = Frame(self.doc.leftMargin,
                                self.doc.bottomMargin,
                                self.doc.width,
                                self.doc.height,
                                id="Normal")

          self.tportrait = Frame(self.doc.leftMargin,
                                self.doc.bottomMargin,
                                self.doc.width,
                                self.doc.height,
                                id="Normal")
          ttemplate = PageTemplate(id='tportrait',frames =self.tportrait, onPage=self.make_title_page)
          ptemplate = PageTemplate(id='portrait',frames =self.portrait, onPage=self.make_portrait)
          ltemplate = PageTemplate(id='landscape',frames =self.landscape, onPage=self.make_landscape)
          self.doc.addPageTemplates([ttemplate,ptemplate,ltemplate]) 
          self.styles = getSampleStyleSheet()
          
          self.start = ""
          self.end = ""
          self.story = []
          self.pgType = "Letter"
          self.image = ""
          self.cimage = ""
          self.client = ""


          self.toc = TableOfContents()
	  self.toc.levelStyles = [  
	            PS(fontName='Times-Bold', fontSize=10, name='TOCHeading1', leftIndent=20, firstLineIndent=-20, spaceBefore=10, leading=16),  
	            PS(fontSize=10, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, spaceBefore=5, leading=12),  
	            ]  


      def addTOC(self, page):
	  self.toc.beforeBuild()
          self.story.insert(page, NextPageTemplate('portrait'))
	  self.story.insert(page+1, self.toc);
          self.story.insert(page+2, PageBreak())

      def setCImage(self,image):
          self.cimage = image

      def setPImage(self,image):
          self.image = image

      def setTitle(self,text):
          self.title = text

      def setClient(self,text):
          self.client = text

      def setDates(self,start,end):
          self.startDate = start
          self.endDate = end

      def setClient(self,text):
          self.client = text

      def make_portrait(self,canvas,doc):
          canvas.saveState()
          canvas.setPageSize(letter)
          canvas.setFont("Times-Roman",10)
          canvas.drawString(6.25 * inch, self.h - 25,"Client Name: %s " % (self.client))
          canvas.line(.50 * inch, self.h - 33, 8 * inch, self.h - 33)
          canvas.line(.50 * inch,.50 * inch, 8 * inch,.50 * inch)
          canvas.drawString(inch * 7.25, 0.25 * inch, "Page %d" % doc.page)
          canvas.drawString(inch * .50, 0.25 * inch, "Confidential Document.")
          canvas.restoreState()

      def make_landscape(self,canvas,doc):
          canvas.saveState()
          canvas.setFont("Times-Roman",10)
          canvas.setPageSize(landscape(letter))
          canvas.line(.50 * inch, self.w - 33, 10.75 * inch,self.w - 33)
          canvas.line(.50 * inch,.50 * inch, 10.75 * inch,.50 * inch)
          canvas.drawString(inch * 10.75, 0.75 * inch, "Page %d" % doc.page)
          canvas.drawString(inch * 1.75, 0.75 * inch, "Confidential Document.")
          canvas.drawString(9.50 * inch,self.w - 25 ,"Client: %s" % self.client)
          canvas.restoreState()

      def make_title_page(self,canvas,doc):
          canvas.saveState()
          canvas.setFont("Times-Bold",20)
          canvas.setFillColor(lightblue)
          canvas.drawString(1 * inch,9 * inch , self.title)
          canvas.setFont("Times-Bold",12)
          canvas.setFillColor(black)
          canvas.drawString(1 * inch,8.70 * inch,"Start (%s) - End (%s)" % (self.startDate,self.endDate))
          canvas.drawString(1 * inch,8.45 * inch,"Client: %s" % self.client)
          canvas.setFont("Times-Roman",10)
          canvas.setFillColor(grey)
          canvas.drawString(1 * inch,2.20 * inch,"Confidential: The following report contains confidential information. Do not distribute, email, mail, fax, or transfer ")
          canvas.drawString(1 * inch,2.05 * inch,"via any electronic mechanism unless it has been approved by the recipient company's security policy. All copies and")
          canvas.drawString(1 * inch,1.90 * inch,"backups of this document should be saved on protected storage at all times. Do not share any of the information")
          canvas.drawString(1 * inch,1.75 * inch,"contained within this report with anyone unless they are authorized to view the information. Violating within this ")
          canvas.drawString(1 * inch,1.60 * inch,"report with anyone unless they are authorized to view the information. Violating any of the previous instructions is")
          canvas.drawString(1 * inch,1.45 * inch,"grounds for termination.")
          if self.image != "":
                aspect = self.get_aspect(self.image)
                canvas.drawImage(self.image,self.w-150,self.h-80,width=120,height=(120 * aspect))
          if self.cimage != "":
                aspect = self.get_aspect(self.cimage)
                canvas.drawImage(self.cimage,2.0625 * inch,self.h-400,width=self.w/2,height=(self.w/2 * aspect))
          canvas.restoreState()

      def get_aspect(self,path):
          img = utils.ImageReader(path)
          iw,ih = img.getSize()
          aspect = ih / float(iw)
          return aspect

      def setPortrait(self):
          self.story.append(NextPageTemplate('portrait'))
          self.addPageBreak()

      def setLandscape(self):
          self.story.append(NextPageTemplate('landscape'))
          self.addPageBreak()

      def setDates(self,start,end):
          self.startDate = start
          self.endDate = end

      def setCanvas(self,canvas):
          self.canvas = canvas  

      def addStory(self,text):
          t = Paragraph(text,self.styles["Normal"])
          self.story.append(t)
          self.story.append(Spacer(1,12))       

      def addStoryTitle(self,text):
          t = Paragraph(text,self.styles["Heading1"])
          self.story.append(t)
          self.story.append(Spacer(1,8))
          self.toc.addEntry(1, text, self.page_counter)

      def getKeys(self,data):
             all = []
             for f in data.keys():
                 all.append(f)
             return all

      def addTable(self,ndata):
          data = []
          keys = self.getKeys(ndata)
          data.append(keys)
          for x in ndata:
              lister = []
              for b in keys:
                  outb = ndata[b]
                  t = Paragraph(str(outb),self.styles["Normal"])
                  lister.append(t)
          data.append(lister)

          tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),black),
                                 ('VALIGN',(0,0),(-1,-1),'TOP'),
                                 ('BOX',(0,0),(-1,-1),1,black),
                                 ('INNERGRID',(0,0),(-1,-1),1,black),
                                 ('BACKGROUND',(0,0),(-1,0),lightblue)])

          t = LongTable(data,repeatRows=1)
          t.setStyle(tblStyle)
          self.story.append(t)
          self.story.append(CondPageBreak(6))
 
      def addPageBreak(self):
          self.story.append(PageBreak())
          self.page_counter = self.page_counter + 1

      def addImage(self,image,w,h):
          self.story.append(Image(image,w,h))
          self.story.append(Spacer(1,12))

      def savePDF(self):
          self.addTOC(2)
          self.doc.build(self.story)
          self.story = []
Example #46
0
 def __init__(self, ext):
     self.ext = re.compile(r'([^.]*)\.' + ext)
     return TableOfContents.__init__(self)