Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

c# - Saving RichTextBox FlowDocument to image

i'am making a programm where i want my RichTextBox content (text+images) to be saved as an image (jpg/png). I tried to use this solution but i get only black filled image from

SaveUIAsGraphicFile() 

I also tried to create FormattedText from my rtb control, printing it works fine, but its not possible to insert images in there. Maybe it is possible to print FlowDocument somehow?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use something like the following method to create a bitmap from a FlowDocument:

public BitmapSource FlowDocumentToBitmap(FlowDocument document, Size size)
{
    document = CloneDocument(document);

    var paginator = ((IDocumentPaginatorSource)document).DocumentPaginator;
    paginator.PageSize = size;

    var visual = new DrawingVisual();
    using (var drawingContext = visual.RenderOpen())
    {
        // draw white background
        drawingContext.DrawRectangle(Brushes.White, null, new Rect(size));
    }
    visual.Children.Add(paginator.GetPage(0).Visual);

    var bitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height,
                                        96, 96, PixelFormats.Pbgra32);
    bitmap.Render(visual);
    return bitmap;
}

public FlowDocument CloneDocument(FlowDocument document)
{
    var copy = new FlowDocument();
    var sourceRange = new TextRange(document.ContentStart, document.ContentEnd);
    var targetRange = new TextRange(copy.ContentStart, copy.ContentEnd);

    using (var stream = new MemoryStream())
    {
        sourceRange.Save(stream, DataFormats.XamlPackage);
        targetRange.Load(stream, DataFormats.XamlPackage);
    }

    return copy;
}

and then use it like shown below to save a RichTextBox's Document to an image file.

var doc = richTextBox.Document;
var bm = FlowDocumentToBitmap(doc, new Size(richTextBox.ActualWidth, richTextBox.ActualHeight));
var encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bm));

using (var stream = new FileStream("doc.jpg", FileMode.Create))
{
    encoder.Save(stream);
}   

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...