如何为WPF文档查看器文档设置纸张尺寸和边距?

时间:2019-03-20 10:51:45

标签: wpf documentviewer

//I want to set the Paper Size and Margins to WPF Document viewer document so that I can preview the settings.Here I attach the xaml and code behind how I created the entire sample application with all xaml and code behind logic.

//Main window created by adding the Grid with Popup to set the document settings like margins paper size,orientation

       <Window x:Class="SampleDocumentViewer.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:SampleDocumentViewer"
            mc:Ignorable="d"
            Title="MainWindow">
        <Grid Background="#E8E8E8"
                    HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch"
                    Margin="0,0,0,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="30"></RowDefinition>
                <RowDefinition Height="80*"></RowDefinition>
                <RowDefinition Height="40"></RowDefinition>
            </Grid.RowDefinitions>
            <ToggleButton Grid.Row="0" Height="25" Width="100" HorizontalAlignment="Left" x:Name="PopupButton" IsChecked="{Binding ElementName=Popup, Path=IsOpen}" Margin="20,0,0,0" Background="#E8E8E8" BorderThickness="0" BorderBrush="#E8E8E8">
                <StackPanel Orientation="Horizontal">
                    <TextBlock>Page Setup</TextBlock>
                    <Viewbox Width="48" Height="48" Margin="-5,-3,0,0">
                        <Canvas Width="48" Height="48">
                            <Path Data="M7,10L12,15L17,10H7Z" Fill="Black" />
                        </Canvas>
                    </Viewbox>
                </StackPanel>
                <ToggleButton.Style>
                    <Style TargetType="ToggleButton" BasedOn="{StaticResource {x:Type ToggleButton}}">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding IsOpen, ElementName=Popup}" Value="True">
                                <Setter Property="IsEnabled" Value="False" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </ToggleButton.Style>
            </ToggleButton>
            <Popup x:Name="Popup" StaysOpen="False" PlacementTarget="{Binding ElementName=PopupButton}" Placement="Bottom" Width="415" Height="200">
                <Grid Background="Transparent" Margin="5,5,5,5">
                    <Grid.Effect>
                        <DropShadowEffect BlurRadius="15" Direction="-90" RenderingBias="Quality" ShadowDepth="2"/>
                    </Grid.Effect>
                    <Grid Width="450" Height="200" Background="#E8E8E8">
                        <!--<Grid.Effect>
                            <DropShadowEffect BlurRadius="15" Direction="-90" RenderingBias="Quality" ShadowDepth="2"/>
                        </Grid.Effect>-->
                        <Grid.RowDefinitions>
                            <RowDefinition Height="30"/>
                            <RowDefinition Height="50"/>
                            <RowDefinition Height="30"/>
                            <RowDefinition Height="40"/>
                            <RowDefinition Height="40"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="20"/>
                            <ColumnDefinition Width="90"/>
                            <ColumnDefinition Width="300"/>
                        </Grid.ColumnDefinitions>
                        <StackPanel Grid.Row="0" Grid.ColumnSpan="5" Background="#007CB0">
                            <Button Grid.Row="0" Grid.Column="5" x:Name="closeBtn" Width="15" Height="15" HorizontalAlignment="Right" VerticalAlignment="Center" 
                             Margin="0,0,10,0" Click="closeBtn_Click">
                                <Path Fill="LightGray" Stretch="Uniform" StrokeThickness="1" Stroke="Black"
                                              Data="M 14.508898,113.34179 7.428267,100.16106 h 8.699683 l 4.351833,7.68916 4.407885,-7.68916 h 8.697689 l -7.077552,13.13791 7.457453,13.77884 h -8.697474 l -4.788001,-8.16176 -4.731959,8.16176 H 6.1512438 Z"/>
                            </Button>
                        </StackPanel>
                        <TextBlock Grid.Row="1" Grid.Column="1" x:Name="paperSizeTB" Height="30"  HorizontalAlignment="Left" VerticalAlignment="Center">Paper Size:</TextBlock>
                        <ComboBox   x:Name="paperSizeCB" Grid.Row="1" Grid.Column="2" Height="30" Width="230" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="10"
                                 SelectionChanged="paperSizeCB_SelectionChanged"></ComboBox>
                        <TextBlock Grid.Row="2" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Top">Orientation:</TextBlock>
                        <StackPanel Grid.Row="2" Grid.Column="2" Orientation="Horizontal">
                            <RadioButton x:Name="potraitRbn"  Height="30" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="10,0,0,0" Checked="potraitRbn_Checked">Portrait</RadioButton>
                            <RadioButton x:Name="landscapeRbn"  Height="30" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="30,0,0,0" Checked="landscapeRbn_Checked">Landscape</RadioButton>
                        </StackPanel>
                        <StackPanel Grid.Row="3" Grid.Column="1"  Orientation="Horizontal">
                            <TextBlock  Height="30"  HorizontalAlignment="Left" VerticalAlignment="Center" Margin="0,10,0,0">Margins:</TextBlock>
                            <TextBlock  Height="30" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="20,10,0,0" >Left:</TextBlock>
                        </StackPanel>
                        <StackPanel Grid.Row="3" Grid.Column="2" Orientation="Horizontal" >
                            <TextBox x:Name="leftMarginTB" Height="20" Width="70"  Margin="10,0,0,0" PreviewTextInput="leftMarginTB_PreviewTextInput"></TextBox>
                            <TextBlock Height="30"  HorizontalAlignment="Left" VerticalAlignment="Center" Margin="0,10,0,0">Inches</TextBlock>
                            <TextBlock Height="30" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="10,10,0,0">Right:</TextBlock>
                            <TextBox x:Name="rigthMarginTB" Height="20"  Width="70" Margin="15,0,0,0" PreviewTextInput="rigthMarginTB_PreviewTextInput"></TextBox>
                            <TextBlock HorizontalAlignment="Left" VerticalAlignment="Center">Inches</TextBlock>
                        </StackPanel>
                        <TextBlock Grid.Row="5" Grid.Column="1" Height="30" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="65,10,0,0">Top:</TextBlock>
                        <StackPanel Grid.Row="5" Grid.Column="2" Orientation="Horizontal">
                            <TextBox x:Name="topMarginTB" Height="20" Width="70"  Margin="10,0,0,0" PreviewTextInput="topMarginTB_PreviewTextInput"></TextBox>
                            <TextBlock Height="30" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="0,10,0,0">Inches</TextBlock>
                            <TextBlock Height="30" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="10,10,0,0">Bottom:</TextBlock>
                            <TextBox x:Name="bottomMarginTB" Height="20"  Width="70" Margin="5,0,0,0" PreviewTextInput="bottomMarginTB_PreviewTextInput"></TextBox>
                            <TextBlock  Height="30" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="0,10,0,0">Inches</TextBlock>
                        </StackPanel>
                    </Grid>
                </Grid>
            </Popup>
            <DocumentViewer Grid.Row="1" Margin="0,0,40,0" Name="documentViewer"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Loaded="documentViewer_Loaded" >
                <DocumentViewer.Resources>
                    <Style TargetType="ContentControl">
                        <Style.Triggers>
                            <Trigger Property="Name" Value="PART_FindToolBarHost">
                                <Setter Property="Visibility" Value="Collapsed" />
                            </Trigger>
                            <Trigger Property="Name" Value="CopyButton">
                                <Setter Property="Visibility" Value="Collapsed" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </DocumentViewer.Resources>
            </DocumentViewer>
        </Grid>
    </Window>

//Main window code behind logic 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SampleDocumentViewer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        FixedDocument fixedDocument;

        public StackPanel mystackpanel { get; set; }
        public StackPanel secondStackPanel { get; set; }

        public StackPanel thirdStackPanel { get; set; }
        public MainWindow()
        {
            InitializeComponent();

            this.potraitRbn.IsChecked = true;
            this.paperSizeCB.Items.Add("Letter");
            this.paperSizeCB.Items.Add("A4");
            this.paperSizeCB.Items.Add("Legal");
            this.paperSizeCB.Items.Add("LegalExtra");
            this.paperSizeCB.Items.Add("Tabloid");

            this.paperSizeCB.SelectedValue = this.paperSizeCB.Items[0];
            this.leftMarginTB.Text = "0";
            this.rigthMarginTB.Text = "0";
            this.topMarginTB.Text = "0";
            this.bottomMarginTB.Text = "0";
        }

//在纵向按钮上已选中

        private void potraitRbn_Checked(object sender, RoutedEventArgs e)
        {
            landscapeRbn.IsChecked = false;

            if (documentViewer.Document != null)
            {
                fixedDocument = documentViewer.Document as FixedDocument;
                var fixedPageHeight = fixedDocument.Pages[0].Child.ActualHeight;
                var fixedPageWidth = fixedDocument.Pages[0].Child.ActualWidth;
                foreach (var page in fixedDocument.Pages)
                {
                    //fixed pages
                    page.Child.Width = fixedPageHeight;
                    page.Child.Height = fixedPageWidth;

                    //Margin if any
                    page.Child.Margin = new Thickness((System.Convert.ToDouble(leftMarginTB.Text) * 96),
                        (System.Convert.ToDouble(rigthMarginTB.Text) * 96), (System.Convert.ToDouble(topMarginTB.Text) * 96), (System.Convert.ToDouble(bottomMarginTB.Text) * 96));

                    page.Child.Measure(new Size(fixedPageHeight, fixedPageWidth));
                    Application.Current.Dispatcher.Invoke(() => page.Child.UpdateLayout());
                }
                documentViewer.Document = null;
                documentViewer.Document = fixedDocument;
                foreach (var page in fixedDocument.Pages)
                {
                    page.UpdateLayout();
                }
                Application.Current.Dispatcher.Invoke(() => documentViewer.InvalidateVisual());
                Application.Current.Dispatcher.Invoke(() => documentViewer.UpdateLayout());
            }
        }

//在横向单选按钮上已选中

        private void landscapeRbn_Checked(object sender, RoutedEventArgs e)
        {
            potraitRbn.IsChecked = false;

            if (documentViewer.Document != null)
            {
                fixedDocument = documentViewer.Document as FixedDocument;
                var fixedPageHeight = fixedDocument.Pages[0].Child.ActualHeight;
                var fixedPageWidth = fixedDocument.Pages[0].Child.ActualWidth;
                foreach (var page in fixedDocument.Pages)
                {
                    //fixed pages
                    page.Child.Width = fixedPageHeight;
                    page.Child.Height = fixedPageWidth;

                    //Margin if any
                    page.Child.Margin = new Thickness((System.Convert.ToDouble(leftMarginTB.Text) * 96),
                        (System.Convert.ToDouble(rigthMarginTB.Text) * 96), (System.Convert.ToDouble(topMarginTB.Text) * 96), (System.Convert.ToDouble(bottomMarginTB.Text) * 96));
                    page.Child.Measure(new Size(fixedPageHeight, fixedPageWidth));
                    Application.Current.Dispatcher.Invoke(() => page.Child.UpdateLayout());
                }

                documentViewer.Document = null;
                documentViewer.Document = fixedDocument;
                foreach (var page in fixedDocument.Pages)
                {
                    page.UpdateLayout();
                }
                Application.Current.Dispatcher.Invoke(() => documentViewer.InvalidateVisual());
                Application.Current.Dispatcher.Invoke(() => documentViewer.UpdateLayout());
            }
        }

//要为文档查看器文档设置纸张尺寸。

        private void paperSizeCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {         
        }

//在左边距PreviewTextInput

        private void leftMarginTB_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
        }

//在右边距PreviewTextInput

        private void rigthMarginTB_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
        }

//在上边距PreviewTextInput

        private void topMarginTB_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
        }

//在底边距PreviewTextInput

        private void bottomMarginTB_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
        }

//在文档查看器上,加载内容并将其添加到文档查看器文档中。

        private void documentViewer_Loaded(object sender, RoutedEventArgs e)
        {
            List<TextBlock> textBlocksForContent = new List<TextBlock>();
            List<TextBlock> textBlocksForSecondContent = new List<TextBlock>();
            List<TextBlock> textBlocksForThirdContent = new List<TextBlock>();
            for (int i = 0; i < 12; i++)
            {
                TextBlock tbNew = new TextBlock();
                tbNew.Margin = new Thickness(100, 0, 0, 0);
                tbNew.FontFamily = new System.Windows.Media.FontFamily("Arial");
                tbNew.FontSize = 14;
                tbNew.FontWeight = FontWeights.Normal;
                switch (i.ToString())
                {
                    case "0":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t{1}", " Antenna Name: ", "Reader1");
                        break;
                    case "1":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t{1}", " Antenna State: ", "Open");
                        break;
                    case "2":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t{1}", " Inventory: ", "Running");
                        break;
                    case "3":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t\t{1}", " S FLAG ", "TRUE");
                        break;
                    case "4":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t{1}", " Population Estimate: ", 123456789);
                        break;
                    case "5":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t{1}", " Color Id: ", "123");
                        break;
                    case "6":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t{1}", " Is Enabled for Reads: ", "Yes");
                        break;
                    case "7":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t\t\t{1}", " Power : ", 120);
                        break;
                    case "8":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t\t\t{1}", " Mode: ", "Speed");
                        break;
                    case "9":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t\t{1}", " Is Active: ", "Yes");
                        break;
                    case "10":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t{1}", " Stop Trigger Type: ", "Set for none");
                        break;
                    case "11":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t{1}", " Antenna Stop Condition Value: ", "None");
                        break;
                }
                textBlocksForContent.Add(tbNew);
            }
            for (int i = 0; i < 12; i++)
            {
                TextBlock tbNew = new TextBlock();
                tbNew.Margin = new Thickness(100, 0, 0, 0);
                tbNew.FontFamily = new System.Windows.Media.FontFamily("Arial");
                tbNew.FontSize = 14;
                tbNew.FontWeight = FontWeights.Normal;
                switch (i.ToString())
                {
                    case "0":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t{1}", " Antenna Name: ", "Reader5");
                        break;
                    case "1":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t{1}", " Antenna State: ", "Open");
                        break;
                    case "2":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t{1}", " Inventory: ", "Running");
                        break;
                    case "3":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t\t{1}", " S FLAG ", "TRUE");
                        break;
                    case "4":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t{1}", " Population Estimate: ", 123456789);
                        break;
                    case "5":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t{1}", " Color Id: ", "123");
                        break;
                    case "6":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t{1}", " Is Enabled for Reads: ", "Yes");
                        break;
                    case "7":
                        tbNew.Text = "Antenna" + String.Format("{0}\t{1}", " Power : ", 120);
                        break;
                    case "8":
                        tbNew.Text = "Antenna" + String.Format("{0}\t{1}", " Mode: ", "Speed");
                        break;
                    case "9":
                        tbNew.Text = "Antenna" + String.Format("{0}\t{1}", " Is Active: ", "Yes");
                        break;
                    case "10":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t{1}", " Stop Trigger Type: ", "Set for none");
                        break;
                    case "11":
                        tbNew.Text = "Antenna" + String.Format("{0}\t{1}", " Antenna Stop Condition Value: ", "None");
                        break;
                }
                textBlocksForSecondContent.Add(tbNew);
            }          
            for (int i = 0; i < 12; i++)
            {
                TextBlock tbNew = new TextBlock();
                tbNew.Margin = new Thickness(100, 0, 0, 0);
                tbNew.FontFamily = new System.Windows.Media.FontFamily("Arial");
                tbNew.FontSize = 14;
                tbNew.FontWeight = FontWeights.Normal;
                switch (i.ToString())
                {
                    case "0":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t{1}", " Antenna Name: ", "Reader8");
                        break;
                    case "1":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t{1}", " Antenna State: ", "Open");
                        break;
                    case "2":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t{1}", " Inventory: ", "Running");
                        break;
                    case "3":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t\t{1}", " S FLAG ", "TRUE");
                        break;
                    case "4":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t{1}", " Population Estimate: ", 123456789);
                        break;
                    case "5":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t\t{1}", " Color Id: ", "123");
                        break;
                    case "6":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t{1}", " Is Enabled for Reads: ", "Yes");
                        break;
                    case "7":
                        tbNew.Text = "Antenna" + String.Format("{0}\t{1}", " Power : ", 120);
                        break;
                    case "8":
                        tbNew.Text = "Antenna" + String.Format("{0}\t{1}", " Mode: ", "Speed");
                        break;
                    case "9":
                        tbNew.Text = "Antenna" + String.Format("{0}\t{1}", " Is Active: ", "Yes");
                        break;
                    case "10":
                        tbNew.Text = "Antenna" + String.Format("{0}\t\t{1}", " Stop Trigger Type: ", "Set for none");
                        break;
                    case "11":
                        tbNew.Text = "Antenna" + String.Format("{0}\t{1}", " Antenna Stop Condition Value: ", "None");
                        break;
                }
                textBlocksForThirdContent.Add(tbNew);
            }         
            mystackpanel = new StackPanel();
            foreach (var cont in textBlocksForContent)
            {
                mystackpanel.Children.Add(cont);
            }
            secondStackPanel = new StackPanel();
            foreach (var content in textBlocksForSecondContent)
            {
                secondStackPanel.Children.Add(content);
            }
            thirdStackPanel = new StackPanel();
            foreach (var content in textBlocksForThirdContent)
            {
                thirdStackPanel.Children.Add(content);
            }

            //Create documeent and add first page content.
            FixedDocument fixedDoc = new FixedDocument();
            PageContent pageContent = new PageContent();
            fixedDoc.Pages.Add(pageContent);
            FixedPage fixedPage = new FixedPage();
            fixedPage.Children.Add(mystackpanel);
            ((System.Windows.Markup.IAddChild)fixedDoc.Pages[0]).AddChild(fixedPage);

            //create secondStackPanel for other document page.
            PageContent secondpageContent = new PageContent();
            fixedDoc.Pages.Add(secondpageContent);
            FixedPage secondPage = new FixedPage();
            secondPage.Children.Add(secondStackPanel);
            ((System.Windows.Markup.IAddChild)fixedDoc.Pages[1]).AddChild(secondPage);

            //create thirdStackPanel for other document page.
            PageContent thirdpageContent = new PageContent();
            fixedDoc.Pages.Add(thirdpageContent);
            FixedPage thirdPage = new FixedPage();
            thirdPage.Children.Add(thirdStackPanel);
            ((System.Windows.Markup.IAddChild)fixedDoc.Pages[2]).AddChild(thirdPage);

            //Set the document   
            this.documentViewer.Document = fixedDoc;

            // Create a FlowDocument dynamically.  
            FixedDocument doc = fixedDoc;
            doc.Name = "FlowDoc";
        }

//单击弹出窗口的关闭按钮时,关闭弹出窗口

        private void closeBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Popup.IsOpen = false;
        }
    }
}

0 个答案:

没有答案