wpf 将 RichTextBox FlowDocument 保存为图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14895745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving RichTextBox FlowDocument to image
提问by AutumnKnight
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 solutionbut i get only black filled image from
我正在制作一个程序,我希望将 RichTextBox 内容(文本+图像)另存为图像(jpg/png)。我试图使用这个解决方案,但我只得到黑色填充的图像
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?
我还尝试从我的 rtb 控件创建 FormattedText,打印它工作正常,但无法在其中插入图像。也许可以以某种方式打印 FlowDocument?
回答by Clemens
You could use something like the following method to create a bitmap from a FlowDocument:
您可以使用类似于以下方法的方法从 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.
然后使用如下所示将 RichTextBox 的文档保存到图像文件中。
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);
}
回答by Clint StLaurent


You can spend HOURS chasing around trying to figure out why the width is wrong when in reality its trying to paginate in columns. Set the document's columnwidth to the full width of your output bitmap.
你可以花 HOURS 四处寻找,试图找出为什么宽度是错误的,而实际上它试图在列中分页。将文档的列宽设置为输出位图的全宽。
public Bitmap FlowDocumentToBitmap(FlowDocument document, Size size)
{
document = CloneDocument(document);
document.ColumnWidth = size.Width;// <- Add this line

