Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a MS Word document in PowerShell and set the paragraph/line spacing to none?

I am looking to create a PowerShell script that will generate a Word document. It works as expected but when I run the script there is a space or a line break between "My Document: Title" and "Date: 01-07-2014". The result looks like this:

My Document: Title

Date: 01-07-2014

I want it to look like this:

My Document: Title
Date: 01-07-2014

How can I write into this script a way to remove spaces within paragraphs? What I mean is, I want to set the paragraph spacing to single in PowerShell (not in Word as a default) By the way, if i do not add the $selection.TypeParagraph() before the "Date: $date", the result looks like this:

My Document: TitleDate: 01-07-2014

As in, there is no carriage return at all. The goal is to have one carriage return but no space after that carriage return. Here is the script.

$date = get-date -format MM-dd-yyyy
$filePath = "C:\users\myuser\file"

[ref]$SaveFormat = "microsoft.office.interop.word.WdSaveFormat" -as [type]
$word = New-Object -ComObject word.application
$word.visible = $true
$doc = $word.documents.add()

$selection = $word.selection
$selection.font.size = 14
$selection.font.bold = 1
$selection.typeText("My Document: Title")

$selection.TypeParagraph()
$selection.font.size = 11
$selection.typeText("Date: $date")

$doc.saveas([ref] $filePath, [ref]$saveFormat::wdFormatDocument)
like image 405
Mike J Avatar asked Feb 15 '23 04:02

Mike J


1 Answers

I think what you want is to change the Paragraph style from "Normal" to "No Spacing".

The start of your code is the same:

$date = get-date -format MM-dd-yyyy
$filePath = "C:\users\myuser\file"

[ref]$SaveFormat = "microsoft.office.interop.word.WdSaveFormat" -as [type]
$word = New-Object -ComObject word.application
$word.visible = $true
$doc = $word.documents.add()

Then you want to change the paragraph style to "No Spacing"

$selection = $word.selection
$selection.WholeStory
$selection.Style = "No Spacing"

And then you can carry on with the rest of your code:

$selection.font.size = 14
$selection.font.bold = 1
$selection.typeText("My Document: Title")

$selection.TypeParagraph()
$selection.font.size = 11
$selection.typeText("Date: $date")

$doc.saveas([ref] $filePath, [ref]$saveFormat::wdFormatDocument)
like image 192
HAL9256 Avatar answered May 12 '23 07:05

HAL9256