gpt4 book ai didi

wpf - 打印 WPF FlowDocument

转载 作者:行者123 更新时间:2023-12-03 08:28:16 30 4
gpt4 key购买 nike

我正在用 WPF 构建一个演示应用程序,这对我来说是新的。我目前在 FlowDocument 中显示文本,需要打印它。

我正在使用的代码如下所示:

        PrintDialog pd = new PrintDialog();
fd.PageHeight = pd.PrintableAreaHeight;
fd.PageWidth = pd.PrintableAreaWidth;
fd.PagePadding = new Thickness(50);
fd.ColumnGap = 0;
fd.ColumnWidth = pd.PrintableAreaWidth;

IDocumentPaginatorSource dps = fd;
pd.PrintDocument(dps.DocumentPaginator, "flow doc");

fd 是我的 FlowDocument,现在我使用默认打印机而不是允许用户指定打印选项。它工作正常,除了文档打印后,屏幕上显示的 FlowDocument 已更改为使用我指定的打印设置。

我可以通过在打印后手动重置所有内容来解决此问题,但这是最好的方法吗?在打印 FlowDocument 之前,我应该制作它的副本吗?或者我应该考虑另一种方法吗?

最佳答案

是的,在打印之前制作 FlowDocument 的副本。这是因为分页和边距会不同。这对我有用。

    private void DoThePrint(System.Windows.Documents.FlowDocument document)
{
// Clone the source document's content into a new FlowDocument.
// This is because the pagination for the printer needs to be
// done differently than the pagination for the displayed page.
// We print the copy, rather that the original FlowDocument.
System.IO.MemoryStream s = new System.IO.MemoryStream();
TextRange source = new TextRange(document.ContentStart, document.ContentEnd);
source.Save(s, DataFormats.Xaml);
FlowDocument copy = new FlowDocument();
TextRange dest = new TextRange(copy.ContentStart, copy.ContentEnd);
dest.Load(s, DataFormats.Xaml);

// Create a XpsDocumentWriter object, implicitly opening a Windows common print dialog,
// and allowing the user to select a printer.

// get information about the dimensions of the seleted printer+media.
System.Printing.PrintDocumentImageableArea ia = null;
System.Windows.Xps.XpsDocumentWriter docWriter = System.Printing.PrintQueue.CreateXpsDocumentWriter(ref ia);

if (docWriter != null && ia != null)
{
DocumentPaginator paginator = ((IDocumentPaginatorSource)copy).DocumentPaginator;

// Change the PageSize and PagePadding for the document to match the CanvasSize for the printer device.
paginator.PageSize = new Size(ia.MediaSizeWidth, ia.MediaSizeHeight);
Thickness t = new Thickness(72); // copy.PagePadding;
copy.PagePadding = new Thickness(
Math.Max(ia.OriginWidth, t.Left),
Math.Max(ia.OriginHeight, t.Top),
Math.Max(ia.MediaSizeWidth - (ia.OriginWidth + ia.ExtentWidth), t.Right),
Math.Max(ia.MediaSizeHeight - (ia.OriginHeight + ia.ExtentHeight), t.Bottom));

copy.ColumnWidth = double.PositiveInfinity;
//copy.PageWidth = 528; // allow the page to be the natural with of the output device

// Send content to the printer.
docWriter.Write(paginator);
}

}

关于wpf - 打印 WPF FlowDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/345009/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com