def test_luatextmk_errorlog(): """Check if parsing of error lines works.""" f_min_latex = min_latex.replace(r"\maketitle", r"\makexxx") try: build_pdf(f_min_latex, builder='lualatexmk') except LatexBuildError as err: assert err.get_errors()
def create_report(voters, title, fname): latex.build_pdf( make_env(loader=FileSystemLoader('.')).get_template( 'vrlist-template.tex').render( records=hierarchize_and_latexify_voters(voters), num_voters='{:,d}'.format(len(voters)), title=fix_latex_string(title), )).save_to(fname)
def _assert_latex_compatibility(self): from latex import build_pdf, LatexBuildError try: build_pdf('\\documentclass{article}\\begin{document}\n' + self._expression + '\n\\end{document}') except LatexBuildError as e: for err in e.get_errors(): self.status = 'failed' logger.error('Error in {}, line {}: {}'.format( err['filename'], err['line'], err['error']))
def test_finds_errors_correctly(): broken_latex = r""" \documentclass{article} \begin{document} All good \undefinedcontrolsequencehere \end{document} """ try: build_pdf(broken_latex) except LatexBuildError as e: assert parse_log(e.log) == e.get_errors() else: assert False, 'no exception raised'
def create_tex_file(req, x, y, z, x_cov, y_cov, z_cov, x_arr, y_arr, z_arr, sputniks, time_in_sec): x_min = min(x_arr) y_min = min(y_arr) z_min = min(z_arr) x_max = max(x_arr) y_max = max(y_arr) z_max = max(z_arr) for i in range(len(x_arr)): x_arr[i] = (time_in_sec[i], (x_arr[i] - x_min) / (x_max - x_min + EPS)) for i in range(len(y_arr)): y_arr[i] = (time_in_sec[i], (y_arr[i] - y_min) / (y_max - y_min + EPS)) for i in range(len(z_arr)): z_arr[i] = (time_in_sec[i], (z_arr[i] - z_min) / (z_max - z_min + EPS)) for i in range(len(sputniks)): sputniks[i] = (time_in_sec[i], sputniks[i]) tex_text = render_to_string('tex_template', context={ 'X': x, 'Y': y, 'Z': z, 'X_COV': x_cov, 'Y_COV': y_cov, 'Z_COV': z_cov, 'X_ARR': x_arr, 'Y_ARR': y_arr, 'Z_ARR': z_arr, 'sputniks': sputniks, 'time': time_in_sec, 'TIME_MIN': min(time_in_sec), 'TIME_MAX': max(time_in_sec) }) logger.warning(tex_text) f = open(settings.BASE_DIR + '/media/' + req.file.name + '.tex', 'w') f.write(tex_text) f.close() latex.build_pdf(tex_text).save_to(settings.BASE_DIR + '/media/' + req.file.name + '.pdf')
def printToPDF(self, template, variables=None): template = self.env.get_template(template) self._parsed_tex = template.render(variables) pdf = latex.build_pdf(self._parsed_tex) return pdf
def test_view_latex(request): ''' Many of this will be not needed !!!! ''' name = 'anon' if request.method == 'POST': # Set to a "good" Username instead of Anon if request.user.username != '': name = request.user.username print(request.POST) with open(name + ".tex", 'w') as f: f.write(request.body.decode("UTF-8")) latex = (open(name + ".tex")) b64_data = "" try: pdf = build_pdf(latex) pdf.save_to('test.pdf') b64_data = base64.b64encode(pdf.data) except LatexBuildError as e: for err in e.get_errors(): print(u'Error in {0[filename]}, line {0[line]}: {0[error]}'.format(err)) # also print one line of context print(u' {}'.format(err['context'][1])) context = "" # convert to base64 context = { 'data': b64_data.decode("UTF-8") } return render(request, 'index.html', context)
def sv_to_pdf(input, caption=None, name=None, delimiter=None, has_header=True, left_aligned_to_header=False, right_aligned_to_header=False, header_gap_size=0, number_label_columns=0, start_line=None, end_line=None, transpose=False, formula=None, number_table_splits=0, tex_lines=False, tex_long_table=False, tex_landscape=False, tex_thin_margins=False): tex_str = sv_to_tex(input, delimiter, has_header, left_aligned_to_header, right_aligned_to_header, header_gap_size, number_label_columns, start_line, end_line, transpose, formula, number_table_splits) return build_pdf( _encapsulate_latex_table(tex_str, caption, name, number_label_columns, tex_lines, tex_long_table, tex_landscape, tex_thin_margins))
def create_book(directory, lang, output, to_pdf): posts_dir = os.path.join(directory, lang) posts = [] for root, _, files in os.walk(posts_dir): posts.extend([os.path.join(root, f) for f in files]) # Filter the non-posts posts = [p for p in posts if re.match(r'^(\w+\/)+\d{4}-\d{2}-\d{2}', p)] recipes = [Recipe(post) for post in posts] with open(os.path.join(directory, f'{lang}.yml'), 'r') as f: i18n = yaml.load(f)['book'] template = env.get_template('base.tex') book = template.render(recipes=recipes, i18n=i18n).replace('°', r'$^\circ$') filename = i18n["filename"] if to_pdf: # this builds a pdf-file inside a temporary directory pdf = build_pdf(book) pdf.save_to(os.path.join(output, f'{filename}.pdf')) else: with open(os.path.join(output, f'{filename}.tex'), 'w') as f: f.write(book)
def make_downloadable_pdf(self, filename, texstring): pdf = latex.build_pdf(texstring, [self.static_path]) response = make_response(str(pdf)) response.headers[ "Content-Disposition"] = "attachment; filename={}".format(filename) response.headers["Content-Type"] = "application/pdf" return response
def make_attachable_pdf(self, filename, texstring): pdf = latex.build_pdf(texstring, [self.static_path]) return { "filename": filename, "mimetype": "application/pdf", "data": str(pdf) }
def export_latex(self): aulas = self.getAulas().json params = { "sil_per_aca": "2020-B", } output = BytesIO() latex = "" for i in aulas: params['aul_ide'] = i['aul_ide'] params['aul_nom'] = i['aul_nom'] latex += "\\section{" + params['aul_nom'] + "}" columnas = ["LUNES", "MARTES", "MIERCOLES", "JUEVES", "VIERNES"] datos = self.get_schedule(params).json info = self.horario_array(datos) index = self.horario_index(datos) df_1 = pd.DataFrame(info, columns=columnas, index=index) latex += df_1.to_latex() output.write(latex.encode('utf-8')) output.seek(0) pdf = build_pdf(output) pdf.save_to('ga.pdf') return send_file(output, attachment_filename="horario.html", as_attachment=True)
def pdf(): texonly = 'texonly' in request.args orientation = 'landscape' if 'landscape' in request.args else 'portrait' cols = whitelist(request.args.get('cols', ''), digits) or '2' font = whitelist(request.args.get('font', ''), digits+letters) fontoptions = whitelist(request.args.get('fontoptions', ''), digits+letters) songids = request.args.get('songids') if songids: try: songids = map(int, songids.split(',')) except ValueError: return 'Invalid songid' else: return 'No songs' template = texenv.get_template('songs.tex') tex = template.render( songs=[song_dict[x] for x in songids if x in song_dict], cols=cols, orientation=orientation, font=font, fontoptions=fontoptions) if texonly: return Response(tex, mimetype='text/plain') else: try: pdffile = build_pdf(tex) except LatexBuildError as e: return Response(tex, mimetype='text/plain') return Response(bytes(pdffile), mimetype='application/pdf')
def test_algorithmLaTeX(F): # iter on realizations for R in F.iterAllRealizations(): print(R.name + "\t") # get LaTeX code code = R.algorithmLaTeX() print(code) # compile it try: build_pdf(code) except LatexBuildError as e: for err in e.get_errors(): print(err["context"][1]) raise LatexBuildError except RuntimeError: print("LaTeX is not installed")
def pdf(): texonly = 'texonly' in request.args orientation = 'landscape' if 'landscape' in request.args else 'portrait' cols = request.args.get('cols') or 2 font = request.args.get('font') fontoptions = request.args.get('fontoptions') recipeids = request.args.get('recipeids') if recipeids: try: recipeids = map(int, recipeids.split(',')) except ValueError: return 'Invalid recipeid' else: return 'No recipes' template = texenv.get_template('recipes.tex') tex = template.render( recipes=[recipe_dict[x] for x in recipeids if x in recipe_dict], cols=cols, orientation=orientation, font=font, fontoptions=fontoptions) if texonly: return Response(tex, mimetype='text/plain') else: try: pdffile = build_pdf(tex) except LatexBuildError as e: return Response(tex, mimetype='text/plain') return Response(bytes(pdffile), mimetype='application/pdf')
def build_report(template_filepath: str, data: Optional[Dict] = None, builder: Optional[str] = None) -> Optional[Data]: """ Builds the given template with the given data :param template_filepath: Template's path to use :param data: Keywords-values for the given LaTeX-template :param builder: Builder to use 'latexmk', 'pdflatex', 'xelatexmk'; None = default = 'pdflatex :return: LaTeX-report """ # Put the data into the template rendered_template = read_and_fill_template(template_filepath, data) if not rendered_template: logger.error(AGENT_UTILS_NAME, f'Template was not found or filled correctly: {template_filepath}') return None # Build the template, and save the result to a file try: pdf = build_pdf(rendered_template, builder=builder) except Exception as e: pdf = None tb = traceback.format_exc() logger.error(AGENT_UTILS_NAME, f'Cant build LaTeX report with builder "{builder}" and data: "{data}".\n' f'Message: {e}.\nStackTrace: {tb}') return pdf
def home(): template = env.get_template('ex2.latex') pdf = build_pdf(template.render(name='Alice')) return bytes(pdf), 200, { 'Content-Type': 'application/pdf', 'Content-Disposition': 'inline; filename="report.pdf"' }
def export(file, format, solution): """ Export the questions to another format. """ # t = Teampy() file_input = click.open_file(file, encoding="utf-8") questionaire = _load_rat_file(file_input) if questionaire is None: return solution = Solution.create_solution_from_string(solution) if format == "blackboard": text = questionaire.write_blackboard(solution) export_file_path = os.path.join(os.path.dirname(file), "blackboard.txt") with open(export_file_path, "w", encoding="utf-8") as file: file.write(text) elif format == "supermark": text = questionaire.write_supermark(solution) export_file_path = os.path.join(os.path.dirname(file), "rat.md") with open(export_file_path, "w", encoding="utf-8") as file: file.write(text) elif format == "pdf": latex = questionaire.write_pdf(solution) export_file_path = os.path.join(os.path.dirname(file), "rat.pdf") # empty directory for tex reasons... current_dir = os.path.abspath(os.path.dirname(file)) pdf = build_pdf(latex, texinputs=[current_dir, ""]) pdf.save_to(export_file_path)
def create_pdf(self, fname=None, build_dir=None, include_subfiles=True): """ Create a PDF of the guidebook Parameters ---------- fname : str, optional Name of file to create, otherwise `main.pdf` is used build_dir : str, optional Directory to build LaTex files include_subfiles : bool or Iterable Rebuild all, None or some of the chapter subfiles. """ build_dir = build_dir or './' #Create LateX name fname = fname or 'main.pdf' tex_name = os.path.splitext(fname)[0] + '.tex' fname = os.path.join(build_dir, fname) #Append build directory logger.info("Creating PDF file at %s ...", fname) #Create LaTeX self.create_tex(tex_name, build_dir=build_dir, include_subfiles=include_subfiles) #Create the PDF logger.debug("Beginning creation of pdf ...") pdf = build_pdf(open(tex_name, 'r').read(), texinputs=[build_dir]) pdf.save_to(fname)
def pdf(): texonly = 'texonly' in request.args orientation = 'landscape' if 'landscape' in request.args else 'portrait' cols = request.args.get('cols') or 2 font = request.args.get('font') fontoptions = request.args.get('fontoptions') songids = request.args.get('songids') if songids: try: songids = map(int, songids.split(',')) except ValueError: return 'Invalid songid' else: return 'No songs' template = texenv.get_template('songs.tex') tex = template.render( songs=[song_dict[x] for x in songids if x in song_dict], cols=cols, orientation=orientation, font=font, fontoptions=fontoptions) if texonly: return Response(tex, mimetype='text/plain') else: try: pdffile = build_pdf(tex) except LatexBuildError as e: return Response(tex, mimetype='text/plain') return Response(pdffile.file.read(), mimetype='application/pdf')
def compile(self, output=False): pdf = latex.build_pdf(self.content) if output: path = self.remote.replace(".tex", "") path += ".pdf" pdf.save_to(path) return pdf
def render_letter(request, template): recipients = (int(x) for x in request.session['recipients'].split(',')) recipients = Member.objects.filter(pk__in=recipients) template = LetterTemplate.objects.get(pk=template) form = LatexLetterForm(template=template) r = 'admin:mportal_member_changelist' opts = Member._meta if request.method == 'POST': form = LatexLetterForm(request.POST, request.FILES, template=template) if form.is_valid(): string = template.template.read().decode() t = engines['django'].from_string(string) context = form.cleaned_data.copy() context['recipients'] = recipients response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="letter.pdf"' src = t.render(context=context, request=request) latex_root = os.path.join(settings.MEDIA_ROOT, 'latex') for f in template.fields.all(): if f.input_type == 'forms.FileField' and\ request.FILES.get(f.var_name, None): fi = request.FILES[f.var_name] save_file_to(fi, os.path.join(latex_root, f.var_name)) pdf = build_pdf(src, texinputs=[latex_root]) response.write(bytes(pdf)) return response context = admin.site.each_context(request) context.update({ 'opts': opts, 'title': _('Brief generieren'), 'recipients': recipients, 'form': form, }) return render(request, 'mportal/render_letter.html', context)
def create_path_pdf(parts, filename): """Create a pdf file filename with images in parts. Arguments: parts: list of Image.PIL filename: str, name of the resulting file """ header = r""" \documentclass[a4paper]{article} \usepackage[top=1.5cm, bottom=1.5cm, left=0.5cm, right=0.5cm]{geometry} \usepackage{graphicx} \sloppy \begin{document} """ tdir = tempfile.TemporaryDirectory() fnames = [] for i, im in enumerate(parts): fname = "{}/{}.png".format(tdir.name, i) fnames.append(fname) im.save(fname) images = "\n\n".join('\includegraphics[scale=0.5]{' + fname + '}' for fname in fnames) footer = r""" \end{document} """ pdf = build_pdf("".join((header, images, footer))) pdf.save_to(filename) tdir.cleanup()
def _compile(latex_input) -> bytes: if build_pdf is None: raise RuntimeError('Python latex module not found') package = str(Path(__file__).parent.absolute()) + '/assets/pdf/' return bytes(build_pdf(latex_input, [package]))
def building_pdf(): # we need to supply absolute paths current_dir = os.path.abspath(os.path.dirname(__file__)) # we are adding an empty string to include the default locations (this is # described on the tex manpage) pdf = build_pdf(open('fall_texdoc.latex'), texinputs=[current_dir, '']) pdf.save_to('generated_pdf.pdf')
def refresh(): data = request.form['data'] dir = os.path.abspath(os.path.dirname(__file__)) pdf = latex.build_pdf(data, texinputs=[dir, '']) fs = open('static/_temp.pdf', 'w') fs.write(bytes(pdf)) fs.close() return redirect("/static/_temp.pdf")
def build_latex_pdf(template_name, context): latex_code = compile_jinja2_latex(template_name, context) try: pdf = build_pdf(latex_code, builder="pdflatex") except: with open(f"/{datetime.datetime.now()}.tex", "w") as f: f.write(latex_code) raise Exception("Latex pdf build error") return pdf
def generate_index(service, processed, processed_folder_id): required_properties = ['ucasPersonalId', 'extractedName'] fully_processed_files = [ item for item in processed if file_has_properties(item, required_properties) ] # Sort files fully_processed_files = sorted( fully_processed_files, key=lambda f: (f.get('appProperties', {}).get('extractedName', '').split(' ')[-1])) # Don't try to generate report if no files if len(fully_processed_files) == 0: return # Do we have an index already? index_files = [ item for item in processed if item.get('appProperties', {}).get('isIndex', False) ] # Make PDF env = latex.jinja2.make_env(loader=jinja2.loaders.FileSystemLoader( os.path.join(os.path.dirname(__file__), 'templates'))) template = env.get_template('report.template.tex') pdf = latex.build_pdf(template.render(files=fully_processed_files)) with tempfile.TemporaryDirectory() as tmpdir: outpath = os.path.join(tmpdir, 'index.pdf') with open(outpath, 'wb') as fobj: fobj.write(bytes(pdf)) # Upload PDF media = MediaFileUpload(outpath, mimetype='application/pdf') api_params = { 'body': { 'name': 'index.pdf', 'copyRequiresWriterPermission': True, 'appProperties': { 'isIndex': True, }, }, 'supportsTeamDrives': True, 'media_body': media, 'fields': 'id' } if len(index_files) == 0: api_params['body']['parents'] = [processed_folder_id] service.files().create(**api_params).execute() else: for item in index_files: service.files().update(fileId=item['id'], **api_params).execute()
def generate( course_name, quiz_number, output_dir, template_file, recipients_file, token_file, s ): """Driver/interface function for generating a report. """ # Create directories if needed figures_dir = Path(output_dir / "figures") for d in [output_dir, figures_dir]: export.create_dir(d) # Use a stale dataset, or grab a fresh one if s is True: print("Loading contents from file...") with open("contents.json", "r") as f: contents = json.load(f) else: print("Fetching data from Canvas...") with token_file.open("r") as f: token = f.read() c = Canvas("asu.instructure.com", "v1", token) report_df = c.get_quiz_report(course_name, quiz_number) print("Fetch complete.") contents = data_processing.generate_report_contents( c, report_df, quiz_number, figures_dir, recipients_file ) with open("contents.json", "w+") as f: json.dump(contents, f) # Render LaTeX template print("Rendering LaTeX Template...") env = make_env(loader=FileSystemLoader(str(template_file.parent))) tpl = env.get_template(str(template_file.name)) rendered_latex = tpl.render(contents=contents) print("Render complete.") # Typeset PDF print("Typesetting PDF...") base_filename = f"muddy_points_{contents.get('quiz_number')}" pdf_filename = Path(output_dir / f"{base_filename}.pdf") pdf = build_pdf(rendered_latex, texinputs=[str(Path.cwd()), ""]) pdf.save_to(str(pdf_filename)) print("Typesetting complete.") # Export to Microsoft Word and LaTeX formats for further editing docx_filename = Path(output_dir / f"{base_filename}.docx") latex_filename = Path(output_dir / f"{base_filename}.tex") export.make_texfile(rendered_latex, latex_filename) export.make_docx(latex_filename, docx_filename) # Create archive print("Creating archive...") zip_filename = Path(output_dir / f"{base_filename}.zip") export.make_archive( zip_filename, [pdf_filename, docx_filename, latex_filename], figures_dir ) print(f"Created archive: {zip_filename}")
def latex2pdf(data, output): """ (str, str) -> None :param data: string of LaTeX document :param output: name of output file :return: None """ pdf = build_pdf(data) with open(output, "wb") as file: pdf.save_to(file)
def _cli(input, output): from catex.core import merge text = merge(*input).__repr__() if output[-4:] == '.pdf': from latex import build_pdf pdf = build_pdf(text) pdf.save_to(output) else: file_out = click.open_file(output) file_out.write(text)
def pdf(): try: logging.info('interpreter_api.pdf(): building pdf') pdf = build_pdf(request.data) logging.debug('interpreter_api.pdf(): PDF creation was successful') return Response(bytes(pdf), status=200, mimetype='application/pdf') except LatexBuildError as e: logging.info('interpreter_api.pdf(): PDF creation was not successful') logging.exception(e) return Response(None, status=400, mimetype='application/pdf')
def convert_to_pdf(self): if self.converted is None: self.convert_to_text() self.pdf = None generated = False try: self.pdf = bytes(build_pdf(self.converted, builder='latexmk')) generated = True except LatexBuildError: print('latexmk failed to build. Falling back to xelatex...') if not generated: try: self.pdf = bytes(build_pdf(self.converted, builder='xelatexmk')) generated = True except LatexBuildError: print('xelatex failed to build. Aborting...') return self.pdf
def make_pdf(folderpath): filename = os.path.basename(os.path.normpath(folderpath))+".pdf" aux_file = os.path.basename(os.path.normpath(folderpath))+".aux" destination = os.path.join(BASE_DIR, "pdfs", filename) filepath = os.path.join(folderpath, "main.tex") pdf = build_pdf(open(filepath), texinputs=[folderpath, '']) pdf.save_to(destination) # format_from_file(aux_file_name = aux_file, filename="main.bib", style=None) dir1 = os.path.basename(destination) dir2 = os.path.split(os.path.dirname(destination))[1] return os.path.join("/",dir2, dir1)
def test_generates_something(): min_latex = r""" \documentclass{article} \begin{document} Hello, world! \end{document} """ pdf = build_pdf(min_latex) assert pdf
def pdf(): try: if not 'items[]' in request.form: return redirect('/') if not 'authors[]' in request.form: return redirect('/') pdffile = build_pdf(get_tex()) return Response(pdffile.stream, mimetype='application/pdf') except LatexBuildError as e: return Response(tex, mimetype='application/x-tex')
def refresh(): data = request.form['data'] dir = os.path.abspath(os.path.dirname(__file__)) pdf = latex.build_pdf(data, texinputs=[dir, '']) project = request.form['project'].encode('utf-8') filename = str(current_user.id) + '_' + project db.blogs.save({"_id": filename, "user": str(current_user.id), \ "project": project, "update_time": time.time() , "data": data}) fs = open(dir + '/static/'+filename+'.pdf', 'w') fs.write(bytes(pdf)) fs.close() return redirect(urllib.quote("/static/"+filename+".pdf"))
def test_run_example(): min_latex = (r"\documentclass{article}" r"\begin{document}" r"Hello, world!" r"\end{document}") from latex import build_pdf # this builds a pdf-file inside a temporary directory pdf = build_pdf(min_latex) # look at the first few bytes of the header print(bytes(pdf)[:10])
def gen_pdf(): project = request.args.get('project') data = db.blogs.find_one({"user": str(current_user.id), "project": project }) if not data: return redirect("/static/basic.pdf") else: data = data['data'] dir = os.path.abspath(os.path.dirname(__file__)) pdf = latex.build_pdf(data, texinputs=[dir, '']) filename = str(current_user.id) + '_' + project.encode('utf-8') fs = open(dir + '/static/'+filename+'.pdf', 'w') fs.write(bytes(pdf)) fs.close() return redirect(urllib.quote("/static/"+filename+".pdf"))
def create_pdf(self, filename=''): self._make_tex() if not filename: filename = 'letter.pdf' self.__tex.seek(0) try: pdf = build_pdf(self.__tex.read().decode('utf-8')) pdf.save_to(filename) except LatexBuildError as e: for error in e.get_errors(): print(u'Error in {0[filename]}, line {0[line]}: {0[error]}'.format(error)) # also print one line of context print(u' {}'.format(error['context'][1])) print() self.__tex.close() sys.exit("Building PDF failed!")
def build_cv(data, templates_dir, assets_dir): current_dir = os.path.abspath(os.path.dirname(__file__)) env = make_env(loader=FileSystemLoader('.')) tpl = env.get_template("{}cv.latex".format(templates_dir)) # Only pass str names for latex for publication in data["publications"]: publication["authors"] = [author["name"] for author in publication["authors"]] for project in data["student_projects"]: project["name"] = project["student"]["name"] tex = tpl.render(**data) # Write tex with open("{}vince-knight.tex".format(assets_dir), 'w') as f: f.write(tex) # Write pdf pdf = build_pdf(tex, texinputs=[current_dir, '']) pdf.save_to("{}vince-knight.pdf".format(assets_dir))
from latex import build_pdf # build_pdf's source parameter can be a file-like object or a string pdf = build_pdf(open("ex1.latex")) # pdf is an instance of a data object (see http://pythonhosted.org/data/) # most often, we will want to save it to a file, as with this example pdf.save_to("ex1.pdf")
from jinja2 import FileSystemLoader from latex.jinja2 import make_env from latex import build_pdf # create a jinja2 environment with latex-compatible markup and instantiate a # template env = make_env(loader=FileSystemLoader('.')) tpl = env.get_template('ex2.latex') # create a greeting for all of our friends for name in ['Alice', 'Bob', 'Carol']: filename = 'hello-{}.pdf'.format(name.lower()) pdf = build_pdf(tpl.render(name=name)) pdf.save_to(filename)
awards = yaml.load(f) current_dir = os.path.abspath(os.path.dirname(__file__)) env = make_env(loader=FileSystemLoader('.')) tpl = env.get_template('cv.latex') tex = tpl.render(appointments=appointments, qualifications=qualifications, publications=publications, students=students, courses=courses, grants=grants, media=media, outreach_activities=outreach_activities, software_projects=software_projects, software_communities=software_communities, roles=roles, interests=interests, awards=awards, ) # Write tex with open("vince-knight.tex", 'w') as f: f.write(tex) # Write pdf pdf = build_pdf(tex, texinputs=[current_dir, '']) pdf.save_to("vince-knight.pdf")
def test_raises_correct_exception_on_fail(): broken_latex = r"""foo""" with pytest.raises(LatexBuildError): build_pdf(broken_latex)
# coding=UTF-8 min_latex = (r"\documentclass{article}" r"\begin{document}" r"Hello, world!" r"\end{document}") from latex import build_pdf # this builds a pdf-file inside a temporary directory pdf = build_pdf(min_latex)
from latex import build_pdf, LatexBuildError # the following inline latex-document is not valid: src = r""" \documentclass{article}\begin{document} \THISCONTROLSEQUENCEDOESNOTEXIT \end{document} """ # when building, catch the exception and print a clean error message try: build_pdf(src) except LatexBuildError as e: for err in e.get_errors(): print u"Error in {0[filename]}, line {0[line]}: {0[error]}".format(err) # also print one line of context print u" {}".format(err["context"][1]) print
import os from latex import build_pdf # we need to supply absolute paths current_dir = os.path.abspath(os.path.dirname(__file__)) # we are adding an empty string to include the default locations (this is # described on the tex manpage) pdf = build_pdf(open('ex3.latex'), texinputs=[current_dir, '']) pdf.save_to('ex3.pdf')