title: PowerShell WPF Printing - Can Not Get the IDocumentPaginatorSource Interface
body: <p>I am trying to use WPF printing from PowerShell. I have found a simple example in VB.Net <a href="http://www.codeproject.com/KB/WPF/WpfBasicTextPrinting.aspx" rel="nofollow">here</a>:</p>
  
  <pre><code>'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)
  </code></pre>
  
  <p>but I am unable to convert it to PowerShell. Here is my attempt:</p>
  
  <pre><code>$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")
  </code></pre>
  
  <p>$source.DocumentPaginator seems to be null, and an exception is raised. (The VB.Net code works)</p>
  
  <p>[Edit]</p>
  
  <p>Here is another attempt that failed:</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>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.</p>