在WPF中是否可以按页码获取每个DocumentPage的内容?

时间:2014-09-12 11:11:29

标签: c# wpf flowdocument documentpaginator documentpage

我使用DocumentPaginator将FlowDocument的文本分成页面。是否有可能在ComputePageCount()之后按页码获取每个页面的内容?如果没有,我怎么能用其他方式呢?

代码:

var flowDocument = this.Document;
flowDocument.MaxPageHeight = this.MaxContentHeight;
DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
paginator.ComputePageCount();

2 个答案:

答案 0 :(得分:2)

是的,这是可能的。

以下是一个例子:

<强> MainWindow.xaml

<Window x:Class="WpfApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <TextBlock x:Name="outputTextBlock" DockPanel.Dock="Bottom"/>
        <FlowDocumentPageViewer>
            <FlowDocument x:Name="flowDocument" Loaded="OnFlowDocumentLoaded">
                <Paragraph>First page</Paragraph>
                <Paragraph BreakPageBefore="True">Second page</Paragraph>
                <Paragraph BreakPageBefore="True">Third page</Paragraph>
            </FlowDocument>
        </FlowDocumentPageViewer>
    </DockPanel>
</Window>

<强> MainWindow.xaml.cs

using System.Text;
using System.Windows;
using System.Windows.Documents;

namespace WpfApplication
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnFlowDocumentLoaded(object sender, RoutedEventArgs e)
        {
            var paginator = (DynamicDocumentPaginator)((IDocumentPaginatorSource)this.flowDocument).DocumentPaginator;

            var text = new StringBuilder();

            for (int pageNumber = 0; ; ++pageNumber)
                using(var page = paginator.GetPage(pageNumber))
                using (var nextPage = paginator.GetPage(pageNumber + 1))
                {
                    if (page == DocumentPage.Missing)
                        break;

                    var startPosition = (TextPointer)paginator.GetPagePosition(page);
                    var endPosition = nextPage == DocumentPage.Missing ? this.flowDocument.ContentEnd : (TextPointer)paginator.GetPagePosition(nextPage);

                    var range = new TextRange(startPosition, endPosition);

                    text.AppendFormat("Page {0}:", pageNumber + 1).AppendLine();
                    text.AppendLine(range.Text);
                }

            this.outputTextBlock.Text = text.ToString();
        }
    }
}

答案 1 :(得分:0)

您可以使用DocumentPaginator对象的GetPage函数。它将页码作为参数。

请参阅http://msdn.microsoft.com/en-us/library/system.windows.documents.documentpaginator.getpage(v=vs.110).aspx