Skip to content

Instantly share code, notes, and snippets.

@Mywk
Created July 3, 2021 20:58
Show Gist options
  • Save Mywk/109dcd29098107299e0385511334ec26 to your computer and use it in GitHub Desktop.
Save Mywk/109dcd29098107299e0385511334ec26 to your computer and use it in GitHub Desktop.
FlowDocument Converter - To create a bitmap from a RichTextBox document
public class FlowDocumentConverter
{
/// <summary>
/// Converts a FlowDocument to a bitmap you can save or print
/// </summary>
/// <remarks>
/// No longer used
/// </remarks>
/// <param name="document"></param>
/// <param name="size"></param>
/// <returns></returns>
public Bitmap FlowDocumentToBitmap(FlowDocument document, System.Windows.Size size)
{
// Clone document first
var clonedDocument = new FlowDocument();
{
var sourceRange = new TextRange(document.ContentStart, document.ContentEnd);
var targetRange = new TextRange(clonedDocument.ContentStart, clonedDocument.ContentEnd);
using (var stream = new MemoryStream())
{
sourceRange.Save(stream, DataFormats.XamlPackage);
targetRange.Load(stream, DataFormats.XamlPackage);
}
}
DocumentPaginator paginator = ((IDocumentPaginatorSource)clonedDocument).DocumentPaginator;
paginator.PageSize = size;
paginator.ComputePageCount();
var container = new DrawingVisual();
using (var drawingContext = container.RenderOpen())
{
// Draw white background
drawingContext.DrawRectangle(Brushes.White, null, new Rect(0, 0, size.Width, size.Height * paginator.PageCount));
for (int i = 0; i < paginator.PageCount; i++)
{
var visual = paginator.GetPage(i).Visual;
var tempBitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height * paginator.PageCount,
96, 96, PixelFormats.Pbgra32);
tempBitmap.Render(visual);
// Don't even ask, the way DrawingContext works is weird to me as I'm not used to do graphics like this
const int lineHeightFix = 36;
drawingContext.DrawImage(tempBitmap, new Rect(0, (size.Height * i) - (i != 0 ? (lineHeightFix * i) : 0), size.Width, size.Height * paginator.PageCount));
}
}
// Create RenderTargetBitmap
var bitmapTargetBitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height * paginator.PageCount,
96, 96, PixelFormats.Pbgra32);
bitmapTargetBitmap.Render(container);
// Convert it into something we can use
Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapTargetBitmap));
enc.Save(outStream);
var tmpBitmap = (new System.Drawing.Bitmap(outStream));
bitmap = tmpBitmap.Clone(new System.Drawing.Rectangle(0, 0, tmpBitmap.Width, tmpBitmap.Height), System.Drawing.Imaging.PixelFormat.Format32bppArgb); ;
}
return bitmap;
}
/// Usage example
public Bitmap GenerateScreenshot()
{
return FlowDocumentToBitmap(richTextBox.Document, new System.Windows.Size(richTextBox.ActualWidth, richTextBox.ActualHeight));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment