Powershell Word Document Page Numbers - powershell

$Doc = $Word.Documents.Add();
$Section = $Doc.Sections.Item(1);
$Header = $Section.Headers.Item(1);
$Header.Range.Text = "document1_${FirstName}_${SecondName}_${StaffID}.doc";
$objRange = $Doc.Range()
$objRange.Font.Name = “Arial”
$objRange.Font.Size = 12
$Doc.SaveAs("$fileserver\document1_${FirstName}_${SecondName}_${StaffID}.docx");
$Doc.Close();
I am using this script to create word documents and deploy them to staff areas on a fileserver. Is there a way to add page numbers into the documents?

The easiest way of doing this is as below:
$Word = New-Object -ComObject word.application
$word.Visible = $false
$Doc = $Word.Documents.Add()
$Section = $Doc.Sections.Item(1)
$Header = $Section.Headers.Item(1)
$Header.Range.Text = "document1_${FirstName}_${SecondName}_${StaffID}.docx"
$objRange = $Doc.Range()
$objRange.Font.Name = "Arial"
$objRange.Font.Size = 12
# ad a pagenumber (for demo centered to the page width)
# for other values see https://learn.microsoft.com/en-us/office/vba/api/word.wdpagenumberalignment
$wdAlignPageNumberCenter = 1
[void]$Section.Footers(1).PageNumbers.Add($wdAlignPageNumberCenter)
$Doc.SaveAs("$fileserver\document1_${FirstName}_${SecondName}_${StaffID}.docx")
$Doc.Close()
# IMPORTANT Cleanup COM objects after use
$Word.Quit()
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($objRange)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Section)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Header)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Word)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

Related

Add an image to Word using PowerShell

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
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)
}

Powershell Word Document Formatting

I am using this Code to create a Word Doucment, Name it and Save it to a user area on a fileserver for a large cohort of people.
I have had a look online and found a few ways to incorporate formatting, does anyone have a simple method of trying to add;
Font Size
Font
Line Spacing
I believe the Font/Font Size is fairly straight forward, but the linespacing might be a bit more complex!
If anyone has any ideas, please let me know! Thank you in advance, have a good day
$Word.Visible = $false;
$Doc = $Word.Documents.Add();
$Section = $Doc.Sections.Item(1);
$Header = $Section.Headers.Item(1);
$Header.Range.Text = "$FirstName $SecondName $ID Activity 1";
$Doc.SaveAs("$fileserver\${date}${time}-${FourID}\Desktop\activity 1_${ID}_${FirstName}_${SecondName}.docx");
$Word.Quit()```
Try:
$Word = New-Object -ComObject Word.Application
$Word.Visible = $false;
$Doc = $Word.Documents.Add();
$Section = $Doc.Sections.Item(1);
$Header = $Section.Headers.Item(1);
$Header.Range.Text = "$FirstName $SecondName $ID Activity 1";
$objRange = $Doc.Range()
$objRange.Font.Name = “Arial”
$objRange.Font.Size = 10
$objRange.Font.Spacing = 1.0
$objRange.ParagraphFormat.LineSpacing = 1
$Doc.SaveAs("$fileserver\${date}${time}-${FourID}\Desktop\activity 1_${ID}_${FirstName}_${SecondName}.docx");
$Word.Quit()
This worked for me.

replace a string with an hyperlink in a file Word powershell

i want to replace a string with an hyperlink
i try with something like this
Update:
$FindText = "[E-mail]"
$email ="asdadasd#asdada.com"
$a=$objSelection.Find.Execute($FindText)
$newaddress = $objSelection.Hyperlinks.Add($objSelection.Range,$email) )
but this insert the email at beginnig of file word don't replace the string "[E-mail]"
Add-Type -AssemblyName "Microsoft.Office.Interop.Word"
$wdunits = "Microsoft.Office.Interop.Word.wdunits" -as [type]
$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $false
$findText = "[E-mail]"
$emailAddress = "someemail#example.com"
$mailTo = "mailto:"+$emailAddress
$objDoc = $objWord.Documents.Open("Path\to\input.docx")
$saveAs = "Path\to\output.docx")
$range = $objDoc.Content
$null = $range.movestart($wdunits::wdword,$range.start)
$objSelection = $objWord.Selection
$matchCase = $false
$matchWholeWord = $true
$matchWildcards = $false
$matchSoundsLike = $false
$matchAllWordForms = $false
$forward = $true
$wrap = 1
$format = $False
$wdReplaceNone = 0
$wdFindContinue = 1
$wdReplaceAll = 2
$wordFound = $range.find.execute($findText,$matchCase,$matchWholeWord,$matchWildCards,$matchSoundsLike,$matchAllWordForms,$forward,$wrap)
if($wordFound)
{
if ($range.style.namelocal -eq "normal")
{
$null = $objDoc.Hyperlinks.Add($range,$mailTo,$null,$null,$emailAddress)
}
}
$objDoc.SaveAs($saveAs)
$objDoc.Close()
$objWord.Quit()
Remove-Variable -Name objWord
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
Kinda ugly, but this script will do what you need. It loads the .docx specified with $objDoc, finds all instances of $findText, and replaces it with a mailto link for $emailAddress and then saves the changes to $saveAs.
Most of this based on a "Hey, Scripting Guy" Article

Find and replace in Text Box in Header of Word Doc using Powershell

I am trying to use Powershell to do a find and replace of some text within a Text Box that is within the Header of a Word Document (.docx). I was able to get it working for text outside of the Header but not that within. I think it is failing because I am not correctly accessing the contents of the Text Box, so I added in the final line (before quit and save) to see what the text was but it printed out blank for each of the three Items in my Header. This is my first time using Powershell and I think I have perhaps spent more time learning this and writing it than I will save by using it...
The relevant snippet of the script is below:
$word = New-Object -COM "Word.Application";
$word.Visible = $false;
$doc = $word.Documents.Open($FullPath);
$selection = $word.Selection;
$section = $doc.sections.item(1);
$header = $section.headers.Item(3);
$FindText = "Cnnn";
$MatchCase = $False;
$MatchWholeWord = $False;
$MatchWildcards = $False;
$MatchSoundsLike = $False;
$MatchAllWordForms = $False;
$Forward = $True;
$wdFindContinue = 1;
$Wrap = $wdFindContinue;
$Format = $False;
$wdReplaceNone = 0;
$ReplaceAll = 2;
$ReplaceWith = "C" + $newString;
$a = $header.Find.Execute($FindText,$MatchCase,$MatchWholeWord, `
$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
$Wrap,$Format,$ReplaceWith, $ReplaceAll);
Write-Host ("Header is: " + $header.Text);
$doc.Save();
$word.Quit();
You need to apply your search to the .TextFrame.TextRange.Find object from the TextBox or any shape containing text.
You could try something like this:
If ($header.ShapeRange.Count) {
ForEach ($shp in $header.ShapeRange) {
If ($shp.TextFrame.HasText) {
$obj = $shp.TextFrame.TextRange.Find
$a = $obj.Execute($FindText,$MatchCase,$MatchWholeWord,`
$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
$Wrap,$Format,$ReplaceWith,$ReplaceAll)
}
}
}

How can I change font spacing and footer formatting in a word document with Powershell?

$Word = New-Object -ComObject Word.Application;
$Word.Visible = $true;
$Doc = $Word.Documents.Add();
$Section = $Doc.Sections.Item(1);
$Header = $Section.Headers.Item(1);
$Footer = $Section.Footers.Item(1);
$Footer.PageNumbers.Add($wdAlignPageNumberCenter);
$Header.Range.Text = "abcd";
$selection.Font.Name="Courier New";
$selection.Font.Size=11;
**$selection.Font.Spacing=1.0;**
$selection=$word.Selection;
Even though I specified my font spacing as 1.0, it is taking a default value and it seems that this is not working. Do I need to make any changes?
Also, this displays the page number in the footer column i.e. 1 or 2 or 3 like this but I want it to be like Page 1, Page 2 ,Page 3. How do I do that?
ok i have a temporary solution after some groundwork for displaying page 1,page 2 ,page 3
$page="`tPage";
$Word = New-Object -ComObject Word.Application;
$Word.Visible = $true;
$Doc = $Word.Documents.Add();
$Section = $Doc.Sections.Item(1);
$Footer = $Section.Footers.Item(1);
$Footer.Range.Text=$page;
$Footer.PageNumbers.Add($wdAlignPageNumberCenter);