def __init__(
        self,
        df,
        filepath,
        table_string=None,
        booktabs=True,
        logging=True,
        options_packages=[
            ("locale=DE", "siunitx"),
            ("", "booktabs"),
            ("ngerman", "babel"),
        ],
    ):
        r"""Fill TexTable with DataFrame.

        Parameters
        ----------
        df : pandas.DataFrame
            Data.
        filepath : str
            Complete filepath without extensions to name PDF and TEX files.
        table_string: str, None
            String in \tabular{table_string}.
            If None, default to 'S' for number of fields.
        booktabs : bool, True
            Using booktabs style horizontal lines.
        logging : bool, True
            Log if compilation occurs.
        options_packages : list[tuple]
            Additional packages with options to include in header of TEX file.
        """
        self.df = df
        self.filepath = filepath
        self.logging = logging

        if table_string is None:
            table_string = "S " * df.shape[1]

        self.table = Tabular(table_string,
                             booktabs=booktabs,
                             width=df.shape[1])
        self.table.escape = False

        self.document = Document(self.filepath,
                                 documentclass="standalone",
                                 document_options="preview")
        for opt_pack in options_packages:
            self.document.packages.append(
                NoEscape(r"\usepackage[{}]".format(opt_pack[0]) + r"{" +
                         str(opt_pack[1]) + r"}"))

        self.table.add_row(self.df.columns)

        self.table.add_hline()  # \midrule

        for i in range(self.df.shape[0]):
            self.table.add_row(self.df.loc[i].values)

        self.document.append(NoEscape(self.table.dumps()))
Exemple #2
0
 def addTable(self, data=None,nrow=None,ncol=None):
     # 初始化参数
     tabsize = '|' + '|'.join(['c']*ncol) + '|'
     mtable = Tabular(tabsize)
     for i in range(nrow):
         mtable.add_hline()
         mtable.add_row(tuple([escape_latex(str(item)) for item in data[i]]))
     mtable.add_hline()
     self.content.append(Command('begin',arguments='center'))
     #self.content.append('这是我们写的歌\par')
     self.content.append(mtable)
     self.content.append(Command('end',arguments='center'))
Exemple #3
0
    def add_table(self, data=None,nrow=None,ncol=None):
        '''添加表格

        :param data: 表格数据
        :param nrow: 表格行数
        :param ncol: 表格列数
        :return: 无返回值
        '''
        tabsize = '|' + '|'.join(['c']*ncol) + '|'
        mtable = Tabular(tabsize)
        for i in range(nrow):
            mtable.add_hline()
            mtable.add_row(tuple([escape_latex(str(item)) for item in data[i]]))
        mtable.add_hline()
        self.content.append(Command('begin',arguments='center'))
        self.content.append(mtable)
        self.content.append(Command('end',arguments='center'))
class TexTable:
    def __init__(
        self,
        df,
        filepath,
        table_string=None,
        booktabs=True,
        logging=True,
        options_packages=[
            ("locale=DE", "siunitx"),
            ("", "booktabs"),
            ("ngerman", "babel"),
        ],
    ):
        r"""Fill TexTable with DataFrame.

        Parameters
        ----------
        df : pandas.DataFrame
            Data.
        filepath : str
            Complete filepath without extensions to name PDF and TEX files.
        table_string: str, None
            String in \tabular{table_string}.
            If None, default to 'S' for number of fields.
        booktabs : bool, True
            Using booktabs style horizontal lines.
        logging : bool, True
            Log if compilation occurs.
        options_packages : list[tuple]
            Additional packages with options to include in header of TEX file.
        """
        self.df = df
        self.filepath = filepath
        self.logging = logging

        if table_string is None:
            table_string = "S " * df.shape[1]

        self.table = Tabular(table_string,
                             booktabs=booktabs,
                             width=df.shape[1])
        self.table.escape = False

        self.document = Document(self.filepath,
                                 documentclass="standalone",
                                 document_options="preview")
        for opt_pack in options_packages:
            self.document.packages.append(
                NoEscape(r"\usepackage[{}]".format(opt_pack[0]) + r"{" +
                         str(opt_pack[1]) + r"}"))

        self.table.add_row(self.df.columns)

        self.table.add_hline()  # \midrule

        for i in range(self.df.shape[0]):
            self.table.add_row(self.df.loc[i].values)

        self.document.append(NoEscape(self.table.dumps()))

    def generate_tex(self):
        """Generate tex file."""
        self.document.generate_tex(self.filepath)

    def generate_pdf(self, clean_tex=False, silent=True):
        """Compile PDF document if content is new and keep tex file.

        Parameters
        ----------
        clean_tex : bool, False
            Remove TEX file after PDF comilation.
        silent : bool, False
            Dispaly LaTeX compilation output.
        """
        try:
            with open(self.filepath + ".tex", "r") as texfile:
                if texfile.read() == self.document.dumps():
                    if (os.stat(self.filepath + ".tex").st_mtime >
                            os.stat(self.filepath + ".pdf").st_mtime):
                        if self.logging:
                            print("Compile PDF ({})".format(
                                "TEX is newer than PDF."))
                        self.document.generate_pdf(clean_tex=clean_tex,
                                                   silent=silent)
                    else:  # PDF is newer than TEX
                        if self.logging:
                            print("Don't compile PDF ({})".format(
                                "No new content and PDF is newer than TEX."))
                        pass
                else:  # TEX will be overwritten with new content
                    if self.logging:
                        print("Compile PDF ({})".format("New content in TEX."))
                    self.document.generate_pdf(clean_tex=clean_tex,
                                               silent=silent)
        except FileNotFoundError:
            if self.logging:
                print("Compile PDF ({})".format("TEX or PDF does not exist."))
            self.document.generate_pdf(clean_tex=clean_tex, silent=silent)
def add_left_column(doc):
    with column_with_margin(doc) as page:
        with page.create(Center()) as c:
            c.append(
                StandAloneGraphic(image_options="width=130px",
                                  filename=os.path.join(BASE_DIR, "logo.png")))
            add_space_plus_new_line(c, 1.5)
            c.append(MediumText(bold("Triple Verified Grading Report")))
            add_space_plus_new_line(c, 0.7)
            c.append(MediumText("No.: G00000013"))
            add_space_plus_new_line(c, 0.5)

        table = Tabular("l l", row_height=1.3)
        qr_code = StandAloneGraphic(image_options="width=50px",
                                    filename=os.path.join(
                                        BASE_DIR, "qr_code.png"))
        table.add_row(MultiRow(3, data=qr_code), "View digital report at:")
        table.add_row(
            "",
            hyperlink("https://www.gradia.net/verify/G00000013",
                      "gradia.net/verify"))
        table.add_row("", "and also on the blockchain")
        page.append(table)

        # we want to match this with the center line
        add_space_plus_new_line(page, 2.5)

        make_heading_divider(page, "report details")
        table = Tabular("l l", row_height=1.5, col_space="1em")
        table.add_row("Origin Testing", bold("Natural"))
        table.add_row("Shape & Cutting", bold("Round Brilliant"))
        table.add_row("Measurements", bold("2.89 - 2.92 x 1.802"))
        page.append(table)

        add_space_plus_new_line(page, 2)
        make_heading_divider(page, "diamond attributes")

        table = Tabular("l l l l", row_height=1.5, col_space="1em")
        table.add_row("Carat", "Color", "Clarity", "Fluoresence")
        table.add_row(bold("0.09"), bold("F"), bold("VS2"), bold("None"))
        page.append(table)
        add_space_plus_new_line(page, 1.5)
        table = Tabular("l l l", row_height=1.5, col_space="1em")
        table.add_row("Cut", "Polish", "Symmetry")
        table.add_row(bold("Very Good"), bold("Very Good"), bold("Good"))
        page.append(table)

        add_space_plus_new_line(page, 2)
        make_heading_divider(page, "comments")
        page.append(bold("This is a sample report."))
        page.append(LineBreak())
        page.append(bold("This is a second sentence."))
def add_right_column(doc):
    with column_with_margin(doc) as page:
        make_heading_divider(page, "diamond proportions")
        page.append(
            StandAloneGraphic(image_options="width=200px",
                              filename=os.path.join(BASE_DIR, "diagram.png")))
        add_space_plus_new_line(page, 1)

        table = Tabular("l l", row_height=1.1, col_space="1em")
        table.add_row("Total Depth", bold("61.5%"))
        table.add_row("Table", bold("59%"))
        table.add_row("Star Length)", bold("45%"))
        table.add_row("Crown Angle", bold("34.5°"))
        table.add_row("Crown Height", bold("14%"))
        table.add_row("Pavilion Angle", bold("41.4°"))
        table.add_row("Pavilion Angle", bold("44%"))
        table.add_row("Lower Half", bold("75%"))
        table.add_row("Girdle Thickness", bold("3.5%"))
        table.add_row("Girdle Min", bold("Medium"))
        table.add_row("Girdle Max", bold("Slightly Thick"))
        table.add_row("Culet", bold("Very Small"))
        page.append(table)

        add_space_plus_new_line(page, 2)
        make_heading_divider(page, "inclusions")
        page.append(bold("Crystal, Feather"))

        add_space_plus_new_line(page, 1)
        page.append(NoEscape(r"\setstretch{0.7}"))
        page.append(FootnoteText(DISCLAIMER))
def add_center_column(doc):
    with column_with_margin(doc) as page:
        make_heading_divider(page, "ownership details")
        table = Tabular("l l", row_height=1.5, col_space="1em")
        table.add_row(MultiRow(2, data="Owner"), bold("GRADIA Laboratory"))
        table.add_row("", "(as of 8-Sep-20)")
        table.add_row("Goldway Ref", bold("SIOT202007002-R"))
        table.add_row("GIA Ref", bold("1231233345"))
        table.add_row("Blockchain Ref", bold("123154647sdiuyfh"))
        page.append(table)

        add_space_plus_new_line(page, 2)
        make_heading_divider(page, "macro image")
        macro_file = os.path.join(BASE_DIR, "macro.png")
        page.append(
            StandAloneGraphic(image_options="width=200px",
                              filename=macro_file))

        add_space_plus_new_line(page, 2)
        make_heading_divider(page, "nano etching")

        table = Tabular("l l l", row_height=1.3, col_space="0.3em")
        nano_picture = StandAloneGraphic(image_options="width=70px",
                                         filename=os.path.join(
                                             BASE_DIR, "nano.png"))
        table.add_row("", "", MultiRow(3, data=nano_picture))
        table.add_row("Etched ID no.", bold("G00000013"), "")
        table.add_empty_row()
        page.append(table)