I am trying to use WPF printing from PowerShell. I have found a simple example in VB.Net here:
'Create a new Run class, passing it the text.
' The Run class contains 1 line of text
Dim r As New Run(text)
'Create a new paragraph, passing it the new run class instance
Dim ph As New Paragraph(r)
'Create the document, passing a new paragraph
Dim doc As New FlowDocument(ph)
doc.PagePadding = New Thickness(100) 'Creates margin around the page
'Send the document to the printer
diag.PrintDocument( _
CType(doc, IDocumentPaginatorSource).DocumentPaginator, _
printCaption)
but I am unable to convert it to PowerShell. Here is my attempt:
$run = New-Object System.Windows.Documents.Run('text')
$paragraph = New-Object System.Windows.Documents.Paragraph($run)
$flowDocument = New-Object System.Windows.Documents.FlowDocument($paragraph)
$thickness = New-Object System.Windows.Thickness(100)
$flowDocument.PagePadding = $thickness
$flowDocument -is [System.Windows.Documents.IDocumentPaginatorSource]
$source = $flowDocument -as [System.Windows.Documents.IDocumentPaginatorSource]
$source.DocumentPaginator -eq $null
$printDialog = New-Object System.Windows.Controls.PrintDialog
$printDialog.PrintDocument($source.DocumentPaginator, "test")
$source.DocumentPaginator seems to be null, and an exception is raised. (The VB.Net code works)
[Edit]
Here is another attempt that failed:
Add-Type -Assembly 'ReachFramework'
$flowDocument = New-Object System.Windows.Documents.FlowDocument
$textRange = New-Object System.Windows.Documents.TextRange(
$flowDocument.ContentStart, $flowDocument.ContentEnd)
$textRange.Text = 'Text'
$xpsDocument = New-Object System.Windows.Xps.Packaging.XpsDocument(
"C:\scripts\test.xps", [System.IO.FileAccess]::ReadWrite)
$xpsDocumentWriter =
[System.Windows.Xps.Packaging.XpsDocument]::CreateXpsDocumentWriter(
$xpsDocument)
$source = $flowDocument -as [System.Windows.Documents.IDocumentPaginatorSource]
$xpsDocumentWriter.Write($source.DocumentPaginator)
$xpsDocument.Close()
I was trying to use one of the XpsDocumentWriter.Write() overloads to send the FlowDocument to a printer, but it failed, $source.DocumentPaginator is null. I didn’t even manage to create a .xps file and save it.
Sometimes when I get frustrated with PowerShell’s language “issues”, I drop back to C# which V2 makes very easy. The following prints for me:
Note that you could do the same with VB code. Just use the
-Language VisualBasicparameter onAdd-Type.