Python reportlab.platypus.SimpleDocTemplate() Examples

The following are 10 code examples of reportlab.platypus.SimpleDocTemplate(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module reportlab.platypus , or try the search function .
Example #1
Source File: report.py    From nanopype with MIT License 7 votes vote down vote up
def __init__(self, cwd, output, version=''):
        self.cwd = cwd
        self.tag = os.path.basename(os.path.normpath(self.cwd))
        self.version = version
        self.story = []
        stylesheet = getSampleStyleSheet()
        self.title_style = stylesheet['Title']
        self.heading_style = stylesheet['Heading2']
        self.heading2_style = stylesheet['Heading3']
        self.normal_style = stylesheet['Normal']
        self.body_style = stylesheet['BodyText']
        self.current_section = 0
        self.doc = doc = SimpleDocTemplate(output,
            pagesize=A4,
            leftMargin=2.2*cm, rightMargin=2.2*cm,
            topMargin=1.5*cm,bottomMargin=2.5*cm)
        self.plot_width = self.doc.width * 0.85
        self.plot_scale = 0.4 
Example #2
Source File: pygments2xpre.py    From stdm with GNU General Public License v2.0 7 votes vote down vote up
def convertSourceFiles(filenames):
    "Helper function - makes minimal PDF document"

    from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, XPreformatted
    from reportlab.lib.styles import getSampleStyleSheet
    styT=getSampleStyleSheet()["Title"]
    styC=getSampleStyleSheet()["Code"]
    doc = SimpleDocTemplate("pygments2xpre.pdf")
    S = [].append
    for filename in filenames:
        S(Paragraph(filename,style=styT))
        src = open(filename, 'r').read()
        fmt = pygments2xpre(src)
        S(XPreformatted(fmt, style=styC))
    doc.build(S.__self__)
    print 'saved pygments2xpre.pdf' 
Example #3
Source File: mangascrapper.py    From MangaScrapper with Apache License 2.0 6 votes vote down vote up
def _create_pdf_(chap_save_loc):
        img_list = natsorted(os.listdir(chap_save_loc))
        pdf_save_loc = chap_save_loc + ".pdf"
        doc = SimpleDocTemplate(pdf_save_loc, pagesize=A2)
        parts = [Image(os.path.join(chap_save_loc, img)) for img in img_list]
        try:
            doc.build(parts)
        except PermissionError:
            logging.error("Missing Permission to write. File open in system editor or missing "
                          "write permissions.") 
Example #4
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 6 votes vote down vote up
def generate(cls, pdf_input_data: dict):
        # setup
        self = cls()
        reports = pdf_input_data.get("reports", [])
        matches = pdf_input_data.get("matches", [])
        report_buffer = BytesIO()
        doc = SimpleDocTemplate(
            report_buffer,
            pagesize=letter,
            rightMargin=72,
            leftMargin=72,
            topMargin=72,
            bottomMargin=72,
        )

        # content fill
        self.pdf_elements.extend(self.cover_page())
        self.pdf_elements.extend(self.report_pages(reports))
        self.pdf_elements.extend(self.match_pages_empty_identifier(matches))

        # teardown
        doc.build(self.pdf_elements, canvasmaker=NumberedCanvas)
        result = report_buffer.getvalue()
        report_buffer.close()
        return result 
Example #5
Source File: report.py    From flask-restful-example with MIT License 5 votes vote down vote up
def pdf_write(generated_pdf_path):
    """
    生成pdf
    :return:
    """
    # 增加的字体,支持中文显示,需要自行下载支持中文的字体
    font_path = current_app.config.get("SIM_SUN")

    pdfmetrics.registerFont(TTFont('SimSun', os.path.join(font_path, 'SimSun.ttf')))
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(fontName='SimSun', name='SimSun', leading=20, fontSize=12))
    data = list()
    # 添加一段文字
    paragraph = paragraph_model("测试添加一段文字")
    data.append(paragraph)
    data.append(PageBreak())  # 分页标识
    # 添加table和图片
    table = table_model()
    data.append(table)
    data.append(PageBreak())  # 分页标识
    img = image_model()
    data.append(img)

    # 设置生成pdf的名字和编剧
    pdf = SimpleDocTemplate(generated_pdf_path, rightMargin=0, leftMargin=0, topMargin=40, bottomMargin=0, )
    # 设置pdf每页的大小
    pdf.pagesize = (9 * inch, 10 * inch)

    pdf.multiBuild(data)
    return generated_pdf_path 
Example #6
Source File: pygments2xpre.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def convertSourceFiles(filenames):
    "Helper function - makes minimal PDF document"

    from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, XPreformatted
    from reportlab.lib.styles import getSampleStyleSheet
    styT=getSampleStyleSheet()["Title"]
    styC=getSampleStyleSheet()["Code"]
    doc = SimpleDocTemplate("pygments2xpre.pdf")
    S = [].append
    for filename in filenames:
        S(Paragraph(filename,style=styT))
        src = open(filename, 'r').read()
        fmt = pygments2xpre(src)
        S(XPreformatted(fmt, style=styC))
    doc.build(S.__self__)
    print('saved pygments2xpre.pdf') 
Example #7
Source File: fd_api_doc.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def write_pdf(self, mod):
        file_path = os.path.join(self.write_path if self.write_path != "" else mod.__path__[0], "doc")
        file_name = mod.__package__ + ".pdf"
        
        if not os.path.exists(file_path):
            os.mkdir(file_path)
        
        doc = SimpleDocTemplate(os.path.join(file_path, file_name), 
                                pagesize = A4,
                                leftMargin = 0.25 * inch,
                                rightMargin = 0.25 * inch,
                                topMargin = 0.25 * inch,
                                bottomMargin = 0.25 * inch)      
         
        lib_name = mod.__package__.replace("_", " ") 
        self.create_hdr(lib_name, font_size=24)
        
        print("\n", lib_name, "\n")
        
        dirs = self.read_include_file(os.path.join(mod.__path__[0], "doc"))
        
        if len(dirs) > 0:
            for d in dirs:
                path = os.path.join(mod.__path__[0], d)
                if os.path.exists(path):
                    self.create_hdr(d.title(), font_size=18)
                    self.search_dir(path)
                 
        else:
            products_path = os.path.join(mod.__path__[0], "products")
            if os.path.exists(products_path):
                self.create_hdr("Products", font_size=18)
                self.search_dir(products_path)
             
            inserts_path = os.path.join(mod.__path__[0], "inserts")
            if os.path.exists(inserts_path):
                self.create_hdr("Inserts", font_size=18)
                self.search_dir(inserts_path)              
         
        doc.build(self.elements) 
Example #8
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_pdf_report(self, report_id, recipient):
        # setup
        report_buffer = BytesIO()
        doc = SimpleDocTemplate(
            report_buffer,
            pagesize=letter,
            rightMargin=72,
            leftMargin=72,
            topMargin=72,
            bottomMargin=72,
        )

        # content fill
        self.pdf_elements.extend(
            api.NotificationApi.get_cover_page(report_id=report_id, recipient=recipient)
        )
        self.pdf_elements.extend(self.report_page(self.report))
        self.pdf_elements.append(
            Paragraph("Record Questions", self.section_title_style)
        )
        self.render_questions(self.report_data)

        # teardown
        doc.build(
            self.pdf_elements,
            onFirstPage=self.get_header_footer(recipient),
            onLaterPages=self.get_header_footer(recipient),
            canvasmaker=NumberedCanvas,
        )
        result = report_buffer.getvalue()
        report_buffer.close()
        return result 
Example #9
Source File: __init__.py    From testplan with Apache License 2.0 4 votes vote down vote up
def create_pdf(source, config):
    """Entry point for PDF generation."""
    if stored_exc is not None:
        # We cannot generate a PDF if there was an exception importing the
        # dependencies, so raise and abort here.
        #
        # Need to explicitly disable the raising-bad-type check here since
        # pylint isn't smart enough to know that we explicitly checked that
        # the stored_exc is not None above.
        raise stored_exc  # pylint: disable=raising-bad-type

    # Depth values will be used for indentation on PDF, however
    # we want first level children to have depth = 0 (otherwise we'll have to
    # do `depth + 1` everywhere in the renderers.
    # The renderer for root will discard the negative depth.
    data = [(depth - 1, rep) for depth, rep in source.flatten(depths=True)]

    reportlab_data = []
    reportlab_styles = []
    row_idx = 0

    for depth, obj in data:

        registry = (
            report_registry
            if isinstance(obj, Report)
            else serialized_entry_registry
        )

        renderer = registry[obj](style=config.pdf_style)
        if renderer.should_display(source=obj):
            row_data = renderer.get_row_data(
                source=obj, depth=depth, row_idx=row_idx
            )

            row_idx = row_data.end

            reportlab_data.extend(row_data.content)
            reportlab_styles.extend(row_data.style)

    template = SimpleDocTemplate(
        filename=config.pdf_path,
        pageSize=const.PAGE_SIZE,
        topMargin=const.PAGE_MARGIN,
        bottomMargin=const.PAGE_MARGIN,
        leftMargin=const.PAGE_MARGIN,
        rightMargin=const.PAGE_MARGIN,
        title="Testplan report - {}".format(source.name),
    )

    tables = create_base_tables(
        data=reportlab_data,
        style=const.TABLE_STYLE + reportlab_styles,
        col_widths=[width * template.width for width in const.COL_WIDTHS],
    )

    template.build(tables) 
Example #10
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 4 votes vote down vote up
def generate_match_report(self, report_id, recipient):
        """
        Generates PDF report about a discovered match.

        Args:
          report_id (str): id used to uniquely identify this report to receiving authority

        Returns:
          bytes: a PDF with the submitted perp information & contact information of the reporters for this match

        """
        # setup :: matches
        sorted_matches = sorted(
            self.matches, key=lambda m: m.added.strftime("%Y-%m-%d %H:%M"), reverse=True
        )
        match_report_and_report_content = [
            (match, MatchReportContent(**json.loads(match.get_match(self.identifier))))
            for match in sorted_matches
        ]
        # setup :: pdf
        buffer = BytesIO()
        doc = SimpleDocTemplate(
            buffer,
            pagesize=letter,
            rightMargin=72,
            leftMargin=72,
            topMargin=72,
            bottomMargin=72,
        )

        # content fill
        self.pdf_elements.extend(
            api.NotificationApi.get_cover_page(report_id=report_id, recipient=recipient)
        )
        self.pdf_elements.append(
            Paragraph(api.NotificationApi.report_title, self.report_title_style)
        )
        self.pdf_elements.append(Paragraph("Perpetrator(s)", self.section_title_style))
        self.pdf_elements.append(
            self.names_and_matching_identifiers(match_report_and_report_content)
        )
        self.pdf_elements.extend(self.match_pages(match_report_and_report_content))

        # teardown
        doc.build(
            self.pdf_elements,
            onFirstPage=self.get_header_footer(recipient),
            onLaterPages=self.get_header_footer(recipient),
            canvasmaker=NumberedCanvas,
        )
        result = buffer.getvalue()
        buffer.close()
        return result