WPF RichTextBox 打印正在创建意外的换行符

WPF RichTexBox printing is creating unexpected line breaks

在我的 WPF 应用程序的 RichTextBox 中,以下打印方法正在创建意外的换行符。 问题:我可能在这里遗漏了什么,我们如何解决这个问题?

例如,当我在 RichTextBox (RTB) 中输入以下文本时,RTB 看起来如图 1 所示。但是当我调用以下两个打印方法时,第一个不会创建意外的换行符,但第二种方法确实会产生意外的换行符:

MainWindow.xaml

<StackPanel>
    <RichTextBox Name="richTB" />

    <Button Click="PrintCommand1">Print RTB Content</Button>
    <Button Click="PrintCommand2">Print RTB Content</Button>
</StackPanel>

方法一

private void PrintCommand1(Object sender, RoutedEventArgs args)
{
    PrintDialog pd = new PrintDialog();
    if ((pd.ShowDialog() == true))
    {
        pd.PrintVisual(richTB as Visual, "printing as visual");
    }
}

方法二

private void PrintCommand2(Object sender, RoutedEventArgs args)
{
    PrintDialog pd = new PrintDialog();
    if ((pd.ShowDialog() == true))
    {
        pd.PrintDocument((((IDocumentPaginatorSource)richTB.Document).DocumentPaginator), "printing as paginator");
    }
}

我输入的文字[注意:只有一个换行符]

This is a test for testing purpose only. Another test: x6. Let us do some background and foreground colors.
This is a new line with formatting, as well.

带有以上文本的 RichTexBox 快照

使用方法 1 的“打印为 PDF”快照(在 Windows 10)[打印正确,有一个真正的换行符]

使用方法 2 的“打印为 PDF”(在 Windows 10)的快照[打印不正确,出现意外的换行符]

因为 DocumentPaginator class 使用 FlowDocument 的上下文并分成多个页面以获得所需的结果,一些 FlowDocument 参数应该在打印前配置:

private void PrintCommand2(Object sender, RoutedEventArgs args)
{
    var pd = new PrintDialog();
    if (pd.ShowDialog() == true)
    {
        FlowDocument doc = richTB.Document;

        // Save all settings that will be configured for printing.
        double pageHeight = doc.PageHeight;
        double pageWidth = doc.PageWidth;
        double columnGap = doc.ColumnGap;
        double columnWidth = doc.ColumnWidth;

        // Make the FlowDocument page match the printed page.
        doc.PageHeight = pd.PrintableAreaHeight;
        doc.PageWidth = pd.PrintableAreaWidth;                
        doc.ColumnGap = 5; 

        // Set the minimum desired width of the column in the System.Windows.Documents.FlowDocument.
        doc.ColumnWidth = doc.PageWidth - doc.ColumnGap - doc.PagePadding.Left - doc.PagePadding.Right;
        pd.PrintDocument(((IDocumentPaginatorSource)doc).DocumentPaginator, "A Flow Document");

        // Reapply the old settings.
        doc.PageHeight = pageHeight;
        doc.PageWidth = pageWidth;                
        doc.ColumnGap = columnGap;
        doc.ColumnWidth = columnWidth;
    }
}

关于Matthew MacDonald这种流文档内容打印的方式以及他的书中描述的更高级的技术Pro WPF 4.5 in C# Windows Presentation Foundation in .NET 4.5(第29章).