本文整理汇总了Python中pylatex.Document.generate_tex方法的典型用法代码示例。如果您正苦于以下问题:Python Document.generate_tex方法的具体用法?Python Document.generate_tex怎么用?Python Document.generate_tex使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pylatex.Document
的用法示例。
在下文中一共展示了Document.generate_tex方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_document
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
def test_document():
geometry_options = {
"includeheadfoot": True,
"headheight": "12pt",
"headsep": "10pt",
"landscape": True
}
doc = Document(
default_filepath='default_filepath',
documentclass='article',
fontenc='T1',
inputenc='utf8',
lmodern=True,
data=None,
page_numbers=True,
indent=False,
document_options=["a4paper", "12pt"],
geometry_options=geometry_options
)
repr(doc)
doc.append('Some text.')
doc.change_page_style(style="empty")
doc.change_document_style(style="plain")
doc.add_color(name="lightgray", model="gray", description="0.6")
doc.add_color(name="abitless", model="gray", description="0.8")
doc.set_variable(name="myVar", value="1234")
doc.set_variable(name="myVar", value="1234")
doc.change_length(parameter=r"\headheight", value="0.5in")
doc.generate_tex(filepath='')
doc.generate_pdf(filepath='', clean=True)
示例2: test_document
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
def test_document():
doc = Document(
default_filepath="default_filepath",
documentclass="article",
fontenc="T1",
inputenc="utf8",
lmodern=True,
data=None,
)
doc.append("Some text.")
doc.generate_tex(filepath="")
doc.generate_pdf(filepath="", clean=True)
示例3: test_document
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
def test_document():
doc = Document(
default_filepath='default_filepath',
documentclass='article',
fontenc='T1',
inputenc='utf8',
lmodern=True,
data=None,
)
repr(doc)
doc.append('Some text.')
doc.generate_tex(filepath='')
doc.generate_pdf(filepath='', clean=True)
示例4: doit
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
def doit(outfile = 'summary', ndim=3, action=True):
if action == False:
print(outfile, ndim)
return
if ndim == 3:
resfile = '05aperture_results_3d.txt'
statfile = '3d_cluster_statistics.txt'
elif ndim == 2:
resfile = '05aperture_results_2d.txt'
statfile = 'cluster_statistics.txt'
# generate blank LaTeX doc
geometry_options = {"tmargin": "1cm", "lmargin": "2cm"}
doc = Document(geometry_options=geometry_options)
# insert some introductory material
dirname = os.getcwd()
doc.append('Clustering output, found in')
doc.append(dirname)
# get the K-means section of results table and insert into the document
with doc.create(Section('K-means results')):
tmptex, ncl_list = get_stats(resfile, 'kmeans', oldcols_results, newcols_results, None, None)
doc.append(tmptex)
doc.append(NewPage())
# add the individual K-means runs
add_sections_to_doc(ncl_list, 'kmeans', doc, statfile, ndim)
# now the intro material for meanshift
# get the results table and insert into the document
with doc.create(Section('Meanshift results')):
tmptex, ncl_list = get_stats(resfile, 'meanshift', oldcols_res_ms, newcols_res_ms, None, None)
doc.append(tmptex)
doc.append(NewPage())
# add the individual meanshift runs
add_sections_to_doc(ncl_list, 'meanshift', doc, statfile, ndim)
# turn the LaTex into a PDF
doc.generate_tex(filepath=outfile)
doc.generate_pdf(outfile, clean_tex=False)
# all done!
return
示例5: test_document
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
def test_document():
doc = Document(
default_filepath='default_filepath',
documentclass='article',
fontenc='T1',
inputenc='utf8',
author='',
title='',
date='',
data=None,
maketitle=False
)
doc.append('Some text.')
doc.generate_tex(filepath='')
doc.generate_pdf(filepath='', clean=True)
示例6: generate_hr_tex
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
def generate_hr_tex(G, matchings, output_dir, stats_filename):
"""
print statistics for the resident proposing stable,
max-cardinality popular, and popular amongst max-cardinality
matchings as a tex file
:param G: graph
:param matchings: information about the matchings
"""
# create a tex file with the statistics
doc = Document('table')
# M_s = matching_algos.stable_matching_hospital_residents(graph.copy_graph(G))
# add details about the graph, |A|, |B|, and # of edges
n1, n2, m = len(G.A), len(G.B), sum(len(G.E[r]) for r in G.A)
with doc.create(Subsection('graph details')):
with doc.create(Tabular('|c|c|')) as table:
table.add_hline()
table.add_row('n1', n1)
table.add_hline()
table.add_row('n2', n1)
table.add_hline()
table.add_row('m', m)
table.add_hline()
with doc.create(Subsection('general statistics')):
with doc.create(Tabular('|c|c|c|c|')) as table:
table.add_hline()
table.add_row(('description', 'size', 'bp', 'bp ratio'))
for desc in matchings:
M = matchings[desc]
sig = signature(G, M)
msize = matching_utils.matching_size(G, M)
bp = matching_utils.unstable_pairs(G, M)
table.add_hline()
table.add_row((desc, msize, len(bp), len(bp)/(m - msize)))
table.add_hline()
# statistics w.r.t. set A
stats_for_partition(G, matchings, doc)
# statistics w.r.t. set B
# stats_for_partition(G, matchings, doc, False)
stats_abs_path = os.path.join(output_dir, stats_filename)
doc.generate_pdf(filepath=stats_abs_path, clean_tex='False')
doc.generate_tex(filepath=stats_abs_path)
示例7: generate_heuristic_tex
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
def generate_heuristic_tex(G, matchings, output_dir, stats_filename):
"""
print statistics for the hospital proposing heuristic as a tex file
:param G: graph
:param matchings: information about the matchings
"""
# create a tex file with the statistics
doc = Document('table')
# add details about the graph, |A|, |B|, and # of edges
n1, n2, m = len(G.A), len(G.B), sum(len(G.E[r]) for r in G.A)
with doc.create(Subsection('graph details')):
with doc.create(Tabular('|c|c|')) as table:
table.add_hline()
table.add_row('n1', n1)
table.add_hline()
table.add_row('n2', n1)
table.add_hline()
table.add_row('m', m)
table.add_hline()
M_s = matching_algos.stable_matching_hospital_residents(graph.copy_graph(G))
with doc.create(Subsection('Size statistics')):
with doc.create(Tabular('|c|c|c|c|c|c|c|')) as table:
table.add_hline()
table.add_row(('description', 'size', 'bp', 'bp ratio', 'block-R',
'rank-1', 'deficiency'))
for desc in matchings:
M = matchings[desc]
sig = signature(G, M)
bp = matching_utils.unstable_pairs(G, M)
msize = matching_utils.matching_size(G, M)
table.add_hline()
table.add_row((desc, msize, len(bp), len(bp)/(m - msize),
len(blocking_residents(bp)),
sum_ranks(sig, (1,)), #sum_ranks(sig, (1, 2, 3)),
total_deficiency(G, M_s)))
table.add_hline()
stats_abs_path = os.path.join(output_dir, stats_filename)
doc.generate_pdf(filepath=stats_abs_path, clean_tex='False')
doc.generate_tex(filepath=stats_abs_path)
示例8: main
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
def main(argv):
doclink = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hl:o:n:",["doclink=","output=","toolname="])
except getopt.GetoptError:
sys.exit(2)
global defaultname
for opt, arg in opts:
if opt == '-h':
print("paperpp.py -l <document class link> -o <outputfile> -n <name>")
sys.exit()
elif opt in ("-l", "--doclink"):
doclink = arg
elif opt in ("-n", "--toolname"):
defaultname = arg
elif opt in ("-o", "--output"):
outputfile = arg
documentcls=download_doc_class(doclink)
print("Initialize docclass:",documentcls)
paperfile = currdir+ os.sep +"paper"
macrofile = currdir+ os.sep +"macro.tex"
with open(macrofile,"w+") as f:
f.write("\\newcommand{\\toolname}{"+defaultname+"}")
name = current_user()
print("Current_user:",name)
doc = Document(author=name,date='',title='Paper Title',maketitle=True, default_filepath=paperfile, documentclass=documentcls)
doc.preamble.append(Command('input', arguments='macro.tex'))
doc = add_package(doc)
doc = add_paperprefix(doc)
doc = add_text(doc)
doc.generate_tex(paperfile)
shutil.copy2(paperfile+".tex",paperfile+".tex.copy")
#doc.generate_pdf(paperfile)
shutil.copy2(paperfile+".tex.copy",paperfile+".tex")
os.remove(paperfile+".tex.copy")
示例9: print
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
for identifier in identifiers:
color = {
"eval7_concat_noopt": "red",
"eval7_concat_opt": "blue"
}[identifier]
name = {
"eval7_concat_noopt": "no optimisation",
"eval7_concat_opt": "concat flattening"
}[identifier]
plot.append(Plot(name = name, options = "very thick,color={}".format(color), coordinates = coordinates[identifier]))
name = "eval7_concat_compiletime"
print("Generating {}.pdf".format(name))
doc.generate_pdf("../tex/{}".format(name), compiler = "D:/Software/texlive/bin/win32/pdflatex.exe")
print("Generating {}.tex".format(name))
doc.generate_tex("../tex/{}".format(name))
print("Done {}.".format(name))
print("")
# for identifier in identifiers:
# print("Preparing {}".format(identifier))
# doc = Document()
# doc.packages.append(Package("geometry", options = ["tmargin=1cm", "lmargin=1cm"]))
# for s in series:
# with doc.create(Section("Series: {}".format(s["name"]))):
# algorithms = ["fifo", "lru", "mru", "specialised"]
# # algorithms = ["mru", "specialised", "specialisedOrig"]
示例10: __init__
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
class Invoice:
def __init__(self, id=None, subject=None, client=None, seller=None, items=None, offer=False):
self.id = str(id)
self.subject = subject # Rechnungsbeschriebung
self.client = client # Kundendaten
self.me = seller # Verkäufer
self.discount = 0 # Rabatt
self.items = items if items is not None else []
self.filename = self.id + '-' + time.strftime('%Y')
self.documentclass = None
self.docoptions = 'DIN,pagenumber=false,parskip=half,fromalign=right,fromphone=true,fromfax=false,fromrule=false,fontsize=12pt'
self.doc = None
if offer is True:
self.setoffer()
else:
self.categroy = ['Rechnung', 'Rechnungsnummer']
self.statictext = {
'tdef': '\\begin{spreadtab}{{tabularx}{\linewidth}{lXrr}}',
'thead': '@ Anzahl & @ Beschreibung & @ Einzelpreis & @ Gesamtpreis \\\\ \\hline',
'temptyrow': '@ & @ & @ & @ \\\\',
'tsep': '\\\\ \\hline \\hline \\\\',
'tsum': ' & & @ Nettobetrag Gesamt & :={sum(d2:[0,-3])} \\euro \\\\',
'tvat': ' & & @ MwSt. 19\% & :={[0,-1]*0.19+0.00} \\euro \\\\',
'ttotal': ' & & @ Bruttobetrag Gesamt & :={sum([0,-2]:[0,-1])} \\euro \\\\'
}
def setoffer(self):
self.categroy = ['Angebot', 'Angebotsnummer']
def setuplatex(self):
self.filename = self.id + '-' + time.strftime('%Y')
self.documentclass = Command('documentclass', arguments='scrlttr2', options=self.docoptions)
self.doc = Document(self.filename, documentclass=self.documentclass, fontenc='T1', inputenc='utf8')
self.doc.preamble.append(Command('input', latex_preamble))
self.doc.preamble.append(Command('LoadLetterOption', 'template'))
self.doc.preamble.append(Command('setkomavar', arguments='subject', extra_arguments=self.subject))
self.doc.preamble.append(Command('setkomavar', arguments='yourmail', options=self.categroy[1], extra_arguments=self.filename))
# Falls man Kundennummer implementieren möchte.
# %\setkomavar{yourref}[Ihre Kundennummer]{263}
def generate(self):
self.cli_input_details() # Details in Dokument eintragen
self.setuplatex() # Latex konfigurieren.
self.cli_input_items() # Items abfragen
self.discount = input(_('Ermäßigung in %: [0%] '))
self.discount = 0 if self.discount == '' else int(self.discount)
multi = round(1-self.discount/100, 2)
self.statictext['tdiscount'] = NoEscape(' & & @ Ermäßigung ' + str(self.discount) + '\% & :={[0,-1]*' + str(multi) + '+0.00} \\euro \\\\')
self.fill_document() # Latex füllen.
self.doc.generate_pdf(settings.latex['output_folder'] + self.filename, compiler=pdflatex, silent=latex_silent)
if latex_output:
self.doc.generate_tex(self.filename)
def cli_input_details(self):
print(_('Bitte Rechnungsdetails angeben: '))
self.id = input(self.categroy[1] + ': ')
self.subject = input(_('Betreff: '))
def cli_input_items(self):
i = input(_('Anzahl an Positionen? '))
for i in range(0, int(i)):
new_item = Item()
self.items.append(new_item)
separator()
def additems(self):
for item in self.items:
tail = '\\euro & :={[-3,0]*[-1,0]} \\euro \\\\'
self.doc.append(NoEscape(str(item.qt) + ' & @ ' + item.desc + item.desc2 + ' & :={' + str(item.price) + '} ' + tail))
def fill_document(self):
self.doc.append(Command('begin', arguments='letter', extra_arguments=self.client.getaddress()))
self.doc.append(Command('opening', ' '))
self.doc.append(UnsafeCommand('vspace', '-1.0cm'))
self.doc.append(Command('STautoround*', '2')) # Round 2 decimals
self.doc.append(Command('STsetdecimalsep', ',')) # Decimal separator sign
self.doc.append(NoEscape(self.statictext['tdef'])) # Table definition
self.doc.append(NoEscape(self.statictext['thead'])) # Table head
self.doc.append(NoEscape(self.statictext['temptyrow'])) # Empty row
self.additems() # All the items
self.doc.append(NoEscape(self.statictext['tsep'])) # Seperator row
self.doc.append(NoEscape(self.statictext['tsum'])) # Sum of all items
if self.discount != 0:
self.doc.append(NoEscape(self.statictext['tdiscount']))
self.doc.append(NoEscape(self.statictext['tvat'])) # VAT
self.doc.append(NoEscape(self.statictext['ttotal'])) # Total = VAT + sum
self.doc.append(Command('end', 'spreadtab')) # End of table
self.doc.append(Command('end', 'letter')) # End of document
示例11: __init__
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
#.........这里部分代码省略.........
def add_list(self,lists,type=1):
""" 添加列表
:param list lists: 列表名称
:param int type: 列表类型
:return: 无返回值
"""
if type == 1:
items = Itemize()
elif type == 2:
items = Enumerate()
elif type == 3:
items = Description()
else:
items = Itemize()
for item in lists:
items.add_item(item)
self.doc.append(items)
def add_table(self, data=None):
""" 添加表格
:param list data: 表格数据
:return: 无返回值
"""
nrow = len(data)
ncol = len(data[0])
tabsize = '|' + '|'.join(['c']*ncol) + '|'
mtable = Tabular(tabsize)
for i in range(nrow):
mtable.add_hline()
mtable.add_row(tuple([str(item) for item in data[i]]))
mtable.add_hline()
self.doc.append(Command('begin',arguments='center'))
self.doc.append(mtable)
self.doc.append(Command('end',arguments='center'))
def add_pretty_table(self,data=None,caption='Table',width='90mm'):
""" 添加漂亮的表格
:param list data: 表格数据
:param str caption: 表格名称
:param str width: 表格宽度
:return: 无返回值
"""
ncol = len(data[0])
self.append(''.join(['\\begin{tabularx}{',width,'}{','X'*ncol,'}']))
self.append('\\toprule')
self.append(''.join(['\\multicolumn{',str(ncol),'}{c}{',caption,'} \\\\']))
self.append(''.join(['\\cmidrule(r){1-',str(ncol),'}']))
self.append(''.join([' & '.join([str(item) for item in data[0]]),' \\\\']))
self.append('\\midrule')
for item in data[1:]:
self.append(''.join([' & '.join([str(unit) for unit in item]),' \\\\']))
self.append('\\bottomrule')
self.append('\\end{tabularx}')
def add_figure(self,file=None,caption=None,width='240px'):
""" 添加图形
:param str file: 图形文件路径
:param str caption: 图形标题
:param str width: 图形宽度
:return: 无返回值
"""
graph = Figure(position='h!')
graph.add_image(file, width=width)
if caption is not None:
graph.add_caption(caption)
self.doc.append(graph)
def add_package(self,name,options=None):
""" 添加latex包
:param str name: latex包的名字
:param list options: latex包的参数
:return: 无返回值
"""
self.doc.packages.append(Package(name=name,options=options))
def generate_tex(self,filepath=None):
""" 创建.tex文件
:param str filepath: 文件路径名称
:return: 无返回值
"""
self.doc.generate_tex(filepath=filepath)
def generate_pdf(self,filepath=None):
""" 创建pdf文件
:param str filepath: 文件路径名称
:return: 无返回值
"""
self.doc.generate_pdf(filepath=filepath)
示例12: min
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
ymin = min([min([max([s["function"](h, ncm, cm) for s in series]) for (h, ncm, cm) in data[algorithm]]) for algorithm in algorithms])
ymax = max([max([max([s["function"](h, ncm, cm) for s in series]) for (h, ncm, cm) in data[algorithm]]) for algorithm in algorithms])
if ymin < 0:
ymin *= 1.1
else:
ymin *= 0.9
if ymax > 0:
ymax *= 1.1
else:
ymax *= 0.9
ymin, ymax = int(ymin), int(ymax)
for algorithm in algorithms:
currentData = data[algorithm]
options = "title={}, height=5cm, width=5cm, grid=major, xmin=(-50), xmax=({}), ymin=({}), ymax=({})".format(algorithm, xmax, ymin, ymax)
with doc.create(TikZ()):
with doc.create(Axis(options = options)) as plot:
for s in series:
color = s["color"]
f = s["function"]
coordinates = [(t, f(h, ncm, cm)) for (t, (h, ncm, cm)) in enumerate(currentData)]
plot.append(Plot(options = "very thick,color={}".format(color), coordinates = coordinates))
print("Generating {}.pdf".format(identifier))
doc.generate_pdf("../tex/{}".format(identifier), compiler = "D:/Software/texlive/bin/win32/pdflatex.exe")
print("Generating {}.tex".format(identifier))
doc.generate_tex("../tex/{}".format(identifier))
print("Done {}.".format(identifier))
print("")
示例13: Document
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
# Document
doc = Document(
default_filename='default_filename',
documentclass='article',
fontenc='T1',
inputenc='utf8',
author='',
title='',
date='',
data=None,
maketitle=False
)
doc.append('Some text.')
doc.generate_tex(filename='')
doc.generate_pdf(filename='', clean=True)
# SectionBase
s = Section(title='', numbering=True, data=None)
# Math
m = Math(data=None, inline=False)
# Table
t = Table(table_spec='|c|c|', data=None, pos=None, table_type='tabular')
t.add_hline(start=None, end=None)
t.add_row(cells=(1, 2), escape=False)
示例14: Document
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
# Document
doc = Document(
default_filepath='default_filepath',
documentclass='article',
fontenc='T1',
inputenc='utf8',
author='',
title='',
date='',
data=None,
maketitle=False
)
doc.append('Some text.')
doc.generate_tex(filepath='')
doc.generate_pdf(filepath='', clean=True)
# SectionBase
s = Section(title='', numbering=True, data=None)
# Math
m = Math(data=None, inline=False)
# Tabular
t = Tabular(table_spec='|c|c|', data=None, pos=None)
t.add_hline(start=None, end=None)
t.add_row(cells=(1, 2), escape=False)
示例15: create_reading_section
# 需要导入模块: from pylatex import Document [as 别名]
# 或者: from pylatex.Document import generate_tex [as 别名]
def create_reading_section(document, medium):
with document.create(Subsection('Reading')):
with document.create(Itemize()) as itemize:
try:
df = pd.read_csv(os.path.join(medium, 'reading.csv'))
except pd.errors.EmptyDataError:
return
for _, row in df.iterrows():
title = row.Title
link = row.Link
itemize.add_item(italic(title))
itemize.append(NewLine())
arguments = Arguments(link, link)
itemize.append(Command('href', arguments=arguments))
for medium in ['books', 'papers']:
with document.create(Section(medium.capitalize())):
if medium == 'books':
create_read_section(document, medium)
create_reading_section(document, medium)
elif medium == 'papers':
create_read_section(document, medium)
document.generate_tex('read')
document.generate_pdf('read', compiler='pdflatex', clean_tex=False)