Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace text #128

Open
marcus-campos opened this issue Mar 25, 2023 · 0 comments
Open

Replace text #128

marcus-campos opened this issue Mar 25, 2023 · 0 comments

Comments

@marcus-campos
Copy link

Hello, congratulations for the work, the lib is amazing!

I'm trying to replace some text in an .odt file, but it replaces it in some places, but it doesn't replace the same text in other pages, could someone help me, please?

class ODFFiles:
    def prepare_files(self, template_path, user_data):
        variables = {
            "{{name}}": user_data.name,
            "{{document}}": user_data.document,
            "{{date}}": WrittenDates(
                date=user_data.created_at
            ).formated()
        }
        
        doc = opendocument.load(template_path)
    
        p_elements = doc.getElementsByType(text.P)
        span_elements = doc.getElementsByType(text.Span)
        
        for variable_key, variable_value in variables.items():
            self.__replace_text(p_elements, variable_key, variable_value)
            self.__replace_text(span_elements, variable_key, variable_value)
     
      def __replace_text(self, elements, old, new):
          for element in elements:
              extracted_text = teletype.extractText(element)
              
              if element.hasChildNodes():
                  self.__replace_text(element.childNodes, old, new)
  
              if extracted_text.find(old) != -1:
                  extracted_text = extracted_text.replace(old, new)
                  
                  new_element = None
                  
                  if element is text.Span:
                      new_element = text.Span()
                  elif text.P:
                      new_element = text.P()
                  else:
                      continue
                      
                  new_element.setAttribute('stylename', element.getAttribute('stylename'))
                  new_element.addText(extracted_text)
                  
                  element.parentNode.insertBefore(new_element, element)
                  element.parentNode.removeChild(element)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant