Printing ScrollViewer Content

I have the following: wpf window with scrollviewer function and Print button.

I am trying to print the contents of a scrollviewer using PrintDialog, but it only works for xps. If I select my printer or document, the final result will be terrible (half a page, cutting, etc.). How can I solve this problem without resizing / scaling the contents of its scrollviewer?

+5
source share
2 answers

For decent (and relatively easy) printing in WPF, you should use FlowDocumentScrollViewer instead of ScrollViewer. Inside the FlowDocumentScrollViewer, you can place a FlowDocument that will contain the content that you want to print.

XAML example:

<FlowDocumentScrollViewer> <FlowDocument PagePadding="48"> <Section> <Paragraph> <Run Text="sample"/> </Paragraph> </Section> <Section> <BlockUIContainer> <my:myUserControl/> </BlockUIContainer> </Section> </FlowDocument> </FlowDocumentScrollViewer> 

The "BlockUIContainer" object is great for user control, which may contain everything you need. The PagePadding property for FlowDocument sets the margin. 48 is equivalent to 1/2 inch. (96 dpi).

Example print code:

 Dim pd As New PrintDialog If pd.ShowDialog Then Dim fd As FlowDocument = docOutput Dim pg As DocumentPaginator = CType(fd, IDocumentPaginatorSource).DocumentPaginator pd.PrintDocument(pg, "my document") End If 
+4
source

FlowDocument is probably the best solution for dynamic content and dynamic print size, i.e. either unknown or subject to change. For my problem, I knew both the content and print size.

The first thing I did was set the content in ScrollViewer, the grid in my case, to A4 size, which can be easily done with

 <Grid x:Name="gridReport" Height="29.7cm" Width="21cm"> 

This means that the grid is displayed exactly in the print area, and everything inside the grid should not be distorted when printing.

This still cuts off the top area if the ScrollViewer was not scrolled to the top at the point of use of PrintDialog. To solve this problem programmatically, before printing, click

 Myscrollviewer.ScrollToTop(); PrintDialog printDialog = new PrintDialog(); if(printDialog.ShowDialog() == true) { printDialog.PrintVisual(gridReport, "Print Report"); } 
+1
source

Source: https://habr.com/ru/post/1388953/


All Articles