def setUp(self): root = os.path.dirname(__file__) impl = getDOMImplementation() template = os.path.join(root, 'simple_template.odt') self.document = impl.createDocument(None, "some_tag", None) self.engine = Renderer() self.engine.render(template)
def test_secr(): gr = find_all_groups() engine = Renderer() template = open('app/groups/templates/template.odt', 'rb') eng = engine.render(template, image='app/groups/writer.png', stroki=gr) #eng возвращает двоичный объект - заполненный шаблон response = make_response(eng) response.headers['Content-Type'] = 'application/vnd.oasis.opendocument.text' response.headers['Content-Disposition'] = \ 'attachment; filename=testfile.odt' return response
def from_template(template, context): """ Generates odt file template - string path to odt template context - context variables like in Jinja2 """ engine = Renderer() result = engine.render(template, context=context) return result
def render_document(self, t_file, context): """ Render template with given context Args: t_file: template file context: (dict) template variables Returns: (str) downloaded file """ engine = Renderer() rendered = engine.render(t_file, **context) return "%s%s" % (S3_PUBLIC_URL, self.save_document(rendered))
def post(self, request, uid): template_file = os.path.join(ODT_TEMPLATES_PATH, 'hunting_ticket.odt') result_file = os.path.join(MEDIA_ROOT, f'{str(uuid.uuid4())}.odt') # renderer = Renderer(template_file, request.data, result_file) # renderer.run() engine = Renderer() result = engine.render(template_file, **request.data) output = open(result_file, 'wb') output.write(result) return Response({'path': result_file})
def remplir_template(self): ## from odf.opendocument import OpenDocumentText ## self.setNomFichierODF(nom_fichier) ## textdoc = OpenDocumentText() ## self.setHandleFichierODF(textdoc) ## return textdoc from secretary import Renderer engine = Renderer() result = engine.renderer(self.getNomFichierTemplate(), Auditeur=self.getVariableEnglobante()) output = open(self.getNomFichierDestination(), 'wb') output.write(result) output.close()
def create_report(template, report, filename="report.odt"): from secretary import Renderer engine = Renderer() result = engine.render(template, report=report) import tempfile with tempfile.NamedTemporaryFile() as output: output.write(result) output.flush() from django.http import FileResponse response = FileResponse(open(output.name, 'rb'), as_attachment=True, filename=filename) return response
def __init__(self, template=None, context=None): """ Şablon ve şablon içinde kullanılacak değişkenler Usage: t = TRenderer(template=f, context={"name": "Cem",}) rendered_doc = t.render_document Args: template (file): file or file like object context (dict): context variables """ self.template = template self.context = context self.engine = Renderer()
def render(self, context): """Render the document using secretary.""" engine = Renderer() engine.environment.filters['format_date'] = format_date engine.environment.filters['format_datetime'] = format_datetime result = engine.render(self.template, **context) response = HttpResponse( content_type='application/vnd.oasis.opendocument.text; charset=UTF-8' ) response['Content-Disposition'] = 'inline; filename=' + self.filename with tempfile.NamedTemporaryFile() as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) return response
def create_odt(self, first, filename): print("creating odt") odt_path = os.path.join(os.path.relpath("MyPatterns"), self.file_base + "_pattern.odt") foldsArr = [] for column in range(0, self.temp.size[0]): # add first page to get the correct page number, double for sheets instead of pages pagenum = column * 2 + first if column in self.final_pattern: # make the number a float with double precision, like 10.15 upper_corner = self.final_pattern[column][0] / 100.0 lower_corner = self.final_pattern[column][1] / 100.0 if SINGLE_PRECISION == True: upper_corner = ('%.1f' % round(upper_corner, 1)).rjust(7) lower_corner = ('%.1f' % round(lower_corner, 1)).rjust(7) else: upper_corner = ('%.2f' % upper_corner).rjust(6) lower_corner = ('%.2f' % lower_corner).rjust(6) foldsArr.append({ "pagenum": str(pagenum).rjust(6), "top": upper_corner, "bottom": lower_corner }) #else: #foldsArr.append({"pagenum": "4", "top": "", "bottom": ""}) engine = Renderer(media_path='.') template = open('template.odt', 'rb') output = open(odt_path, 'wb') output.write( engine.render(template, TITLE=self.file_base, image=os.path.join(os.path.relpath("MyPatterns"), self.file_base + "_sheets.png"), image_orig=os.path.join( os.path.relpath("MyPictures"), filename), folds=foldsArr))
def create_report(data): engine = Renderer() root = os.path.dirname(__file__) document = root + '/templates/bedjango/template.odt' DIRECTORY = root + '/templates/bedjango/tmp/' result = engine.render(document, data=data) tempfile.tempdir = DIRECTORY response = HttpResponse( content_type= 'application/vnd.oasis.opendocument.text; charset=UTF-8') response[ 'Content-Disposition'] = 'inline; filename=report_on_complaint_{}.odt'.format( now.strftime('%d%m%Y')) with tempfile.NamedTemporaryFile(delete=False) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) clear_folder(DIRECTORY) return response
def _open_template(self, template: TemplateModel, file_format=None) -> None: ''' Opens a template for document manipulation. The ´file_format´ argument is optional. ''' template_name = template.file if file_format: self.file_format = file_format else: templates = self._list_files( files_path=f'{self.pwd}/{self._templates_path}/{template_name}', file_formats=self.SUPPORTED_INPUT_FORMATS) template = templates[0] self.file_format = template.split('.')[-1] del templates, template self.template_name = template_name self.path = f'{self.pwd}/{self._templates_path}/{template_name}/{template_name}.{self.file_format}' if (self.file_format in self.ODF_FORMATS): # using relatorio # self._file = Template(source='', filepath=self.path) # using secretary self._file = Renderer() elif (self.file_format in self.OFFICE_FORMATS): self._file = DocxTemplate(self.path) else: raise TypeError( 'The file format is invalid or it is not supported.') try: self.info_path = f'{self.pwd}/{self._templates_path}/{template_name}/{template_name}.json' with open(self.info_path, 'r') as f: self.info = json.load(f) except Exception as e: raise e
def render_template(self, template_file: str, rendered_file: str, values: Dict[str, Any], pdf: bool): logging.info( f"Rendering template {template_file} into {rendered_file} (PDF = {pdf})..." ) engine = Renderer() result = engine.render(template_file, **values) with open(rendered_file, "wb") as outf: outf.write(result) if pdf: soffice = self.get_soffice() saved_dir = os.getcwd() os.chdir(os.path.dirname(rendered_file)) cmd = f"{soffice} --headless --convert-to pdf '{os.path.basename(rendered_file)}'" out = subprocess.run([ soffice, "--headless", "--convert-to", "pdf", os.path.basename(rendered_file), ]) os.chdir(saved_dir) os.unlink(rendered_file)
def renderx(x,user,projectname,data): root = os.path.dirname(__file__) base = os.path.join(root,'./static/users/%s/%s/' %(user,projectname)) jdata = os.path.join(base,'./json/data.json') # try: # r = requests.get(jsonpath) # addr = json.loads(r.text) # except : # return -1 template = os.path.join(base, './odt/'+x) engine = Renderer() engine.environment.filters['fnbarcode'] = fnbarcode result = engine.render(template,data=data) outf = os.path.join(base,'./out/') templatename = str(random.uniform(0,100))+x fname = os.path.join(outf,templatename) data = [] data.append(base) data.append(fname) data.append(templatename) output = open(fname, 'wb') output.write(result) return data
class MixinReport(): """ Использует для рендера шаблонов С использование библиотеки secretary """ __engine = Renderer() template_name = '' # Имя шаблона для рендера context = {} # Данные # renderers def __renders(self): template = os.path.join(settings.BASE_DIR, 'static', self.template_name) result = self.__engine.render(template, **self.context) return result def get_report(self): """ Возваращет готовый шаблон """ response = HttpResponse(content_type='application/odt', content=self.__renders()) response['Content-Disposition'] = 'attachment; filename="renders.odt"' return response
# /usr/bin/activate import os import sys sys.path.insert(0, os.path.abspath(os.path.join(__file__, '../../..'))) from secretary import Renderer if __name__ == '__main__': engine = Renderer(media_path='.') template = open('template.odt', 'rb') output = open('output.odt', 'wb') output.write(engine.render(template, image='writer.png')) print("Template rendering finished! Check output.odt file.")
def test(): engine = Renderer() print "hello"
def execute(self, parameters, messages): """The source code of the tool.""" arcpy.ImportToolbox(os.path.join(os.path.dirname(__file__), "URB.pyt")) arcpy.gp.toolbox = os.path.join(os.path.dirname(__file__), "URB.pyt") # Local variables: contesto = parameters[0].valueAsText coordinate_catastali = parameters[1].valueAsText protocollo_numero = parameters[2].valueAsText protocollo_data = parameters[3].valueAsText richiedente = parameters[4].valueAsText odt_target = parameters[5].valueAsText #json = "" poligono = "" output_json = "" #facoltativo #output_testo_PI = "" #output_json__2_ = "" #output_testo_PAT = "" test = False PI_test = ''' [ {"note": null, "articolo": 0, "layer": 0, "definizione": "Area totale", "nome": "Area totale", "url": "", "gruppo": "cdu", "area": 3978.322295527004, "interno_pe": 0}, {"layer": 39, "definizione": "Area interessata da vincolo aeroportuale disciplinato dalla L. 4 febbraio 1963 n.58", "nome": "Perimetro ricognitivo aeroportuale", "url": "http://www.padovanet.it/allegati/C_1_Allegati_15388_Allegato_0.pdf", "gruppo": "perimetri", "area": 2974.954930029389, "note": null, "articolo": "", "interno_pe": null}, {"layer": 39, "definizione": "Area interessata da vincolo aeroportuale disciplinato dalla L. 4 febbraio 1963 n.58", "nome": "Perimetro ricognitivo aeroportuale", "url": "http://www.padovanet.it/allegati/C_1_Allegati_15388_Allegato_0.pdf", "gruppo": "perimetri", "area": 2974.954930029389, "note": null, "articolo": "", "interno_pe": null}, {"layer": 56, "definizione": "Zona di degrado %", "nome": "Perimetro zone di degrado", "url": "http://www.padovanet.it/allegati/C_1_Allegati_15388_Allegato_0.pdf#92", "gruppo": "centro_storico", "area": 1003.3676370044367, "note": null, "articolo": 41, "interno_pe": 0}, {"layer": 39, "definizione": "Area interessata da vincolo aeroportuale disciplinato dalla L. 4 febbraio 1963 n.58", "nome": "Perimetro ricognitivo aeroportuale", "url": "http://www.padovanet.it/allegati/C_1_Allegati_15388_Allegato_0.pdf", "gruppo": "perimetri", "area": 1003.3676370044367, "note": null, "articolo": "", "interno_pe": null}, {"layer": 39, "definizione": "Area interessata da vincolo aeroportuale disciplinato dalla L. 4 febbraio 1963 n.58", "nome": "Perimetro ricognitivo aeroportuale", "url": "http://www.padovanet.it/allegati/C_1_Allegati_15388_Allegato_0.pdf", "gruppo": "perimetri", "area": 1003.3676370044367, "note": null, "articolo": "", "interno_pe": null}, {"note": null, "articolo": "999.999", "layer": 999, "definizione": "Viabilità", "nome": "Area non zonizzata", "url": "", "gruppo": "cdu", "area": 3978.322295527004, "interno_pe": 0}] ''' CS_test = u''' [{"norma1": "UNITA' DI PIANO DELLA CLASSE E MODALITA' DI TIPO E - RISTRUTTURAZIONE EDILIZIA", "area": 3953.5930837093556, "despro1": "RESIDENZIALE, COMMERCIALE, DIREZIONALE, TURISTICA E ARTIGIANALE", "full_id": "0026500014", "despro": " "}] ''' PAT_test = u''' [ {"nta": 5.1, "layer": "b0101011_vincolo", "fc": "SIT.b0101011_Vincolo_r", "desc": "Vincolo sui beni culturali (D.Lgs. 42/2004, artt.10 e 12)"}, {"nta": "5.6.12", "layer": "b0105021_fascerispetto", "fc": "SIT.b0105021_FasceRispetto_r", "desc": "Servitù o Fasce di rispetto aeroportuale"}, {"nta": "5.5.1", "layer": "b0104011_centrostorico", "fc": "SIT.b0104011_CentroStorico_r", "desc": "Centro Storico (P.R.G., P.T.C.P. art.26 A N.T., P.T.R.C. art.24 N.T.)"}, {"nta": "5.6.8.1", "layer": "b0105051_centriabitati", "fc": "SIT.b0105051_CentriAbitati_r", "desc": "Centri Abitati"} ] ''' arcpy.ImportToolbox(os.path.join(os.path.dirname(__file__), "URB.pyt")) arcpy.gp.toolbox = os.path.join(os.path.dirname(__file__), "URB.pyt") if test: identificazione = "TEST" PI_def = json.loads(PI_test) CS_def = json.loads(CS_test) PAT_def = json.loads(PAT_test) arcpy.AddMessage(str(PAT_def)) for item in PAT_def: arcpy.AddMessage(item['desc']) else: poligono = contesto identificazione = "" if coordinate_catastali: CC_result = arcpy.gp.CC2FCtool(coordinate_catastali) arcpy.AddMessage("CC_result: %s" % CC_result.getOutput(0)) poligono = CC_result.getOutput(0) identificazione = u"così individuata nel Catasto Terreni: %s" % decodificaCatasto( coordinate_catastali) else: if not contesto: arcpy.AddError( "Deve essere specificato almeno un contesto, come layer o come coordinate catastali" ) exit(0) poligono = contesto # Process: CDU_PI PI_result = arcpy.gp.CDUPItool(poligono, output_json) arcpy.AddMessage("PI_result: %s" % PI_result.getOutput(0)) PI_def = json.loads(PI_result.getOutput(0)) checkInCS = False for defin in PI_def: if defin["layer"] == 55: checkInCS = True if checkInCS: # Process: CDU_CS CS_result = arcpy.gp.CDUCStool(poligono, output_json) arcpy.AddMessage("CS_result: %s" % CS_result.getOutput(0)) CS_def = json.loads(CS_result.getOutput(0)) else: CS_def = [] # Process: CDU_PAT PAT_result = arcpy.gp.CDUPATtool(poligono, output_json) arcpy.AddMessage("PAT_result: %s" % PAT_result.getOutput(0)) PAT_def = json.loads(PAT_result.getOutput(0)) PI_desc = '' PI_nta = '' dest_selection = [] for item in PI_def: arcpy.AddMessage("item: %s" % str(item)) if item["layer"] != 0 and not item["layer"] in dest_selection: dest_selection.append(item["layer"]) if '%' in item["definizione"]: definizione = item["definizione"].replace( '%', unicode(item["note"] or "")) else: definizione = item["definizione"] PI_desc += '%s, ' % definizione.upper() PI_nta += '%s, ' % str(item["articolo"]).upper() PI_desc = PI_desc[:-2] + "; " PI_nta = PI_nta[:-2] + "; " CS_udp = '' dest_selection = [] for item in CS_def: if not item["norma1"] + item["despro1"] in dest_selection: dest_selection.append(item["norma1"] + item["despro1"]) CS_udp += '%s con destinazione %s, ' % (item['norma1'], item["despro1"]) CS_udp = CS_udp[:-2] + "; " PAT_desc = '' PAT_nta = '' dest_selection = [] for item in PAT_def: arcpy.AddMessage("dest_selection: %s" % str(dest_selection)) if not item["desc"] in dest_selection: dest_selection.append(item["desc"]) PAT_desc += '%s, ' % item["desc"].upper() PAT_nta += '%s, ' % str(item["nta"]).upper() PAT_desc = PAT_desc[:-2] + "; " PAT_nta = PAT_nta[:-2] + "; " params = { "protocollo": { "numero": str(protocollo_numero), "data": str(protocollo_data) }, "richiedente": richiedente, "pi": { "desc": PI_desc, "nta": PI_nta }, "cs": CS_udp, "pat": { "desc": PAT_desc, "nta": PAT_nta }, } arcpy.AddMessage("PARAMS: %s" % str(params)) engine = Renderer() template2 = os.path.join(os.path.dirname(__file__), "SOMMARIO_template.odt") result2 = engine.render(template2, PI_def=PI_def, CS_def=CS_def, PAT_def=PAT_def) #sommario_target = os.path.join(tempfile.mkdtemp(),"sommario.odt") sommario_target = get_jobfile("output", "odt") with open(sommario_target, 'wb') as output: output.write(result2) output.flush() arcpy.AddMessage("SOMMARIO DESTINAZIONI: %s" % sommario_target) if not odt_target: #odt_target = os.path.join(tempfile.mkdtemp(),"CDU.odt") odt_target = get_jobfile("output", "odt") template1 = os.path.join(os.path.dirname(__file__), "CDU_template.odt") result1 = engine.render(template1, **params) with open(odt_target, 'wb') as output: output.write(result1) output.flush() arcpy.AddMessage("SOMMARIO DESTINAZIONI: %s" % odt_target) parameters[5].value = odt_target
from secretary import Renderer import barcode import os root = os.path.dirname(__file__) temp = os.path.join(root, './static/test_template2.odt') imgpath = "" engine = Renderer() # Configure custom application filters def square(barcod): ean = barcode.get('ean13', barcod) global imgpath imgpath = ean.save('image') # if imgpath: # print 'imgpath'-imgpath # engine.environment.filters['square'] = square # result = engine.render(temp,x=imgpath) # output = open('rendered_document.odt', 'wb') # output.write(result) # import os # import json # from secretary import Renderer # import requests # import barcode # from barcode.writer import ImageWriter # def fnbarcode(barcod):
def executeProcess(self, folder): pto = self.fetchOne(folder.name) # print(pto) pto['dataMono'] = date.today().strftime('%d/%m/%Y') # Necessário para diminuir o tamanho dos campo no modelo: pto['freq'] = pto['freq_processada'] pto['mc'] = pto['meridiano_central'] pto['mascara'] = pto['mascara_elevacao'] pto['taxa'] = pto['taxa_gravacao'] pto['sigmaXY'] = pto['precisao_horizontal_esperada'] pto['sigmaZ'] = pto['precisao_vertical_esperada'] pto['m'] = 'Sim' if pto['materializado'] else 'Não' # por algum bug no odt/secretary não dá pra replicar imagem (no caso a assinatura, que está no rodapé) pto['signature'] = self.settings['signature'] pto['signature1'] = self.settings['signature'] pto['signature2'] = self.settings['signature'] pto['altitude_ortometrica'] = '{:.2f}'.format( pto['altitude_ortometrica']) pto['altitude_geometrica'] = '{:.2f}'.format( pto['altitude_geometrica']) pto['durRast'] = pto["fim_rastreio"] - pto["inicio_rastreio"] pto['photoCGEO'] = self.settings['pathImageCGEO'] try: pto['inicio_rastreio'] = pto['inicio_rastreio'].strftime( '%d/%m/%Y %H:%M:%S') pto['data_processamento'] = pto['data_processamento'].strftime( '%d/%m/%Y') except AttributeError: pass # Fotos do ponto photosPt = [ str(f) for f in Path(folder / '3_Foto_Rastreio').iterdir() if f.suffix in self.img_extensions ] for _idx in range(len(photosPt)): pto[f'photoPt{_idx + 1}'] = photosPt[_idx] # Não esquecer que as visões aéreas tem que ser geradas! pto['photoCroqui'] = [ str(f) for f in Path(folder / '4_Croqui').iterdir() if f.match('*.jpg') ][0] pto['photoAerView'] = str( Path(folder / '7_Imagens_Monografia' / f'{pto["cod_ponto"]}_AEREA.jpg')) pto['photoView1'] = str( Path(folder / '7_Imagens_Monografia' / f'{pto["cod_ponto"]}_MUNICIPIO.jpg')) pto['photoView2'] = str( Path(folder / '7_Imagens_Monografia' / f'{pto["cod_ponto"]}_ESTADO.jpg')) # pto['photoAerView'] = [str(f) for f in Path(self.settings['photoAerView']).iterdir() if f.match('{}*.jpg'.format(pto['cod_ponto']))][0] # pto['photoView1'] = [str(f) for f in Path(self.settings['photoView1']).iterdir() if f.match('{}*.jpg'.format(pto['cod_ponto']))][0] # pto['photoView2'] = [str(f) for f in Path(self.settings['photoView2']).iterdir() if f.match('{}*.jpg'.format(pto['cod_ponto']))][0] engine = Renderer() # Path do template result = engine.render(template='../modelo.odt', pto=pto) with open(folder / '{}.odt'.format(pto['cod_ponto']), 'wb') as output: output.write(result) # Gera o pdf _path_odt = str(Path(folder / pto['cod_ponto'])) subprocess.run([ f"{self.settings['pathLibreOffice']}", "--headless", "--convert-to", "pdf", f"{_path_odt}.odt" ]) # Transfere o pdf para a estrutura de pastas e deleta o odt Path.mkdir(folder / '8_Monografia', exist_ok=True) Path.replace( Path.cwd() / '{}.pdf'.format(pto['cod_ponto']), Path(folder / '8_Monografia' / '{}.pdf'.format(pto['cod_ponto']))) Path.unlink(Path(folder / '{}.odt'.format(pto['cod_ponto']))) print(f'Monografia do ponto {pto["cod_ponto"]} concluída.')