Ver Mensaje Individual
  #8 (permalink)  
Antiguo 08/12/2011, 07:30
Avatar de _cronos2
_cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 11 meses
Puntos: 310
Respuesta: Escribir en .docx

YUJUUUUUUUUU, al fin lo conseguí! Bueno en realidad lo conseguí ya el lunes, pero entre unas cosas y otras no he tenido tiempo para postearlo antes Al final tuve que pasar casi completamente de docx y hacerlo con lxml, que por cierto me encantó por lo sencillo y potente que es. Finalmente el código quedo así:
Código Python:
Ver original
  1. # -*- coding: utf-8 -*-
  2.  
  3. from docx import *
  4.  
  5. def gen_rid():
  6.     from random import shuffle
  7.     hex = list("0123456789ABCDEF")
  8.     shuffle(hex)
  9.     return ''.join( hex[0:8] )
  10.  
  11. def make_link(target, mode = 'External', text = ''):
  12.     hyperlink = etree.fromstring(
  13.         '''\
  14.         <w:p w:rsidR="{rid}" w:rsidRDefault="{rid}" xmlns:w="{url}">
  15.             <w:hyperlink>          
  16.                 <w:r w:rsidRPr="{rid}">
  17.                     <w:rPr>
  18.                         <w:rStyle w:val="Hipervnculo"/>
  19.                     </w:rPr>
  20.                     <w:t>{text}</w:t>
  21.                 </w:r>
  22.             </w:hyperlink>
  23.         </w:p>
  24.         '''.format(rid = rid, text = text, url = w)
  25.     )
  26.  
  27.     links.append({
  28.         'hyperlink' : hyperlink[0],
  29.         'target' : target,
  30.         'mode' : mode,
  31.         'text' : text      
  32.     })
  33.  
  34.     return hyperlink
  35.  
  36. def new():
  37.     d = etree.fromstring( '''<w:document xmlns:w="%s" xmlns:r="%s"></w:document>''' % (w, r) )
  38.     dbody = etree.SubElement( d, '{%s}body' % w)
  39.    
  40.     return d, dbody
  41.  
  42.  
  43. relationships, rid = relationshiplist(), gen_rid()
  44. links = []
  45. w, r = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
  46.  
  47. d, dbody = new()
  48. dbody.append( make_link('http://www.google.es', 'External', 'http://www.google.es') )
  49. # ...
  50. wordrelationships = wordrelationships(relationships, links)
Y tuve que cambiar el módulo docx:
Código Python:
Ver original
  1. def wordrelationships(relationshiplist, links = []):
  2.     '''Generate a Word relationships file'''
  3.     # Default list of relationships
  4.     # FIXME: using string hack instead of making element
  5.     #relationships = makeelement('Relationships',nsprefix='pr')
  6.     relationships = etree.fromstring(
  7.     '''<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>'''
  8.     )
  9.    
  10.     count = 1
  11.     for relationship in relationshiplist:
  12.         # Relationship IDs (rId) start at 1.
  13.         relationships.append(
  14.             makeelement('Relationship', attributes = {
  15.                 'Id' : 'rId' + str(count),
  16.                 'Type' : relationship[0],
  17.                 'Target' : relationship[1]
  18.             }, nsprefix = None)
  19.         )
  20.         count += 1
  21.  
  22. # A partir de aquí el código es mío
  23.     r = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' # nsprefix = 'r'
  24.     if links: # links != []    
  25.         for obj in links:
  26.             relationships.append(
  27.                 makeelement('Relationship', attributes = {
  28.                     'TargetMode' : obj['mode'],
  29.                     'Id' : 'rId' + str(count),
  30.                     'Type' : '%s/hyperlink' % r,
  31.                     'Target' : obj['target']
  32.                 }, nsprefix = None)
  33.             )
  34.            
  35.             hl = obj['hyperlink']
  36.             hl.set('{%s}id' % r, 'rId' + str(count))
  37.            
  38.             count += 1
  39.    
  40.     return relationships
para poder darle soporte a los hipervínculos. Lo único que no conseguí es que se vieran como links, de color azul, sino que se siguen viendo como texto plano, pero es lo de menos.
Espero que esto le sirva a alguien algún día
Saludos y gracias por todo :D
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red