Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: The font will not change on a printed FlowDocument

Tags:

c#

wpf

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.

like image 447
Snoop Avatar asked Aug 03 '16 14:08

Snoop


1 Answers

I try your code and found when I remove this line and then change the r.FontSize to 50, it seems work.

pg.LineHeight = 0;
like image 110
zzczzc004 Avatar answered Oct 03 '22 20:10

zzczzc004