iTextSharp text file to powershell in Landscape - powershell

I'm trying to convert a text file to PDF using powershell in landscape.
Currently using a iTextSharp that has got me to great place with text conversion to PDF however I'm not able to find anything to place it in landscape when the lines are added to create the PDF.
Here is what I'm currently using.
[System.Reflection.Assembly]::LoadFrom("I:\powershell\itextsharp.dll")
$doc = New-Object itextsharp.text.document
$stream = [IO.File]::OpenWrite("I:\powershell\test.pdf")
$writer = [itextsharp.text.pdf.PdfWriter]::GetInstance($doc, $stream)
$doc.Open()
[IO.File]::ReadAllLines("I:\powershell\test.txt") | foreach {
$line = New-Object itextsharp.text.Paragraph($_)
$doc.Add($line)
}
$doc.Close()
$stream.Close()
I have found some for C# and Java just nothing with powershell.
Tried this which did not work:
$doc = New-Object iTextSharp.text.Document([iTextSharp.text.PageSize]::LEGAL_LANDSCAPE)
Thank you so much.
D

Use the overloaded constructor that takes a Rectangle, which explicitly sets the page size:
$doc = New-Object itextsharp.text.document(New-Object itextsharp.text.Rectangle(792, 612));

Related

How add autocorrect entries with an hyperlink using powershell script

In MS Outlook, is there a way to automatically replace some words like Google, MSN, Facebook, etc (I have an exhausting list in a CSV file), by the hyperlink that redirects to correct website.
So basically when I type google it transforms it to a hyperlink.
My CSV file:
Word, URL
Facebook, https://facebook.com
MSN, https://msn.com
Google, https://google.com
What I have so far is a script that add to the object autocorrect entries a word and replaces it by another word not using a CSV but a word document. But I'm not able to replace it by an hyperlink. It causes an error saying that autocorrect entries accept only string format and not object (hyperlink).
Reference: Add formatted text to Word autocorrect via PowerShell
When I create manually via outlook an hyperlink and I add this hyperlink to autocorrect and I run the following PowerShell script I can't find this autocorrect entry:
(New-Object -ComObject word.application).AutoCorrect.Entries | where{$_.Value -like "*http*"}
I want to adapt this code coming from Use PowerShell to Add Bulk AutoCorrect Entries to Word
If someone has an idea on how to add a hyperlink to the autocorrect entries, I would be grateful.
Thanks!
I finally managed how to add autocorrect entries for both word and outlook.
I need to create a .docx file with 'X row' and '2 Columns', the first column contain the word that i want an autocorrect like 'google' and the second column the 'google' link.
$objWord = New-Object -Com Word.Application
$filename = 'C:\Users\id097109\Downloads\test3.docx'
$objDocument = $objWord.Documents.Open($filename)
$LETable = $objDocument.Tables.Item(1)
$LETableCols = $LETable.Columns.Count
$LETableRows = $LETable.Rows.Count
$entries = $objWord.AutoCorrect.entries
for($r=1; $r -le $LETableRows; $r++) {
$replace = $LETable.Cell($r,1).Range.Text
$replace = $replace.Substring(0,$replace.Length-2)
$withRange = $LETable.Cell($r,2).Range
$withRange.End = $withRange.End -1
# $with = $withRange.Text
Try {
$entries.AddRichText($replace, $withRange) | out-null
}
Catch [system.exception] {
Write-Host $_.Exception.ToString()
}
}
$objDocument.Close()
$objWord.Quit()
[gc]::collect()
[gc]::WaitForPendingFinalizers()
$rc = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($objWord)
This code allow to modify the file Normal.dotm that contains all the autocorrect to an object link (C:\Users{your user id}\AppData\Roaming\Microsoft\Templates)
But then to apply those change to Outlook you have delete the 'NormalEmail.dotm' and the copy/paste 'Normal.dotm' and the rename it to 'NormalEmail.dotm'
This is the script to avoid to do it manually :
$FileName='C:\Users\{your id}\AppData\Roaming\Microsoft\Templates\Normal.dotm'
$SaveTo='C:\Users\{your id}\AppData\Roaming\Microsoft\Templates\NormalEmail.dotm'
Remove-Item –path $SaveTo
$Word = New-Object –ComObject Word.Application
$Document=$Word.Documents.Open($Filename)
$Document.SaveAs($SaveTo)
$Document.Close

How Do I Remove An Existing Word Doc Watermark With Powershell? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need to use PowerShell to remove a watermark from an existing Word doc. I'm attempting to convert the results of the Word macro recorder to PowerShell but am getting a "[System.__ComObject] doesn't contain a method named 'Shapes'" error. Any help is appreciated. The PS code is below.
$Word=New-Object -ComObject "Word.Application"
$wdSeekPrimaryHeader = 1
$Doc=$Word.Documents.Open("C:\Users\mynamehere\Downloads\andSuch\SampleDoc1.docx")
$Selection=$Word.Selection
$Doc.ActiveWindow.ActivePane.View.SeekView=$wdSeekPrimaryHeader
$Selection.HeaderFooter.Shapes("PowerPlusWaterMarkObject357476642").Select
$Selection.ShapeRange.Delete
$Doc.Save()
$Doc.Close()
$Word.Quit()
Show your code?
A simple search for your use case 'PowerShell and Microsoft word remove watermark' would give you a list, and even full scripts for exactly what you are after. For example, this one is about adding a Watermark. Of course removing is, you'd reverse the logic.
How to Watermark Word Documents with PowerShell
#Relevant files
$File = $args[0]
$WM = $args[1]
#Open document in Word
$Word = New-Object -ComObject Word.Application
$Word.Visible = $False
$Doc = $Word.Documents.Open($File)
#Insert Watermark
Function Watermark
{
#Create rectangle
$Shape = $args[0].Shapes.AddShape(1,0, 0, 500, 125)
#Fill rectanlge with watermark image
$PicFill = $Shape.Fill.UserPicture($args[1])
#Hide rectangle lines
$Shape.Line.Visible = $False
#Set transparency of watermark
$Shape.Fill.Transparency = .8
#Center watermark on width of page
$Shape.Left = -999995
#Center watermark on height of page (This was guess and checked)
$Shape.Top = 250
#Rotate watermark
#Rotation rarely works when Word is not visible. Command left here for reference.
$Shape.Rotation = 315
}
#Only on 1st Page
#Watermark $Doc $WM
#On all Pages
#Determine number of pages in document
$Bind = 'System.Reflection.BindingFlags' -as [type]
$Doc.Repaginate()
$Prop = $Doc.BuiltInDocumentProperties(14)
$Pages = [System.__ComObject].invokemember('Value', $Bind::GetProperty, $null, $Prop, $null)
#Start at 0 to include any cover pages
For ($i = 0; $i -le $Pages - 1; $i ++)
{
#Change pages
$Word.Selection.GoTo(1,2,$null,$i)
#Apply watermark
Watermark $Doc $WM
}
#Check version of Word installed and save changes
$Version = $Word.Version
If ($Version -eq '16.0' -Or $Version -eq '15.0') {
$Doc.Close($True)
}
ElseIf ($Version -eq '14.0') {
$Doc.Close([ref]$True)
}
#Exit Word
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
$Word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Word)
#Cleanup
Remove-Variable Word
You could also, just ---
Opened any Word doc with a watermark.
Fire up the Word Macro recorder.
Do what you wish in Word.
Stop the recorder when done.
Export the macro code.
Convert the macro VBA code for use with PowerShell.
Here's my solution, cobbled together from "Hey, Scripting Guy!" entries and this question about PowerShell and Word footers.
Function OpenWordDoc($Filename)
{
$Word = NEW-Object –ComObject Word.Application
Return $Word.documents.open($Filename)
}
$Doc = OpenWordDoc -Filename "C:\Users\mynamehere\Downloads\andSuch\WaterMarkDoc.docx"
$Savename = "C:\Users\mynamehere\Downloads\andSuch\SansWaterMarkDoc.docx"
[void]$Doc.Sections.Item(1).Headers.Item(1).range.Delete(1)
Function SaveAsWordDoc($Document,$FileName)
{
$Doc.Saveas([REF]$Filename)
$Doc.Close()
}
SaveAsWordDoc –document $Doc –Filename $Savename

Columns Page Layout in Word with Powershell

I'm creating a word document with Powershell and I need to create a two-column column similar to the GUI method shown in the screen shot below:
I've researched other websites that explain basic Powershell Word objects, properties and methods, such as this one. However, there seems to be a lot more functionality that is "hidden" deep in the pages and pages of properties and methods. I'm looking to create a two-column column in my word doc. Here is the code I used to create the document and write to it:
$fileName = 'C:\template.docx'
$word = New-Object -Com Word.Application
$word.Visible = $true
$document = $word.Documents.Open($fileName)
$selection = $word.Selection
$text = "Test Text."
$selection.TypeText($text)
$document.SaveAs($fileName)
$document.Close()
$word.Quit()
$word = $null
Having worked with Excel ComObjects, it's not the easiest to figure out how to make it work with PowerShell.
You're missing this line:
$selection.PageSetup.TextColumns.SetCount(2)
How to get there?
Check the Word Interop Com Object MSDN page
It's probably the PageSetup object we're interesting in (because in the GUI the two columns appear under Layout > Page Setup > Columns)
Googling "word com object pagesetup" leds to a better MSDN documentation page that lists the properties
Repeat this process for TextColumns - it has the methods in the "Remarks" but I prefer to a doc page which lists the members
Finally, finding the SetCount method.
Hopefully this helps you to figure out how to navigate the Word ComObject document in future. The examples are in VBA or C# at best and need to be translated to PowerShell.
$fileName = 'C:\Template.docx'
$binding = "System.Reflection.BindingFlags" -as [type]
$word = New-Object -Com Word.Application
$word.Visible = $true
$document = $word.Documents.Open($fileName)
$selection = $word.Selection
$text = "Test Text."
$selection.TypeText($text)
$selection.PageSetup.TextColumns.SetCount(2)
# check the GUI here.
# You will see the Layout > Page Setup > Columns > Two is selected
$document.SaveAs($fileName)
$document.Close()
$word.Quit()
$word = $null

Powershell Select-All from Word Doc

I want to open, then select all of the text from a word document, not any of the properties, formatting, etc. Ihave searched this site and googled it to no end. Basically similar to opening a Word doc and pressing Ctrl-A and assigning the result to a variable.
$word = New-Object -ComObject Word.Application
$word.visible = $True
$wordfilepath = "\\symphony1\powershell\Phones\Phone.docx"
$doc = $word.Documents.Open($wordfilepath)
????
$selection" >> $textfilepath
Basically a newbie question, but can anyone help?
Thanks.
This will probably suit your needs. It creates a new word object, opens your existing file, and pulls the text from it.
$filePath = <your file here>
$doc = New-Object -com word.application
$fileToOpen = $doc.Documents.Open("$filePath")
$text = $fileToOpen.Range().text
Be forewarned that it will strip out even very basic formatting features such as new lines. Here's a nice list of other range members and properties that you may find helpful.

Add AUTOTEXT to MS Word Document with Power Shell

I am working on a project where I need to add AUTOTEXT entries like the Page 1 of X listings to the header and footer of a Power Shell generated MS Word document. I have tried extracting ideas from the following C# examples, but I cannot seem to figure out how to make it work. I was curious if someone could share some code to help me with this.
A starting point. This function add page number to the footer of document passed as parameter ( used on word 2010):
function Add-PageFooter ([string]$Document) {
add-type -AssemblyName "Microsoft.Office.Interop.Word"
set-variable -name wdAlignPageNumberCenter -value 1 -option constant
$fc1 = "Page"
$word = New-Object -comobject Word.Application
$Word.Visible = $True
#$Word.Visible = $False
$fc2 = [ref] "" -as [Type]
$OpenDoc = $Word.Documents.Open($Document)
$c = $OpenDoc.Sections.Item(1).Footers.Item(1).PageNumbers.Add($wdAlignPageNumberCenter)
$range1 = $openDoc.Sections.Item(1).Footers.Item(1).range
$field1 = $OpenDoc.Fields.Add($range1, -1, $fc2)
$field1.Code.Text = $fc1
$field1.Update
#$OpenDoc.Close()
}
Another way is to create a Word Macro and execute from powershell:
$wd = new-object -comobject word.application # create a com object interface (word application)
$wd.documents.open("C:\word\test.doc") # open doc
$wd.run("Macro01") # exec macro named macro01 that add custom footer and/or header
$wd.quit() # exit application
The macro must be saved on normal.dot (normal.dotm for 2010 and above) to have it in all open documents.
In this way you can customize what you want in a word document and not just header/footer recording in a macro your actions in the docs.