示例#1
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()
    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)
示例#3
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
示例#4
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)
示例#5
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())
示例#6
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)
示例#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)
 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 = []
示例#9
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())
示例#10
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))
示例#11
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)
示例#12
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()]
示例#13
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),
        ]
示例#14
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)
示例#15
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())
示例#16
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())
示例#17
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
示例#18
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
示例#19
0
def simple_toc():
    doc = SimpleDocTemplate("Ejemplo11.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'])
    toc.addEntry(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'])
    toc.addEntry(0, 'The Middle', 2)
    story.append(para)
    para = Paragraph("The Middle Sub-Header", style=styles['Heading2'])
    toc.addEntry(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'])
    toc.addEntry(0, 'The End', 3)
    story.append(para)

    doc.multiBuild(story)
示例#20
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 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))
示例#22
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)
示例#23
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())
示例#24
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
示例#25
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())
示例#26
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)
    def story(self):
        """Return report as a list ready to be passed to MyDocTemplate multiBuild method."""
        tree = RenderTree(self)
        story = [
            Paragraph("<seqreset id='h1'/>", PARAGRAPH_STYLES['Normal']),
            NextPageTemplate('ContentPage'),
            PageBreak(),
            Paragraph('<b>Table of Contents</b>', PARAGRAPH_STYLES['centered']),
            TableOfContents(levelStyles=PARAGRAPH_STYLES['TOCHeadings']),
            PageBreak()
        ]

        for row in list(tree)[1:]:
            elements = list(row.node.elements.values())
            flowables = list(chain(*elements))
            story += flowables
        return story
示例#28
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())
示例#29
0
 def create_toc(self):
     self.toc = TableOfContents()
     self.toc.levelStyles = [
         ParagraphStyle(fontName='Times-Bold',
                        fontSize=14,
                        name='Heading1',
                        leftIndent=20,
                        firstLineIndent=-20,
                        spaceBefore=5,
                        leading=16),
         ParagraphStyle(fontSize=12,
                        name='Heading2',
                        leftIndent=40,
                        firstLineIndent=-20,
                        spaceBefore=0,
                        leading=12),
     ]
     self.elements += [
         self.toc,
         pdf.PageBreak(),
     ]
示例#30
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)