Home > database >  Add an image to Word using PowerShell
Add an image to Word using PowerShell

Time:01-06

As stated in the Title, I would like to add an image into a Word document. Though my goal is to NOT use a path (stating where the image is located).

**Like this: **

$word = New-Object -ComObject Word.Application $word.visible = $true $document = $word.documents.Add() $selection = $word.selection $newInlineShape = $selection.InlineShapes.AddPicture($path)

But rather using some type of Base64String, so that this skript works with every device, regardless if the image path doesn't exist.

My attempt:

$word = New-Object -ComObject Word.Application $word.visible = $true

$document = $word.documents.Add() $selection = $word.selection

$base64ImageString = [Convert]::ToBase64String((Get-Content $path -encoding byte)) $imageBytes = [Convert]::FromBase64String($base64ImageString) $ms = New-Object IO.MemoryStream($imageBytes, 0, $imageBytes.Length) $ms.Write($imageBytes, 0, $imageBytes.Length); $alkanelogo = [System.Drawing.Image]::FromStream($ms, $true)

$pictureBox = new-object Windows.Forms.PictureBox $pictureBox.Width = $alkanelogo.Size.Width; $pictureBox.Height = $alkanelogo.Size.Height; $pictureBox.Location = New-Object System.Drawing.Size(153,223) $pictureBox.Image = $alkanelogo;

$newInlineShape = $selection.InlineShapes.AddPicture($pictureBox.Image)

Note: The variable "$path" is only here as a placeholder

CodePudding user response:

I've figured it out. I downloaded the image to my local computer, converted it to a base64 string and then back to an image. So that this script works with every user regardless of there path, I built in it to download the file to a specific path (that I created). Powershell will then extract the image from the path I created.

$filepath = 'C:\temp\image.png'
$folderpath = 'C:\temp\'

if([System.IO.File]::Exists($filepath -or $folderpath)){
    rmdir 'C:\temp\image.png'

    $b64 = "AAA..."


    $bytes = [Convert]::FromBase64String($b64)
    [IO.File]::WriteAllBytes($filepath, $bytes)
}else{ 
    mkdir 'C:\temp\' -ErrorAction SilentlyContinue

    $b64 = "AAA..."


    $bytes = [Convert]::FromBase64String($b64)
    [IO.File]::WriteAllBytes($filepath, $bytes)
}
  • Related