def append_to_document(self, doc: Document, doc_answers: Enumerate) -> None: variable_dict = {} for variable in self.variables: variable_dict[variable.symbol] = variable.value parsed_text = QuestionParser(**variable_dict).parse(self.text) with doc.create(Section(parsed_text)): doc.append('Respuesta: ') doc.append(LineBreak()) doc_answers.add_item('Respuesta de pregunta abierta')
def append_to_document(self, doc: Document, doc_answers: Enumerate) -> None: variable_dict = {} for variable in self.variables: variable_dict[variable.symbol] = variable.value parsed_text = QuestionParser(**variable_dict).parse(self.text) with doc.create(Section(parsed_text)): doc.append(bold('Verdadero\t\tFalso')) expr = BooleanParser(**variable_dict).parse(self.expression) doc_answers.add_item('VERDADERO' if expr else 'FALSO')
def test_lists(): # Lists itemize = Itemize() itemize.add_item(s="item") itemize.append("append") enum = Enumerate() enum.add_item(s="item") enum.append("append") desc = Description() desc.add_item(label="label", s="item") desc.append("append")
def mdframed_informar(doc, enum, programa_extensao): with doc.create(MdFramed(options=MDFRAMED_OPTIONS)): item(doc, enum, 'INFORMAR: ') with doc.create(Enumerate()) as subenum: doc.append(Command('scriptsize')) subenum.add_item( NoEscape( 'Esta atividade faz parte de algum Programa de Extensão? ') ) if programa_extensao: doc.append( NoEscape(r'Não ({}) Sim ({}): Qual? {}'.format( PHANTOM, TIMES, programa_extensao.nome))) else: doc.append( NoEscape(r'Não ({}) Sim ({}): Qual? '.format( TIMES, PHANTOM))) doc.append( NoEscape(r''' Coordenador(a) do Programa: \\ \\ \\ Assinatura: \hrulefill \\ ''')) # TODO: ??? subenum.add_item( NoEscape( r'Esta Atividade de Extensão está articulada (quando for o caso): \ ao Ensino ({}) à Pesquisa ({})'.format( PHANTOM, PHANTOM)))
def create_cs170_hw(num="0", author="", questions=[]): # Create document doc = Document() #Inclue packages doc.packages.append(Package('amsmath')) doc.packages.append(Package('amssymb')) doc.packages.append(Package('enumitem')) # Make title title = 'CS 170 - HW %d' % (num) doc.preamble.append(Command('title', bold(title))) doc.preamble.append(Command('author', author)) doc.preamble.append(Command('date', '')) doc.append(NoEscape(r'\maketitle')) # Instructions #with doc.create(Section("Instructions")) as section: # section.append("N/A") # Create questions for question in questions: name = question[0] parts = question[1] with doc.create(Section(name)): if (parts > 0): with doc.create( Enumerate(enumeration_symbol=r"(\alph*)")) as enum: for _ in range(0, parts): enum.add_item("") # Generate Latex file file_name = "cs170_hw" + str(num) doc.generate_tex(file_name) print("%s.tex generated!" % (file_name))
def create_pdf(self) -> Document: questions = functools.reduce( lambda a, b: a + b, map(lambda x: x.get_questions(), self.questions), []) doc = Document() doc.preamble.append(Package('titling')) for i in range(1, self.count + 1): random.shuffle(questions) with doc.create(Center()): doc.append(HugeText(self.header)) doc.append(bold('Nombre:')) doc.append(LineBreak()) doc.append(bold('ID:')) doc.append(LineBreak()) with doc.create(FlushRight()): doc.append(LargeText(f'Examen tipo {i}')) enum = Enumerate() for question in questions: question.append_to_document(doc, enum) doc.append(NewPage()) doc.append('Guía de respuestas') doc.append(enum) doc.append(NewPage()) doc.append(Command('setcounter', ['section', '0'])) return doc
def set(self, *problems, scores=None, line_space=None): """Set this question and output it.""" if scores is None: if self.scores is None: print("你必须给定明确的分数(scores参数)") else: scores = self.scores if line_space is None: line_space = self.line_space n = len(problems) if type(scores) is list: title = f'本大题共{n}小题,共{sum(scores[:len(problems)])}分' else: title = f'本大题共{n}小题,每小题{scores}分,共{n * scores}分' title = f"{self.name}: {title}{self.describe}" with self.core.create(Subsection(f'{chinese_nums[self.number]}、' + title, False)): with self.core.create(Enumerate()) as enum: self.core.append(NoEscapeStr(r"\addtocounter{enumi}" + f"{{{self.core.num}}}")) for i, problem in enumerate(problems): if type(scores) is list: enum.add_item(NoEscapeStr(f"(本题{scores[i]}分)" + problem)) else: if type(problem) is str: enum.add_item(NoEscapeStr(problem)) else: enum.add_item(problem) enum.append(NoEscapeStr(f"\\\\[{line_space}mm]")) self.core.num += n
def format_latex(title, soup): # create document doc = Document() # set preamble doc.preamble.append(Command('title', title)) doc.append(NoEscape(r'\maketitle')) # get the main content body main_content = soup.body.find('div').find('div') elements = main_content.find_all(True) # iterate over elements for ele in elements: if ele.name == 'h1': doc.append(Section(ele.text)) elif ele.name == 'h2': doc.append(Subsection(ele.text)) elif ele.name == 'h3': doc.append(Subsubsection(ele.text)) elif ele.name == 'h4': doc.append(Paragraph(ele.text)) elif ele.name == 'h5': doc.append(Subparagraph(ele.text)) elif ele.name == 'p': doc.append(ele.text + '\n') elif ele.name == 'ul': with doc.create(Itemize()) as item: for li in ele.find_all('li'): item.add_item(li.text) elif ele.name == 'ol': with doc.create(Enumerate()) as enum: for li in ele.find_all('li'): enum.add_item(li.text) elif ele.name == 'img': with doc.create(Figure(position='h!')) as fig: # create tmp directory for images pathlib.Path('build/images').mkdir(parents=True, exist_ok=True) # check if source is using // shorthand for http:// src = ele['src'] if src.startswith('//'): src = 'http:' + src # generate image path image_path = 'images/' + src.split('/')[-1] # retrieve image print('downloading image ' + src) headers = {'User-Agent': USER_AGENT} response = requests.get(src, stream=True, headers=headers) with open('build/' + image_path, 'wb') as f: response.raw.decode_content = True shutil.copyfileobj(response.raw, f) # append image fig.add_image(image_path) return doc
def append_to_document(self, doc: Document, doc_answers: Enumerate): variable_dict = {} for variable in self.variables: variable_dict[variable.symbol] = variable.value question_parser = QuestionParser(**variable_dict) parsed_text = question_parser.parse(self.text) correct_answer = question_parser.parse(self.correct_answer) answers = list( map(question_parser.parse, map(lambda x: x.answer, self.dummy_questions))) random.shuffle(answers) correct_pos = random.randint(0, len(answers)) answers.insert(correct_pos, correct_answer) with doc.create(Section(parsed_text)): with doc.create( Enumerate(enumeration_symbol=r'\alph*) ', options={'start': 1})) as enum: for answer in answers: enum.add_item(answer) doc_answers.add_item(chr(ord('a') + correct_pos))
def test_lists(): # Lists itemize = Itemize() itemize.add_item(s="item") itemize.append("append") repr(itemize) empty_itemize = Itemize() assert empty_itemize.dumps() == '' repr(empty_itemize) enum = Enumerate() enum.add_item(s="item") enum.append("append") repr(enum) desc = Description() desc.add_item(label="label", s="item") desc.append("append") repr(desc)
def latex(self, numero_ejercicio): ejercicio = Subsection('Ejercicio {}.'.format(numero_ejercicio)) ejercicio.append( NoEscape('\\begin{flushleft}' + self.problema.replace('\n', '\linebreak \n') + '\end{flushleft}')) with ejercicio.create( Enumerate(enumeration_symbol=r"\alph*)")) as enum: for opcion in self.opciones: enum.add_item(NoEscape(opcion.replace('\n', '\linebreak \n'))) return ejercicio
def gerar_pdf_parecer(parecer): doc = pdfutils.init_document() pdfutils.pacotes(doc) # Configurações (preâmbulo) pdfutils.configuracoes_preambulo(doc) pdfutils.cabecalho(doc) frase_anexo = 'ANEXO XI DA RESOLUÇÃO Nº 236/2014-CEPE, DE 13 DE NOVEMBRO DE 2014.' pdfutils.rodape(doc, NoEscape(r'\texttt{' + frase_anexo + '}%')) doc.append(NoEscape(r'{\normalsize\texttt{' + frase_anexo + '}}%')) pdfutils.titulo(doc, 'RELATÓRIOS ESPECÍFICOS PARA ATIVIDADES DE EXTENSÃO', 'FORMULÁRIO ÚNICO DE PARECER DE ATIVIDADES DE EXTENSÃO') # Início do formulário with doc.create(Enumerate()) as enum: pdfutils.item(doc, enum, 'PARECER CONCLUSIVO DA COMISSÃO DE EXTENSÃO DE CENTRO') doc.append(bold('IDENTIFICAÇÃO:')) doc.append(NewLine()) doc.append(NoEscape(r'Coordenador(a): {} \\'.format(escape_latex(parecer.projeto_extensao.coordenador.nome_completo)))) doc.append(NoEscape(r'Colegiado: {} \\'.format(escape_latex(parecer.projeto_extensao.coordenador.colegiado)))) doc.append(NoEscape(r'Centro: {} \\'.format(parecer.projeto_extensao.centro.nome))) doc.append(NoEscape(r'Campus: {} \\'.format(parecer.projeto_extensao.campus.nome))) doc.append(NoEscape(r'Título da atividade: {} \\ \\'.format(escape_latex(parecer.projeto_extensao.titulo)))) # TODO: referente a portaria? # doc.append(NoEscape(r'Parecer referente a: \\ \\')) doc.append(bold(NoEscape(r'COMENTÁRIOS: \\'))) pdfutils.tabela_alternativas(doc, EstadoProjeto, '|c|X|X|c|c|', id=parecer.estado_parecer.id) doc.append(NewLine()) doc.append(NewLine()) doc.append(NoEscape(r'Ata nº: {} \\'.format(escape_latex(parecer.numero_ata)))) data = parecer.data.strftime('%d/%m/%Y') doc.append(NoEscape(r'Data: {} \\'.format(data))) texto = 'Carimbo e Assinatura do Coordenador(a) da Comissão de Extensão ou Representante Legal' largura = Command('widthof', texto).dumps() pdfutils.assinatura(doc, texto, largura, Center()) os.system('mkdir -p ' + PDF_DIR) filepath = '{}/parecer_{}_projeto_{}'.format(PDF_DIR, str(parecer.id), str(parecer.projeto_extensao.id)) doc.generate_pdf(filepath, clean_tex=False, compiler=pdfutils.COMPILER, compiler_args=pdfutils.COMPILER_ARGS) return filepath
def test_lists(): # Lists itemize = Itemize() itemize.add_item(s="item") itemize.append("append") repr(itemize) enum = Enumerate(enumeration_symbol=r"\alph*)", options={'start': 172}) enum.add_item(s="item") enum.add_item(s="item2") enum.append("append") repr(enum) desc = Description() desc.add_item(label="label", s="item") desc.append("append") repr(desc)
def build_question(self, doc, q, i, enum_symbs, level): label = r"\label{%s}" % q._uuid if q.meta.has('label'): label += r"\label{%s}" % q.meta.label # start text for question text = label # add points indicator if given if q.meta.has('points') and int(q.meta.points) > 0: if int(q.meta.points) == 1: text += f"({q.meta.points} point) " else: text += f"({q.meta.points} points) " if len(q._figures) > 0: if len(q._figures) > 1: raise RuntimeError( "WARNING: multiple figures detected in a single question. This is not supported by the LaTeX Writer.\n" ) f = q._figures[0] text += r"For this question, consider Figure \ref{%s}. " % f._uuid text += q.formatted_text if q.meta.has('newpage') and q.meta.newpage: doc.append(Command('newpage')) if q.meta.has('pre_vspace'): doc.append(Command('vspace', q.meta.pre_vspace)) with doc.create( Enumerate( enumeration_symbol=NoEscape(enum_symbs[level]))) as qlist: doc.append( Command('setcounter', [self.get_counter_for_level(level), i])) qlist.add_item(NoEscape(text)) self.build_answer(doc, q) if q.meta.has('post_vspace'): doc.append(Command('vspace', q.meta.post_vspace)) for j in range(len(q._parts)): p = q._parts[j] self.build_question(doc, p, j, enum_symbs, level + 1)
def do(): doc = Document() # create a bulleted "itemize" list like the below: # \begin{itemize} # \item The first item # \item The second item # \item The third etc \ldots # \end{itemize} with doc.create(Section('"Itemize" list')): with doc.create(Itemize()) as itemize: itemize.add_item("the first item") itemize.add_item("the second item") itemize.add_item("the third etc") # you can append to existing items itemize.append(Command("ldots")) # create a numbered "enumerate" list like the below: # \begin{enumerate} # \item The first item # \item The second item # \item The third etc \ldots # \end{enumerate} with doc.create(Section('"Enumerate" list')): with doc.create(Enumerate()) as enum: enum.add_item("the first item") enum.add_item("the second item") enum.add_item(NoEscape("the third etc \\ldots")) # create a labelled "description" list like the below: # \begin{description} # \item[First] The first item # \item[Second] The second item # \item[Third] The third etc \ldots # \end{description} with doc.create(Section('"Description" list')): with doc.create(Description()) as desc: desc.add_item("First", "The first item") desc.add_item("Second", "The second item") desc.add_item("Third", NoEscape("The third etc \\ldots")) doc.generate_pdf('lists', clean_tex=False)
def build_answer(self, doc, q): if q._answer is not None: try: # multiple choice # NOTE: need to access all_formatted_choices member of q._answer # so that try block will fail before an enumeration is created all_choices = self.MC_Answer_get_all_choices(q._answer) symb = r'\alph*)' try: symb = ass.meta.config['answer']['multiple_choice/symbol'] except: pass doc.append(NoEscape(r' \\ ')) with doc.create(MiniPage()): with doc.create( Enumerate( enumeration_symbol=NoEscape(symb))) as clist: for choice in all_choices: label = r'\label{%s}' % choice[0] clist.add_item(NoEscape(label + choice[1])) except: pass try: # numerical ans = q._answer.quantity space = "2in" try: space = ass.meta.config['answer']['numerical/spacing'] except: pass doc.append(NoEscape(r"\vspace{%s}" % space)) except: pass try: # text ans = q._answer.text space = "2in" try: space = ass.meta.config['answer']['text/spacing'] except: pass doc.append(NoEscape(r"\vspace{%s}" % space)) except: pass
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_comments(self, issue: dict) -> None: """ Add comments for the specified issue. Each comment has the author and the body. :param issue: Issue represented as dictionary :return: None """ doc = self.doc filtered_comments = [ comment for comment in issue["comments"] if comment["author"] not in self.bots ] if not filtered_comments: doc.append("No comments") else: with doc.create(Enumerate()) as enum: for comment in filtered_comments: comment_body = utils.escape_with_listings(comment["body"]) enum.add_item( bold(comment["author"] + ": ") + comment_body)
def tabela_gestao_recursos_financeiros(doc, enum, previsao_orcamentaria): item(doc, enum, NoEscape(r'GESTÃO DOS RECURSOS FINANCEIROS: ')) doc.append(Command('noindent')) with doc.create(Enumerate(options={'leftmargin': '7pt'})) as subenum: subenum.add_item( bold(NoEscape(r'ÓRGÃO GESTOR DOS RECURSOS FINANCEIROS \\'))) with doc.create(MdFramed(options=MDFRAMED_OPTIONS)): doc.append(NoEscape(r'IDENTIFICAÇÃO: \\')) for tipo_gestao in TipoGestaoRecursosFinanceiros.objects.all(): nome_tipo_gestao = tipo_gestao.nome.upper() if previsao_orcamentaria.identificacao and previsao_orcamentaria.identificacao.id == tipo_gestao.id: marcador = TIMES else: marcador = PHANTOM if nome_tipo_gestao in ('PRAP', 'SECRETARIA FINANCEIRA', 'UNIOESTE'): doc.append( NoEscape(r'({}) {} \\'.format(marcador, nome_tipo_gestao))) elif nome_tipo_gestao in 'FUNDAÇÃO': doc.append( NoEscape(r'({}) {}: '.format(marcador, bold(nome_tipo_gestao)))) if previsao_orcamentaria.fundacao: doc.append(escape_latex(previsao_orcamentaria.fundacao)) doc.append(NewLine()) else: # outros doc.append( NoEscape(r'({}) {}: '.format(marcador, bold(nome_tipo_gestao)))) if previsao_orcamentaria.outro_orgao_gestor: doc.append( escape_latex(previsao_orcamentaria.outro_orgao_gestor)) doc.append(NewLine())
def tabela_certificados(doc, id=None): with doc.create(Enumerate()) as enum: enum.add_item( NoEscape( r'Relacionar o nome dos participantes com direito a certificados. \\' )) table_spec = NoEscape(r'''|>{\centering\arraybackslash}X| @{ }c@{ }| @{ }c@{ }| @{ }c@{ }| ''') cabecalho_tabela = ['NOME', 'FUNÇÃO', 'FREQUÊNCIA (%)', 'C/H TOTAL'] with doc.create(Tabularx(table_spec, width_argument=WIDTH_ARGUMENT)) as tab: tab.add_hline() tab.add_row(cabecalho_tabela) tab.add_hline() certificados = CertificadoRelatorio.objects.filter(relatorio_id=id) for certificado in certificados: if certificado: linha = [ escape_latex(certificado.nome), certificado.funcao, certificado.frequencia, certificado.carga_horaria_total ] tab.add_row(linha) tab.add_hline() doc.append(LineBreak()) # TODO: Item 9.2: Inserir onde o certificado sera gerado: PROEX ou Centro de Coordenação / Órgão Promotor enum.add_item( NoEscape(r'Informar se os certificados devem ser emitidos: \\')) doc.append( NoEscape( '({}) pela PROEX \hfill ({}) pelo Centro da Coordenação ou Órgão Promotor' .format(PHANTOM, PHANTOM)))
def section_1_introduction(): sec = Subsection(title='Introduction') sec.append( NoEscape( 'Calculation documented herein follows Annex B in ' '"Eurocode 1: Actions on structures – Part 1-2: General actions – Actions on structures exposed to fire" ' '(BS EN 1991-1-2). This method allows the determination of (a) the maximum temperatures of a compartment ' 'fire; (b) the size and temperatures of the flame from openings; and (c) the thermal radiation and ' 'convection parameters.\\par')) sec.append( NoEscape( 'This method considers steady-state conditions for various parameters and is only valid when the following ' 'conditions are met:')) section_1_enumerate_1 = Enumerate() section_1_enumerate_1.add_item( NoEscape( 'Fire load $q_{fd}$ is greater than 200 ${MJ}\\cdot m^{-2}$; and' )) section_1_enumerate_1.add_item( NoEscape( 'The size of the fire compartment should not exceed 70 $m$ in length, 18 $m$ in width and 5 $m$ in height.' )) sec.append(section_1_enumerate_1) sec.append(NoEscape('\\par')) sec.append( NoEscape( 'Units, symbols and abbreviations are consistent with the referenced document unless stated.\\par' )) sec.append( NoEscape( 'Numerical values shown in this document are rounded as appropriate for readability, however, calculations ' 'are carried out based on the actual values.\\par')) sec.append( NoEscape( 'This assessment is specific to \\textit{no forced draught} condition in accordance with ' 'Clause B.4.1 in BS EN 1991-1-2.')) return sec
def GenerateAssignmentPdf(assignment, filepath=None): doc = Document() doc.packages.append(Package('geometry', options=['tmargin=1cm', 'lmargin=1cm'])) doc.packages.append(Package('multicol')) doc.packages.append(Package('graphicx')) doc.packages.append(Package('amsmath')) QuestionData = QuestionSets[assignment] with doc.create(Section('Integer Equations Quiz')): doc.append(NoEscape(r''' \begin{center} \fbox{\fbox{\parbox{5.5in}{\centering Answer the questions in the spaces provided on the question sheets. Then enter your answer into the Integer Equations Quiz on Schoology. If you run out of room for an answer, raise your hand to ask for an extra piece of paper.}}} \end{center} \vspace{0.1in} \makebox[\textwidth]{Name and period:\enspace\hrulefill} ''')) doc.append(NoEscape(r'\begin{multicols}{2}')) with doc.create(Enumerate(enumeration_symbol=r"\arabic*)", options={'start': 1})) as enum: for Question in QuestionData: for Parameters in Question['ParameterSetVariants']: template = jenv.get_template(Question['Template']) out = template.render(**Parameters) enum.add_item(NoEscape(out)) #enum.add_item(NoEscape(Question['Question'])) doc.append("\n\n") letters = ['a','b','c','d'] if 'Choices' in Parameters: for i,Choice in enumerate(Parameters['Choices']): if Choice['type'] == 'image': doc.append(letters[i]+')') doc.append(NoEscape(r'\includegraphics[width=0.2\columnwidth]{'+Choice['path']+'}')) doc.append(NoEscape(r'\vspace{'+Question['SpaceAfter']+r'}')) doc.append(NoEscape(r'\end{multicols}')) doc.generate_tex(filepath=filepath)
a = Axis(data=None, options=None) p = Plot(name=None, func=None, coordinates=None, options=None) # Utils escape_latex(s='') fix_filename(path='') dumps_list(l=[], escape=False, token='\n') bold(s='') italic(s='') verbatim(s='', delimiter='|') # Lists itemize = Itemize() itemize.add_item(s="item") itemize.append("append") enum = Enumerate() enum.add_item(s="item") enum.append("append") desc = Description() desc.add_item(label="label", s="item") desc.append("append")
def ol_tag(element, document): with document.create(Enumerate()) as enum: for item in element.findAll(): if item.name == 'li': enum.add_item(item.get_text())
def add_section(self, section_name: str): with self.doc.create(Section(section_name)): with self.doc.create(Enumerate()) as enum: for problem in self.problems: enum.add_item(NoEscape(problem)) self.problems = []
def __describe_issue(self, issue: dict, root_issue: bool = False) -> None: """ Describe the issue passed in the following form: 1. Summary 2. Description 3. Attachments 4. Commits 5. Comments 6. Pull requests :param issue: Issue represented as a dictionary :param root_issue: Whether the issue passed is the root (not a connected) issue of the document :return: None """ doc = self.doc chapter_title = ("Root issue " if root_issue else "Connected issue ") + issue["issue_key"] with doc.create(Chapter(chapter_title)): if "summary" not in self.exclude: with doc.create(Section("Summary")): summary = utils.escape_with_listings(issue["summary"]) doc.append(summary) if "description" not in self.exclude: with doc.create(Section("Description")): description = utils.escape_with_listings( issue["description"]) doc.append(description) if "attachments" not in self.exclude: with doc.create(Section("Attachments")): attachments = issue["attachments"] if not attachments: doc.append("No attachments") else: with doc.create(Enumerate()) as enum: for attachment in issue["attachments"]: enum.add_item( self.__hyperlink(attachment["content"], attachment["filename"])) # Each commit is described in the following way: # "Commit <short_SHA> by <author> (<date>): <commit_message>" if self.commits and "commits" not in self.exclude: with doc.create(Section("Commits")): issue_key = issue["issue_key"] commits = self.commits if not commits[issue_key]: doc.append("No related commits") else: with doc.create(Enumerate()) as enum: for commit in commits[issue_key]: enum.add_item( NoEscape("Commit {} by {} ({}): {}".format( bold(commit["short_sha"]), bold(escape_latex(commit["author"])), escape_latex(commit["date"]), escape_latex(commit["message"])))) if "comments" not in self.exclude: with doc.create(Section("Comments")): self.__add_comments(issue) # Each pull request is described in the following way: # Title: <pr_title> # Author: <pr_author> # Date: <pr_date> # Status: <pr_status> # Comments: [ # <comment_author> (<comment_date>): <comment_body> # ... # ] if self.pull_requests and "pull_requests" not in self.exclude: with doc.create(Section("Pull requests")): issue_key = issue["issue_key"] pull_requests = self.pull_requests if not pull_requests[issue_key]: doc.append("No pull requests") else: for pr in pull_requests[issue_key]: with doc.create( Subsection("Pull request {}".format( pr["number"]))): doc.append( NoEscape(r"{}: {}\\".format( bold("Title"), pr["title"]))) doc.append( NoEscape(r"{}: {}\\".format( bold("Author"), pr["author"]))) doc.append( NoEscape(r"{}: {}\\".format( bold("Date"), pr["date"]))) doc.append( NoEscape(r"{}: {}\\".format( bold("Status"), pr["status"]))) doc.append( NoEscape(r"{}: ".format(bold("Comments")))) if not pr["comments"]: doc.append("No comments") else: with doc.create(Enumerate()) as enum: for comment in pr["comments"]: enum.add_item( NoEscape("{} ({}): {}".format( bold(comment["author"]), comment["date"], escape_latex( comment["body"]. replace('\r', '\n')))))
def gerar_pdf_curso(curso): doc = pdfutils.init_document() pdfutils.pacotes(doc) # Configurações (preâmbulo) pdfutils.configuracoes_preambulo(doc) pdfutils.cabecalho(doc) frase_anexo = 'ANEXO V DA RESOLUÇÃO Nº 236/2014-CEPE, DE 13 DE NOVEMBRO DE 2014.' pdfutils.rodape(doc, NoEscape(r'\texttt{' + frase_anexo + '}')) doc.append(NoEscape(r'{\normalsize\texttt{' + frase_anexo + '}}')) pdfutils.titulo(doc, 'FORMULÁRIO ESPECÍFICO PARA ATIVIDADES DE EXTENSÃO', 'MODALIDADE CURSO DE EXTENSÃO') doc.append(Command('hrulefill')) # Início do formulário with doc.create(Enumerate()) as enum: pdfutils.item(doc, enum, 'TÍTULO: ', escape_latex(curso.titulo)) pdfutils.item(doc, enum, 'COORDENADOR(a): ', escape_latex(curso.coordenador.nome_completo)) periodo_inicio = curso.periodo_realizacao_inicio.strftime('%d/%m/%Y') periodo_fim = curso.periodo_realizacao_fim.strftime('%d/%m/%Y') periodo_realizacao = 'de {} a {}'.format(periodo_inicio, periodo_fim) pdfutils.item(doc, enum, 'PERÍODO DE REALIZAÇÃO: ', periodo_realizacao) pdfutils.mdframed_informar(doc, enum, curso.programa_extensao) pdfutils.tabela_unidade_administrativa(doc, enum, curso.unidade_administrativa, curso.campus) pdfutils.tabela_centro(doc, enum, curso.centro) pdfutils.tabela_grande_area(doc, enum, id=curso.grande_area.id) pdfutils.tabela_palavras_chave( doc, enum, PalavraChave_CursoExtensao.objects.filter( curso_extensao_id=curso.id)) pdfutils.tabela_area_tematica_principal( doc, enum, id=curso.area_tematica_principal.id) if curso.area_tematica_secundaria: pdfutils.tabela_area_tematica_secundaria( doc, enum, id=curso.area_tematica_secundaria.id) else: pdfutils.tabela_area_tematica_secundaria(doc, enum) pdfutils.tabela_linha_extensao(doc, enum, curso.linha_extensao, id=curso.linha_extensao.id) pdfutils.item(doc, enum, 'PÚBLICO ALVO: ', escape_latex(curso.publico_alvo)) pdfutils.item(doc, enum, 'NÚMERO DE PESSOAS A SEREM BENEFICIADAS: ', curso.numero_pessoas_beneficiadas) pdfutils.item(doc, enum, 'CARGA HORÁRIA TOTAL: ', curso.carga_horaria_total) pdfutils.item(doc, enum, 'Nº DE VAGAS: ', curso.numero_vagas) pdfutils.item(doc, enum, 'LOCAL DA INSCRIÇÃO: ', escape_latex(curso.local_inscricao)) pdfutils.item(doc, enum, NoEscape(r'RESUMO: \\')) resumo_fmt = curso.resumo.replace('\r', '') doc.append(escape_latex(resumo_fmt)) pdfutils.item(doc, enum, NoEscape(r'PROGRAMAÇÃO: \\')) programacao_fmt = curso.programacao.replace('\r', '') doc.append(escape_latex(programacao_fmt)) pdfutils.item(doc, enum, NoEscape(r'EQUIPE DE TRABALHO: \\')) pdfutils.mdframed_equipe_trabalho(doc, curso) pdfutils.item(doc, enum, NoEscape(r'DISCENTES UNIOESTE: \\')) pdfutils.tabela_discentes(doc, curso) pdfutils.item( doc, enum, NoEscape(r'MEMBROS DA COMUNIDADE / PARTICIPANTES EXTERNOS: \\')) pdfutils.tabela_membros(doc, curso) # Checa antes pois a previsão orçamentária não é obrigatório if PrevisaoOrcamentaria_CursoExtensao.objects.filter( curso_extensao_id=curso.id): previsao_orcamentaria = PrevisaoOrcamentaria_CursoExtensao.objects.get( curso_extensao=curso.id) pdfutils.tabela_previsao_orcamentaria(doc, enum, previsao_orcamentaria) pdfutils.tabela_gestao_recursos_financeiros( doc, enum, previsao_orcamentaria) os.system('mkdir -p ' + PDF_DIR) filepath = '{}/curso-extensao_{}'.format(PDF_DIR, str(curso.id)) doc.generate_pdf(filepath, clean_tex=False, compiler=pdfutils.COMPILER, compiler_args=pdfutils.COMPILER_ARGS) return filepath
def gerar_pdf_relatorio(relatorio): doc = pdfutils.init_document() pdfutils.pacotes(doc) # Configurações (preâmbulo) pdfutils.configuracoes_preambulo(doc) pdfutils.cabecalho(doc) frase_anexo = 'ANEXO X DA RESOLUÇÃO Nº 236/2014-CEPE, DE 13 DE NOVEMBRO DE 2014.' pdfutils.rodape(doc, NoEscape(r'\texttt{' + frase_anexo + '}')) doc.append(NoEscape(r'{\normalsize\texttt{' + frase_anexo + '}}')) pdfutils.titulo(doc, 'RELATÓRIOS ESPECÍFICOS PARA ATIVIDADES DE EXTENSÃO', 'RELATÓRIO DE EVENTOS E CURSOS') doc.append(Command('hrulefill')) # Início do formulário with doc.create(Enumerate()) as enum: pdfutils.item(doc, enum, 'TÍTULO DA ATIVIDADE: ', escape_latex(relatorio.projeto_extensao.titulo)) with doc.create(Enumerate()) as subenum: subenum.add_item('Vinculada a algum Programa de Extensão? ') if relatorio.projeto_extensao.programa_extensao: doc.append(NoEscape(r'Não ({}) Sim ({}): Qual? {}'.format(pdfutils.PHANTOM, pdfutils.TIMES, escape_latex(relatorio.projeto_extensao.programa_extensao.nome)))) else: doc.append(NoEscape(r'Não ({}) Sim ({}): Qual? '.format(pdfutils.TIMES, pdfutils.PHANTOM))) pdfutils.item(doc, enum, 'COORDENADOR(a): ', escape_latex(relatorio.projeto_extensao.coordenador.nome_completo)) periodo_inicio = relatorio.periodo_inicio.strftime('%d/%m/%Y') periodo_fim = relatorio.periodo_fim.strftime('%d/%m/%Y') periodo_realizacao = 'de {} a {}'.format(periodo_inicio, periodo_fim) pdfutils.item(doc, enum, 'PERÍODO DO RELATÓRIO: ', periodo_realizacao) pdfutils.tabela_unidade_administrativa(doc, enum, relatorio.projeto_extensao.unidade_administrativa, relatorio.projeto_extensao.campus) pdfutils.tabela_centro(doc, enum, relatorio.projeto_extensao.centro) pdfutils.item(doc, enum, 'COLEGIADO: ', escape_latex(relatorio.projeto_extensao.coordenador.colegiado)) pdfutils.item(doc, enum, 'PÚBLICO ATINGIDO: ', escape_latex(relatorio.publico_atingido)) pdfutils.item(doc, enum, 'CERTIFICADOS: ') pdfutils.tabela_certificados(doc, id=relatorio.id) pdfutils.item(doc, enum, NoEscape(r'RESUMO DA ATIVIDADE REALIZADA: \\')) resumo_fmt = escape_latex(relatorio.resumo.replace('\r', '')) doc.append(escape_latex(resumo_fmt)) pdfutils.item(doc, enum, NoEscape(r'RELACIONAR AS ATIVIDADES REALIZADAS OU A PROGRAMAÇÃO PARA CURSOS OU EVENTOS: \\')) atividades_fmt = relatorio.atividades_realizadas_programacao.replace('\r', '') doc.append(escape_latex(atividades_fmt)) pdfutils.item(doc, enum, NoEscape(r'RELACIONAR AS DIFICULDADES TÉCNICAS E/OU ADMINISTRATIVAS (se houver): \\')) dificuldades_fmt = relatorio.dificuldades.replace('\r', '') doc.append(escape_latex(dificuldades_fmt)) pdfutils.local_data_assinatura(doc) os.system('mkdir -p ' + PDF_DIR) filepath = '{}/relatorio_{}'.format(PDF_DIR, str(relatorio.id)) doc.generate_pdf(filepath, clean_tex=False, compiler=pdfutils.COMPILER, compiler_args=pdfutils.COMPILER_ARGS) return filepath
def fill_document(doc): with doc.create(Section('Section 9.1', numbering=False)): with doc.create(Subsection('8', numbering=False)): with doc.create( Enumerate(enumeration_symbol=r"\alph*)", options={'start': 1})) as enum: enum.add_item('5') enum.add_item('3') enum.add_item('7') enum.add_item(NoEscape('$\sqrt{49+25}\\approx 8.6$')) enum.add_item(NoEscape('$\sqrt{9+25}\\approx 5.8$')) enum.add_item(NoEscape('$\sqrt{49+9}\\approx 7.6$')) with doc.create(Subsection('12', numbering=False)): with doc.create(Alignat(numbering=False, escape=False)) as agn: agn.append( r'radius = \sqrt{(\sqrt{1^2+2^2})^2+3^2} &= \sqrt{14} \\') agn.append(r'(x-1)^2+(y-2)^2+(z-3)^2 &= (\sqrt{14})^2\\') agn.append(r'(x-1)^2+(y-2)^2+(z-3)^2 &= 14') with doc.create(Subsection('14', numbering=False)): with doc.create(Alignat(numbering=False, escape=False)) as agn: agn.append(r'x^2+8x+y^2-6y+z^2+2z &= -17\\') agn.append(r'(x+4)^2-16+(y-3)^2-9+(z+1)^2-1 &= -17\\') agn.append(r'(x+4)^2+(y-3)^2+(z+1)^2 &= -17 +16+9+1\\') agn.append(r'(x+4)^2+(y-3)^2+(z+1)^2 &= 9\\') doc.append( 'The equation represents a sphere with center (-4,3,-1) and radius = 3' ) with doc.create(Subsection('16', numbering=False)): with doc.create(Alignat(numbering=False, escape=False)) as agn: agn.append(r'3(x^2+y^2+z^2) &=10+6y+12z\\') agn.append(r'x^2+y^2+z^2 &=\frac{10}{3}+2y+4z\\') agn.append(r'x^2+y^2-2y+z^2-4z &=\frac{10}{3}\\') agn.append(r'x^2+(y-1)^2-2+(z-2)^2-4 &=\frac{10}{3}\\') agn.append(r'x^2+(y-1)^2+(z-2)^2 &=\frac{10}{3}+2+4\\') agn.append(r'x^2+(y-1)^2+(z-2)^2 &=\frac{28}{3}\\') doc.append( 'The equation represents a sphere with center (0,1,2) and radius =' ) doc.append(NoEscape('$2\sqrt{\\frac{7}{3}}$')) with doc.create(Subsection('21-32', numbering=False)): with doc.create( Enumerate(enumeration_symbol=r"\arabic*)", options={'start': 21})) as enum: enum.add_item( 'The vertical plane that lies over the line given by x=5 in the xy-plane' ) enum.add_item( 'The vertical plane that lies over the line given by y=-2 in the xy-plane' ) enum.add_item( 'The subspace containing all numbers smaller than the plane that goes through y=8' ) enum.add_item( 'The subspace containing all numbes larger than the vertical plane that lies over the line given by x=-3 in the xy-plane' ) enum.add_item( 'The subspace contained between (and including) the xy-planes that pass through z=0 and z=6' ) enum.add_item( 'The cup-shaped shell defined by spinning the parabola given by ' ) doc.append(NoEscape('$z^2=1$')) doc.append(' spun around the z-axis') enum.add_item( 'The circle that lies in the xy-plane and is centered at (0,0,-1) and has a radius = 2' ) enum.add_item( 'The cylindrical shell of radius = 4 that is centered around the x-axis' ) enum.add_item( 'The subspace contained within the sphere centered at (0,0,0) with radius ' ) doc.append(NoEscape('$\leq\sqrt{3}$')) enum.add_item( 'The plane that extends out from the line given by x=z') enum.add_item( 'The subspace that is outside the sphere centered at (0,0,1) with a radius of 1' ) with doc.create(Subsection('38', numbering=False)): with doc.create(Alignat(numbering=False, escape=False)) as agn: agn.append( r'\sqrt{(x+1)^2+(y-5)^2+(z-3)^2} &= 2\sqrt{(x-6)^2+(y-2)^2+(z+2)^2}\\' ) agn.append( r'x^2+2x+1+y^2-10y+25+z^2-6z+9 &= 4(x^2-12x+36+y^2-4y\\ \ &\textnormal{ }+4+z^2+4z+4)\\') agn.append( r'4x^2-x^2-48x-2x+4y^2-y^2-16y+10y+4z^2-z^2+16z+6z &= -141\\' ) agn.append(r'3x^2-50x+3y^2-6y+3z^2+22z &=-141\\') agn.append( r'x^2-\frac{50}{3}x+y^2-2y+z^2+\frac{22}{3}z &=-47\\') agn.append( r'(x-\frac{25}{3})^2+(y-1)^2+(z-\frac{11}{3})^2 &=-47+\frac{625}{9}+\frac{121}{9}\\' ) agn.append( r'(x-\frac{25}{3})^2+(y-1)^2+(z-\frac{11}{3})^2 &=\frac{323}{9}\\' ) doc.append('The center is (25/3, 1, 11/3) and the radius is ') doc.append(NoEscape('$\\frac{\\sqrt{323}}{3}$')) with doc.create(Section('Section 9.2', numbering=False)): with doc.create(Subsection('22', numbering=False)): doc.append( NoEscape( '$\\langle \\frac{-6}{\\sqrt{6}}, \\frac{12}{\\sqrt{6}}, \\frac{6}{\\sqrt{6}}\\rangle$' )) with doc.create(Subsection('28', numbering=False)): with doc.create(Alignat(numbering=False, escape=False)) as agn: agn.append( r'wind = &\langle 50cos(\frac{7\pi}{4}), 50sin(\frac{7\pi}{4}) \rangle \ \\plane = &\langle 250cos(\frac{\pi}{6}), 250sin(\frac{\pi}{6}) \rangle\\' ) agn.append( r'true course = \langle 251.86, 89.64\rangle \textnormal{ and } & \ ground speed = \sqrt{251.86^2 + 89.64^2} = 267.34\\') with doc.create(Subsection('38', numbering=False)): with doc.create(Alignat(numbering=False, escape=False)) as agn: agn.append(r'\vec{i} = & \langle 1,0,0 \rangle\\') agn.append(r'\vec{j} = & \langle 0,1,0 \rangle\\') agn.append(r'\vec{k} = & \langle 0,0,1 \rangle\\') agn.append( r'\vec{v} = & \langle a\vec{i},b\vec{j},c\vec{k} \rangle\\' ) agn.append( r'hypotenuse = \rvert\rvert v\rvert\rvert = & \sqrt{a^2+b^2+c^2}\\' ) agn.append(r'cos\alpha = & \frac{a}{\sqrt{a^2+b^2+c^2}}\\') agn.append(r'cos\beta = & \frac{b}{\sqrt{a^2+b^2+c^2}}\\') agn.append(r'cos\gamma = & \frac{c}{\sqrt{a^2+b^2+c^2}}\\') agn.append( r'cos^2\alpha + cos^2\beta + cos^2\gamma = & \frac{a^2}{a^2+b^2+c^2} + \ \frac{b^2}{a^2+b^2+c^2} + \frac{c^2}{a^2+b^2+c^2}\\' ) agn.append(r'cos^2\alpha + cos^2\beta + cos^2\gamma = & 1\\') with doc.create(Subsection('43', numbering=False)): with doc.create(Figure(position='h!')) as triangle_pic: image_filename = os.path.join(os.path.dirname(__file__), 'tri1.jpg') triangle_pic.add_image(image_filename, width='255px')
itemize.add_item("the first item") itemize.add_item("the second item") itemize.add_item("the third etc") # you can append to existing items itemize.append(Command("ldots")) # create a numbered "enumerate" list like the below: # \begin{enumerate}[label=\alph*),start=20] # \item The first item # \item The second item # \item The third etc \ldots # \end{enumerate} with doc.create(Section('"Enumerate" list')): with doc.create( Enumerate(enumeration_symbol=r"\alph*)", options={'start': 20})) as enum: enum.add_item("the first item") enum.add_item("the second item") enum.add_item(NoEscape("the third etc \\ldots")) # create a labelled "description" list like the below: # \begin{description} # \item[First] The first item # \item[Second] The second item # \item[Third] The third etc \ldots # \end{description} with doc.create(Section('"Description" list')): with doc.create(Description()) as desc: desc.add_item("First", "The first item") desc.add_item("Second", "The second item")
with doc.create(Itemize()) as itemize: itemize.add_item("the first item") itemize.add_item("the second item") itemize.add_item("the third etc") # you can append to existing items itemize.append(Command("ldots")) # create a numbered "enumerate" list like the below: # \begin{enumerate} # \item The first item # \item The second item # \item The third etc \ldots # \end{enumerate} with doc.create(Section('"Enumerate" list')): with doc.create(Enumerate()) as enum: enum.add_item("the first item") enum.add_item("the second item") enum.add_item(NoEscape("the third etc \\ldots")) # create a labelled "description" list like the below: # \begin{description} # \item[First] The first item # \item[Second] The second item # \item[Third] The third etc \ldots # \end{description} with doc.create(Section('"Description" list')): with doc.create(Description()) as desc: desc.add_item("First", "The first item") desc.add_item("Second", "The second item")