Powershell Open text file print it on exit

2k views Asked by At

I have a text file that I need to open in Notepad.exe and have the user add some input to it. Then I would like to print the file to AdobePDF when the user exits the file.

Here is what I have to open the file

Start-Process notepad.exe C:\path\to\text\file\MyTextFile.txt -NoNewWindow -Wait

Not sure how to Print PDF on exit. AdobePDF is an installed printer but it is NOT THE DEFAULT printer. Any help or tips would be greatly appreciated.

1

There are 1 answers

2
Prageeth Saravanan On BEST ANSWER

You can try something like this,

$TxtFilePath = "C:\folder\txtfile.txt"
Start-Process notepad.exe $TxtFilePath -NoNewWindow -Wait #Assuming user save the file
Get-Content -Path $TxtFilePath| Out-Printer PDFCreator #PDFCreator is the printer name for PDF 

--EDIT--

I could not figure out a direct approach to retain the file name, kind of wrote a hack with ms word,

Function Save-TxtAsPDF
{
    Param([string] $FilePath, [string] $OutFolder)

    # Required Word Variables
    $ExportASPDFConstant = 17
    $DoNotSaveConstant = 0

    # Create a hidden Word window
    $word = New-Object -ComObject word.application
    $word.visible = $false

    # Add a Word document
    $doc = $word.documents.add()

    # Put the text into the Word document
    $txt = Get-Content $FilePath
    $selection = $word.selection
    $selection.typeText($txt)

    # Set the page orientation to landscape
    $doc.PageSetup.Orientation = 1

    $FileName = (Split-Path -Path $FilePath -Leaf).Replace(".txt",".pdf")  


    $DestinationPath = Join-Path $OutFolder $FileName

    # Export the PDF file and close without saving a Word document
    $doc.ExportAsFixedFormat($DestinationPath,$ExportASPDFConstant)
    $doc.close([ref]$DoNotSaveConstant)
    $word.Quit()
}


$TxtFilePath = "C:\folder\tt.txt"
$OutFolder = "C:\Outputfolder"

Start-Process notepad.exe $TxtFilePath -NoNewWindow -Wait #Assuming user save the file

Save-TxtAsPDF -FilePath $TxtFilePath -OutFolder $OutFolder

See if that helps!