wordpress hit counter
Re: Search and replace in a presentation - PresentationML - Formats - OpenXML Developer

Re: Search and replace in a presentation

Formats

Discussions about working with different Open XML Formats

Search and replace in a presentation

  • rated by 0 users
  • This post has 1 Reply |
  • 1 Follower
  • I am using the following snippet--borrowed from this site, in fact--to traverse a presentation and fill in a template.  I am doing something wrong, however, as the saved file does not reflect the changes made.  Any ideas?

    It is as tho the StreamWriter does not actually write anything.

    Slide theSlide = slidePart.Slide;
    if (theSlide != null)
    {

      bool isFound = false;
      using (StreamReader sr = new StreamReader(slidePart.GetStream()))
      {
        docText = sr.ReadToEnd();
        if (docText.IndexOf(templateID) >= 0)
        {
          MessageBox.Show("Found "+templateID);
          isFound = true;
        }
      }

      Regex regexText = new Regex(templateID);
      docText = regexText.Replace(docText, templateValue);

      using (StreamWriter sw = new StreamWriter(slidePart.GetStream(FileMode.Create)))
      {
        if (docText.IndexOf(templateID) >= 0)
        {
          if (isFound)
            MessageBox.Show("Problem: still found " + templateID);
        }
        sw.Write(docText);
        isChanged = true;
      }
     
    }

  • Hi lwdallas

    The code you are using works for me

    However, it's not clever enough for text that may have become split.. Did the message box pop up with having "Found" occur? If it didn't it may be the case that your text has been separated in the Open XML of the presentation. If so, you may want to use a text value that you know is unique but doesn't contain grammer.

    You can test the code in debug, but if it's successfully running the regex change but doesn't persist the update to the file you should check you're doing the following.
    1) When you open the Presentation Document you need to set it as editable, like this:
    PresentationDocument.Open(docName, true)
    2) After your above code, you need to call the Save() method on the Presentation, like this:
    presentationDocument.PresentationPart.Presentation.Save();

    Hope this helps
Page 1 of 1 (2 items)