OpenXML - powershell - trying to add shape - cannot insert the OpenXmlElement "newChild" because it is part of a tree

33 Views Asked by At

I am trying to find the simplest case of adding a paragraph to a slide in PPTX using the openXML and powershell core.

I keep hitting this error "Cannot insert the openXML element...because it is part of a tree"

Can anyone help? I have tried cloning objects - but the error keeps happening:



# Specify the PowerPoint file path  
$FilePath = "C:\temp\file2.pptx"  
  
# Create a PowerPoint document object  
$Document = [DocumentFormat.OpenXml.Packaging.PresentationDocument]::Open($FilePath, $false)  
  
# Get the first slide part  
$SlidePart = $Document.PresentationPart.SlideParts[0]  
  
# Create a new text box shape  
[DocumentFormat.OpenXml.Presentation.Shape]$TextBoxShape = $null

$TextBoxShape = [DocumentFormat.OpenXml.Presentation.Shape]::new()

$TextBoxShape.NonVisualShapeProperties = [DocumentFormat.OpenXml.Presentation.NonVisualShapeProperties]::new() 
$TextBoxShape.NonVisualShapeProperties.NonVisualDrawingProperties = [DocumentFormat.OpenXml.Drawing.NonVisualDrawingProperties]::new()
$val = [DocumentFormat.OpenXml.UInt32Value]::new(1)
$TextBoxShape.NonVisualShapeProperties.NonVisualDrawingProperties.Id = $val 
$TextBoxShape.NonVisualShapeProperties.NonVisualDrawingProperties.Name = "TextBox 1"  
$TextBoxShape.NonVisualShapeProperties.NonVisualDrawingProperties.Description = "TextBox"  
$TextBoxShape.NonVisualShapeProperties.ApplicationNonVisualDrawingProperties =[DocumentFormat.OpenXml.Presentation.ApplicationNonVisualDrawingProperties]::new()  
$TextBoxShape.ShapeProperties =[DocumentFormat.OpenXml.Presentation.ShapeProperties]::new()
$TextBoxSHape.ShapeStyle = [DocumentFormat.OpenXml.Presentation.ShapeStyle]::new()
$TextBoxShape.TextBody =[DocumentFormat.OpenXml.Drawing.TextBody]::new() 

$run = [DocumentFormat.OpenXml.Drawing.Run]::new()
$run.Text = "Hello World"
$TextBoxShape.TextBody.appendChild($run.CloneNode($true))
$SlidePart.slide.Shapetree.appendChild($TextBoxShape.CloneNode($true))
$Document.Close()  

It fails at the last point - when I try and add to the shapetree:


$SlidePart.slide.Shapetree.appendChild($TextBoxShape.CloneNode($false …
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Exception calling "AppendChild" with "1" argument(s): "Cannot insert the OpenXmlElement "newChild" because it is part of a tree. "

0

There are 0 best solutions below