def tex_framed_topng(filen, den="200"): if not os.path.isfile(filen): print(os.getcwd()) print("%s is not a file name." % filen) return # filen: name with dir and ext # filename: name with ext # flname: name but no ext ROOT = os.path.abspath('./') filedir, filename = os.path.split(filen) flname, ext = os.path.splitext(filename) if filedir != '': os.chdir(filedir) # nf is 'no frame' flname_nf = flname + "_nf" with open(flname, mode='r') as fl: try: text = fl.read() except Exception as e: print(e) return # deal with text text, text1, write_nf = text_treatment(text) with open(flname, mode='w') as fl: fl.write(text) if write_nf: with open(flname_nf, mode='w') as fl_nf: fl_nf.write(text1) pdfl = PDFLaTeX.from_texfile(flname) pdfl_nf = PDFLaTeX.from_texfile(flname_nf) try: pdfl.create_pdf(keep_pdf_file=True) pdfl_nf.create_pdf(keep_pdf_file=True) except Exception as e: print(e) return if not os.path.isdir(flname + "_images"): os.mkdir(flname + "_images") os.mkdir(flname + "_images/nf") os.mkdir(flname + "_images/hf") os.chdir(flname + "_images/hf") no_frame_pngs = to_png(flname, den) os.chdir("../nf") to_png(flname_nf, den) os.chdir('../') for png in no_frame_pngs: os.remove('hf/' + png) os.remove('nf/' + png) os.chdir(ROOT)
def create_pdf(self): self._prepare_attributes() with open('template.tex') as f: tex = f.read() try: urllib.request.urlretrieve(self.info['image'], "image.jpg") except Exception as e: re_image = re.compile('\\includegraphics.*\n') tex = re_image.sub('', tex) for att in RequiredAttributes: tex = tex.replace('%' + att.name + '%', self.info[att.name]) filename = slugify(self.info['name']) + ".tex" with open(filename, 'w') as f: f.write(tex) pdfl = PDFLaTeX.from_texfile('./' + filename) pdfl.pdf_filename = slugify(self.info['name']) pdfl.dir = os.path.dirname(os.path.realpath(__file__)) pdf, log, completed_process = pdfl.create_pdf(keep_pdf_file=True) os.remove(filename) try: os.remove('image.jpg') except: pass
def print_plan_mc_sheet(self, file_name): with open('mc_sheet.tex', 'w') as tempfile: tempfile.write(mc_sheet_header + self.mc_table_header()) for idx, race in enumerate(self.races): tempfile.write(race.as_mc_sheet(idx + 1)) tempfile.write(mc_table_footer) pdfl = PDFLaTeX.from_texfile('mc_sheet.tex') pdf, log, complete = pdfl.create_pdf() with open(file_name, 'wb') as outfile: outfile.write(pdf)
def download(type): if type == "pdf": main = page.to_latex() pdfl = PDFLaTeX.from_binarystring(main.encode("utf-8"), jobname="test") ret_file, _, _ = pdfl.create_pdf(keep_pdf_file=True, keep_log_file=False) elif type == "json": ret_file = json.dumps(page.to_dict(), indent=4) elif type == "tex": ret_file = page.to_latex() return Response( ret_file, mimetype=f"text/{type}", headers={"Content-disposition": f"attachment; filename=mcv.{type}"}, )
def write_pdf_from_tex(cls, tex_filename: str, pdf_filename: str = None): assert tex_filename.endswith( '.tex'), '"{}" is not a valid .tex file name'.format(tex_filename) if pdf_filename is None: pdf_filename = tex_filename[:-4] if pdf_filename[0] == '/': pdf_filename = pdf_filename[1:] if pdf_filename.endswith('.pdf'): pdf_filename = pdf_filename[:-4] pdfl = PDFLaTeX.from_texfile(tex_filename) pdfl.set_jobname(pdf_filename) pdfl.create_pdf(keep_pdf_file=True)
def submit_form(request): if request.method == 'POST': form = DocGenForm(request.POST) if form.is_valid(): link = form.cleaned_data["link"] language = form.cleaned_data["language"] file_type = form.cleaned_data["file_type"] if (os.path.basename(os.getcwd()) != "docs"): print(os.getcwd()) os.chdir("form_submit/templates/docs") # TODO: add 'make clean' equivalent before 'build_sphinx' f = open("settings.py", "w") f.write("language = '" + language + "'\n") f.write("link = '" + link + "'\n") f.close() if file_type == 'website': subprocess.call(['python', 'setup.py', 'build_sphinx']) return HttpResponseRedirect('/index') elif file_type == 'pdf': subprocess.call(['python', 'setup.py', 'build_sphinx']) os.chdir("./build/sphinx/latex") pdfl = PDFLaTeX.from_texfile('AideDesignSpecs.tex') pdf, _, _ = pdfl.create_pdf(keep_pdf_file=True) output_file = open('AideDesignSpecs.pdf', 'rb') response = HttpResponse(output_file, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="AideDesignSpecs.pdf"' output_file.close() return response else: # If the form is invalid, re-render the page with existing information. return render(request, "form_submit/submit.html", { "form": form }) return render(request, 'form_submit/submit.html', { 'form': DocGenForm() })
def write_tex(self): tex = '' for b in self.blocks: tex = tex + b.get_tex() tex = tex + '\end{document}' with open('somefile.tex', 'w') as tex_main: tex_main.write(tex) with open('structure.tex', 'w') as tex_struct: tex_struct.write(struct()) # time.sleep(5) pdfl = PDFLaTeX.from_texfile('somefile.tex') pdf, log, completed_process = pdfl.create_pdf(keep_pdf_file=True, keep_log_file=True) # time.sleep(5) os.rename('somefile.pdf', 'output.pdf') # os.rmdir('some*') os.system('rm some*') os.system('rm structure.tex')
def create_pdf(): text = request.get_json(force=True).get("text") print(text) print("_-----------------------_") name = "blub" encoding = "utf-8" raw_text = r'{}'.format(text) #print(raw_text) pdf, log, completed_process = PDFLaTeX.from_binarystring( raw_text.encode(encoding=encoding), name).create_pdf() #return send_file(base64.b64encode(pdf), mimetype="application/pdf") #print(bytearray(pdf).decode("utf-8")) #return base64.b64encode(pdf) # f = open("keks2.pdf", "wb") #print(base64.b64encode(pdf)) # f.write(base64.b64encode(pdf)) # f.close() return make_response(jsonify({"message":base64.b64encode(pdf).decode("ascii")}), 200) return send_file(pdf, mimetype="application/pdf", as_attachment=True, attachment_filename="blub.pdf") return make_response(jsonify({"message":str(base64.b64encode(bin(pdf)))}), 200)
def pdflatex(): pdfl = PDFLaTeX.from_texfile('rapport.tex') pdf, log, completed_process = pdfl.create_pdf(keep_pdf_file=True, keep_log_file=True)
from pdflatex import PDFLaTeX import sys file_name = sys.argv[1] tex_file = Path.cwd() / file_name pdfl = PDFLaTeX.from_texfile(tex_file) pdf_data = pdfl.create_pdf()[0] pdf_file = turnin_project_path / "{}.pdf".format(file_name[:-4]) pdf_file.write_bytes(pdf_data)
for i in range(len(origin_names)): print(origin_names[i]) print(new_names[i]) old_file = "cs2311HWs/{}/{}.tex".format(origin_names[i], origin_names[i]) old_txt = open(old_file).read() body_file_name = re.findall(r"\\input\{(hw.+)}", old_txt)[0] + ".tex" print(body_file_name) old_file = "cs2311HWs/{}/{}".format(origin_names[i], body_file_name) old_txt = open(old_file).read() # print(old_txt) new_file = "cs2311HWs/{}/{}".format(new_names[i], body_file_name) old_txt = change_date(old_txt) #old_txt = change_description(old_txt) # print(old_txt) atxtfile = open(atxt_names[i]).read() old_txt = change_ref_book(old_txt, atxtfile) f = open(new_file, mode="w") if f is None: exit(-1) f.write(old_txt) from pdflatex import PDFLaTeX pdfl = PDFLaTeX.from_texfile(new_file) pdf, log, completed_process = pdfl.create_pdf(keep_pdf_file=True, keep_log_file=False) # See PyCharm help at https://www.jetbrains.com/help/pycharm/
from pdflatex import PDFLaTeX import os latex_file = '/Users/venkateshmurugadas/Documents/nli_coliee/nli_legal_test_coliee_ovgu_local/attention_visuals/' import os files = [] for i in os.listdir(latex_file): if i.endswith('.tex'): files.append(i) for file in files: pdfl = PDFLaTeX.from_texfile(latex_file+file) pdf, log, completed_process = pdfl.create_pdf(keep_pdf_file= True)
def submit_form(request): if request.method == "POST": form = DocGenForm(request.POST) if form.is_valid(): link = form.cleaned_data["link"] report_type = form.cleaned_data["report_type"] if "esp" in report_type: language = "es" elif "eng" in report_type: language = "en" # language = form.cleaned_data["language"] # file_type = form.cleaned_data["file_type"] if "validation_pdf" in report_type: validator = Validator() validator.validate(link) file_name = ".".join( validator.report_writer.report_name.split(".")[:-1] + ["pdf"]) output_file = open(file_name, "rb") response = HttpResponse(output_file, content_type="application/pdf") response["Content-Disposition"] = ('attachment; filename="' + file_name + '"') output_file.close() return response else: if os.path.basename(os.getcwd()) != "docs": os.chdir("form_submit/templates/docs") with open("settings.py", "w") as f: f.write("language = '" + language + "'\n") f.write("link = '" + link + "'\n") f.close() # TODO: add 'make clean' equivalent before 'build_sphinx' if "docs_website" in report_type: subprocess.call(["python", "setup.py", "build_html"]) return HttpResponseRedirect("/index") elif "docs_pdf" in report_type: subprocess.call(["python", "setup.py", "build_latex"]) os.chdir("./build/sphinx/latex") pdfl = PDFLaTeX.from_texfile("AideDesignSpecs.tex") pdf, log, _ = pdfl.create_pdf(keep_pdf_file=True) output_file = open("AideDesignSpecs.pdf", "rb") response = HttpResponse(output_file, content_type="application/pdf") response["Content-Disposition"] = ("attachment; filename=" '"AideDesignSpecs.pdf"') output_file.close() # reset directory so if called again it's back in docs os.chdir("../../..") return response else: # If the form is invalid, re-render the page with existing info return render(request, "form_submit/submit.html", {"form": form}) return render(request, "form_submit/submit.html", {"form": DocGenForm()})
from pdflatex import PDFLaTeX import amazon.amazon_reviews import breast.breast_cancer import iris.iris import wine.wine_quality pdfl = PDFLaTeX.from_texfile("main.tex") pdf, log, completed_process = pdfl.create_pdf(keep_pdf_file=True, keep_log_file=False)
# col_format = "|" # column lines # for i in range(real_nrows): # col_format += "c|" # latex_table = pandas_table.to_latex(index=False, column_format=col_format) def latex_with_lines(df, *args, **kwargs): kwargs["column_format"] = "|".join( [""] + ["l"] * df.index.nlevels + ["r"] * df.shape[1] + [""] ) res = df.to_latex(*args, **kwargs) return res.replace("\\\\\n", "\\\\ \\midrule\n") latex_table = "\\LARGE\n" + latex_with_lines(pandas_table, index=False) latex_table_sol = "\\LARGE\n" + latex_with_lines(pandas_table_sol, index=False) f = open("LaTeX_stuffs/mytable.tex", "w") f.write(latex_table + "\n" + latex_table_sol) f.close() # Write latex document that imports mytable.tex f = open("LaTeX_stuffs/" + pdf_name + ".tex", "w") s = "\\documentclass{article}\n\\usepackage[a4paper, total={8in, 11in}]{geometry}\n\\usepackage{graphicx}\n\\renewcommand{\\arraystretch}{2.25}\n\\usepackage{booktabs}\n\\begin{document}\n\\input{LaTeX_stuffs/mytable}\n\\end{document}" f.write(s) f.close() # Make the pdf with PDFLaTeX pdfl = PDFLaTeX.from_texfile("LaTeX_stuffs/" + pdf_name + ".tex") pdf, log, completed_process = pdfl.create_pdf(keep_pdf_file=True, keep_log_file=False)
def pdf_compile(infile): pdfl = PDFLaTeX.from_texfile(infile) pdf, log, completed_process = pdfl.create_pdf(keep_pdf_file=True, keep_log_file=False)
def Solve_Square_Eq(aa, bb, cc, debug_mode=False): # aa, bb, cc = getEQ() eq_type = 'тип квадратного уравнения' if aa != 0 and bb != 0 and cc != 0: eq_type = 'full' elif aa == 0: print('это не квадратное уравнение') exit() elif bb == 0 and cc == 0: eq_type = 'trim_bc' elif bb == 0: eq_type = 'trim_b' elif cc == 0: eq_type = 'trim_c' os.chdir(os.path.dirname(os.path.abspath(__file__))) os.chdir(r'latex') tex_out = '{aa}x2{bb:+}x{cc:+}'.format(aa=aa, bb=bb, cc=cc) file = open(r'{}.tex'.format(tex_out), 'wt', encoding="utf-8") header = namedtuple('header', 'fsize doctype') coding = namedtuple('coding', 'coding module') language = namedtuple('language', 'lang module') # create tex document # \documentclass{article} writeline(file, getheader(header(r'[12pt]', '{article}'))) # \usepackage[utf8]{inputenc} writeline(file, getcoding(coding(r'[utf8]', '{inputenc}'))) # \usepackage[russian]{babel} writeline(file, getlanguage(language(r'[english,russian]', '{babel}'))) # body start writeline(file, r'\begin{document}') writeline(file, r'\begin{flushleft}') # user_Text writeline(file, equation(aa, bb, cc, et=eq_type)) if eq_type == 'full': for l in full_solution(aa, bb, cc): writeline(file, l) elif eq_type == 'trim_c': for l in trim_c_colution(aa, bb): writeline(file, l) elif eq_type == 'trim_b': for l in trim_b_colution(aa, cc): writeline(file, l) elif eq_type == 'trim_bc': for l in trim_bc_colution(aa): writeline(file, l) # body end writeline(file, r'\end{flushleft}') writeline(file, r'\end{document}') file.close() mode = '' if not debug_mode: mode = '-interaction=batchmode' priv = '--admin' # return_value = subprocess.call(['pdflatex', ''.join(mode), os.path.abspath(tex_out)], shell=False) file = '{}.{}'.format(os.path.abspath(tex_out), 'tex') pdfl = PDFLaTeX.from_texfile(os.path.abspath(file)) pdfl.set_output_directory('latex') pdfl.set_jobname(tex_out) pdf, log, completed_process = pdfl.create_pdf(keep_pdf_file=True, keep_log_file=True) # logger.warning('pdflatex return: %s', str(return_value)) mime_type = 'application/pdf' filename = r'{}.pdf'.format(tex_out) description = 'squared equation solution' parent_id = Solutions_folder f = GDriveUploadFile(filename=filename, description=description, mime_type=mime_type, parent_id=parent_id) return file_prefix.format(f['id'])