Mar*_*cke 0 printing wpf textbox
我正在使用 WPF 开发文本编辑器,并尝试使用以下代码来打印文本框的内容:
PrintDialog pd = new PrintDialog();
if ((pd.ShowDialog() == true))
{
RichTextBox richTB = new RichTextBox();
richTB.Document.Blocks.Add(new Paragraph(new Run(TBXEditor.Text)));
//use either one of the below
pd.PrintVisual(richTB as Visual, "printing as visual");
pd.PrintDocument((((IDocumentPaginatorSource)richTB.Document).DocumentPaginator), "printing as paginator");
}
Run Code Online (Sandbox Code Playgroud)
它不好用。如果我单击打印菜单一次,我会打印两张并且没有左边距。行首的文本未完全打印
有没有人有更好的解决方案?
You're getting two prints because you're calling two print methods (pd.PrintVisual and pd.PrintDocument). For margin, you need to set Padding for your FlowDocument. You can refer the below code, which works as you expected.
Also, you don't need to create RichTextBox and access the FlowDocument inside that. Instead you can create FlowDocument and work with that itself.
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
FlowDocument flowDocument = new FlowDocument();
flowDocument.PagePadding = new Thickness(50);
flowDocument.Blocks.Add(new Paragraph(new Run(TBXEditor.Text)));
printDialog.PrintDocument((((IDocumentPaginatorSource)flowDocument).DocumentPaginator), "Using Paginator");
}
Run Code Online (Sandbox Code Playgroud)