简体   繁体   中英

WPF: The font will not change on a printed FlowDocument

I am trying to print the contents of a rich-text box. I do that in the following way:

  1. Obtain a TextRange from the FlowDocument .
  2. Create a new FlowDocument with a smaller font using the TextRange .
  3. Send this new FlowDocument to the printer.

My problem, is that the font doesn't seem to change. I would like it to go down to size 8. Instead, it remains at a fixed size. Here is my code:

private void button_Print_Click(object sender, RoutedEventArgs e)
{
    IDocumentPaginatorSource ps = null;
    FlowDocument fd = new FlowDocument();
    PrintDialog pd = new PrintDialog();
    Paragraph pg = new Paragraph();
    Style style = new Style(typeof(Paragraph));
    Run r = null;
    string text = string.Empty;

    // get the text
    text = new TextRange(
        this.richTextBox_Info.Document.ContentStart,
        this.richTextBox_Info.Document.ContentEnd).Text;

    // configure the style of the flow document
    style.Setters.Add(new Setter(Block.MarginProperty, new Thickness(0)));
    fd.Resources.Add(typeof(Paragraph), style);

    // style the paragraph
    pg.LineHeight = 0;
    pg.LineStackingStrategy = LineStackingStrategy.BlockLineHeight;
    pg.FontFamily = new FontFamily("Courier New");
    pg.TextAlignment = TextAlignment.Left;
    pg.FontSize = 8;

    // create the paragraph
    r = new Run(text);
    r.FontFamily = new FontFamily("Courier New");
    r.FontSize = 8;
    pg.Inlines.Add(r);

    // add the paragraph to the document
    fd.Blocks.Add(pg);
    ps = fd;

    // format the page
    fd.PagePadding = new Thickness(50);
    fd.ColumnGap = 0;
    fd.ColumnWidth = pd.PrintableAreaWidth;

    // print the document
    if (pd.ShowDialog().Value == true)
    {
        pd.PrintDocument(ps.DocumentPaginator, "Information Box");
    }
}

I would like to add that, changing the font works just fine for the flow-document when it is inside of the rich-text box. However, when I am doing it programmatically (as shown above) I run into problems.

我尝试你的代码,发现当我删除这一行,然后将r.FontSize更改为50,它似乎工作。

pg.LineHeight = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM