I see this question every so often so it makes sense to share it through a quick post. When using the print API in Silverlight 4 you can run into the dreaded exception:

“System.Security.SecurityException: Dialogs must be user-initiated”

Then you examine your code and confirm that your code where you invoke the PrintDocument’s Print method are indeed being handled by a user-initiated event. If you are not invoking Print in a user-initiated event then your know your solution :)

Here is some sample code you can try to reproduce the problem:

void btnPrint_Click(object sender, System.Windows.RoutedEventArgs e)
{
 
    PrintDocument pd = new PrintDocument();
    pd.PrintPage += (s, args) =>
    {
        args.PageVisual = LayoutRoot;
    };
    pd.Print("SomeDocument");
}

And here is some XAML to go with the C# code:

<Grid x:Name="LayoutRoot" Background="White">
    <Button Content="Print"
                Name="btnPrint"
                Height="20"
                Width="75" 
                Click="btnPrint_Click"/>
</Grid>

The problem can often be caused by doing what developers do well: debugging code. If you put a breakpoint in your code that invokes the Print method and walk over the Print method, you could see the exception shown above.

image

The easy solution is to remove the breakpoint and let the code run through.

Pretty simple … but not always obvious … hope this helps.

 

Quick sidenote: It is worth noting that the Print API for Silverlight 4 changed after the early beta and that the Print method requires a single argument for the print document name. So make sure you pass the name of the print document to the Print method.