def compile_pdf(error, output): # Load document-template try: f = codecs.open(path.join(path_constants.installation, FATAL_ERROR_TEX_FILE), encoding='utf-8') except: raise IOError("Problem loading document template.") tex_code = u'' for line in f: tex_code += line tex_code = tex_code % error try: pdf = latex2pdf(unicode(tex_code)) except Exception as exc: raise RuntimeError("Problem generating pdf: %s" % exc) try: f = open(output, 'wb+') except Exception as exc: raise IOError("Problem opening file for output: %s" % exc) try: f.write(pdf) f.close() except Exception as exc: f.close() raise RuntimeError("Problem writing to PDF file: %s" % exc)
def generate(name, oformat): tformat = oformat if oformat == 'pdf': tformat = 'latex' conn = sqlite3.connect( DBFILE ) db = conn.cursor() presentation = db.execute('SELECT title,author,text FROM presentations WHERE name=?', (name,) ).fetchone() p_title = presentation[0] p_author = presentation[1] p_text = presentation[2] rows = db.execute('SELECT slide,title,text FROM slides WHERE name=?', (name,) ).fetchall() new_rows = [] for row in rows: new_row = (row[0], row[1], pypandoc.convert(row[2], tformat, format='markdown')) new_rows.append(new_row) rows = new_rows tpl = 'slides.' + oformat result = template(tpl, name=name, rows=rows, p_title=p_title, p_author=p_author) if oformat == 'html': return result elif oformat == 'pdf': result = latex2pdf(result) response.content_type = 'application/pdf' return result elif oformat == 'latex': response.content_type = 'text/plain; charset=utf-8' return result
def download(): if flask.request.method != 'POST': return flask.redirect(flask.url_for('index')) number = flask.request.form['number'] if not number.isdigit(): return flask.render_template('error.html', msg=u'Задано некорректное число задач.') else: number = int(number) if number <= 0: return flask.render_template('error.html', msg=u'Задано слишком маленькое число задач.') if number > 200: return flask.render_template('error.html', msg=u'Задано слишком большое число задач.') docType = flask.request.form['type'] if not docType in ['x-tex','pdf']: return flask.render_template('error.html', msg=u'Задан неверный тип документа.') data = markov.generate_tex(number) if docType == 'pdf': data = tex.latex2pdf(data.decode('utf8')) response = flask.make_response(data) response.headers['Content-Type'] = 'application/%s' % docType response.headers['Content-Disposition'] = 'attachment; filename="tasks"' return response
def test_instructionToLatex_renders(self): # Verify all instructions render correctly: ents = [] for i in cue.Instruction.__dict__: if '__' in i: continue instruction = cue.Instruction.__dict__[i] ents.append(cue.Entry(instruction, r"Description", 0.0)) r = cue.Route(ents, route_id=123, length_mi=0.0) latex_code = latex.makeLatex(r) pdf_data = tex.latex2pdf(latex_code)
def get_pdf(tex_obj): "creates a pdf from a textab object (using tex)" txt = tex_obj.get_tex() document = u""" \\documentclass{article} \\usepackage{booktabs} \\begin{document} %s \\end{document} """ % txt pdf = tex.latex2pdf(document) return pdf
def gen_doc(self, status): try: l = self.produce_list() self.document = self.document % tuple(l + [status]) self.document = self.document.replace("pct.", "\%") pdf = latex2pdf(unicode(self.document)) f = open(self.the_file, 'wb+') f.write(pdf) f.close() except Exception as exc: raise RuntimeError("Problem compiling document: %s" % exc)
def _QuickRender(instruction=cue.Instruction.NONE, modifier=cue.Modifier.NONE, description="", note="", abs_dist=0.0, for_dist=0.0, color=cue.Color.NONE): ''' Renders a single instruction to PDF. ''' ent = [ cue.Entry(instruction, description, abs_dist, note, modifier, for_dist, color) ] r = cue.Route(ent, route_id=123, length_mi=0.0) latex_code = latex.makeLatex(r) pdf = tex.latex2pdf(latex_code)
def test_latexRenderTest(self): ''' Create a few very pathological cue entries, verify the latex rendering doesn't choke: ''' ents = [ cue.Entry(cue.Instruction.LEFT, r"Are we escaping everything # & $ | < > % \\ {} ???", 0.0), cue.Entry( cue.Instruction.LEFT, r"What **about *formatting***? **Does **it** work, too?**", 0.1) ] r = cue.Route(ents, route_id=123, route_name=r"\terrible &oute Name \\ %%%", elevation_gain_ft=123.45, length_mi=123.456) latex_code = latex.makeLatex(r) pdf_data = tex.latex2pdf(latex_code)
def run(self): """ Actual fetcher. Could this be threaded? """ url = view_text_json % self.url logger.debug("Fetching URL: " + url) raw_content = urllib2.urlopen(url) json_content = json.loads(raw_content.read()) test_content = json_content['content'] test_content = unicodedata.normalize('NFKD', test_content).encode('ascii', 'ignore') # Here, we begin constructing the syntax tree parser = MyHTMLParser() parser.feed(test_content) string = """ \\documentclass[12pt]{article} \\begin{document} {\\Large %s} """ % clean(json_content['title']) for line in parser.lines: line = escape_latex(line) string += line string += """ \\end{document} """ with open('temp.latex', 'wb+') as f: f.write(string) pdf = latex2pdf(string) with open('temp.pdf', 'wb+') as f: f.write(pdf)
code = "".join(map(lambda x: str(x), source)) print code # In[ ]: book = {"parts": [ #alice_in_curiosity_country, gettysburg_address ]} latex = build_latex(book) f = open("book4.tex","w") f.write(latex) f.close() # In[ ]: from tex import latex2pdf pdf = latex2pdf(latex) f = open("book.pdf", 'w+') f.write(pdf) f.close() # In[ ]:
from tex import latex2pdf document = ur""" ... \documentclass{article} ... \begin{document} ... Hello, World! ... \end{document} ... """ print 'got here' pdf = latex2pdf(document) type(pdf) <type 'str'> print "PDF size: %.1f KB" % (len(pdf) / 1024.0) PDF size: 5.6 KB pdf[:5] '%PDF-' pdf[-6:] '%%EOF\n'
from tex import latex2pdf import sys if __name__ == "__main__": sys.stdout.write(latex2pdf(sys.stdin.read().decode("utf-8")))
#!/usr/bin/env python2
if not route_id.isalnum(): htmlError("Invalid route id: " + cgi.escape(route_id)) sys.exit(1) md5_hash = None cue_entries = None try: md5_hash, cue_entries = ridewithgps.getMd5AndCueSheet(route_id) except ridewithgps.RideWithGpsError as e: htmlError("Error querying RideWithGPS: %s" % e) sys.exit(1) basefilename = "%s-%s" % (route_id, md5_hash) pdffilename = basefilename + ".pdf" # base_dir = "/mnt/shared/mucow_cgi/roboviva/" base_dir = '.' os.chdir(base_dir) # Check if we've done this already: if not dataExists(pdffilename, base_dir): latex = latex.makeLatex(cue_entries) try: with open(pdffilename, 'wb') as pdffile: pdffile.write(tex.latex2pdf(latex)) except: htmlError("Error formatting latex!\n\n" + latex) sys.exit(1) servePDF(pdffilename)