以类似于Winforms的WPF打印

本文关键字:WPF 打印 Winforms 类似于 | 更新日期: 2023-09-27 18:28:58

下面是我在Windows表单中进行打印的过程。我使用了PrintDocument类。它包含PrintPage事件,我用它来绘制我需要打印的图形,并成功地获得了预期的结果。

以下是代码:

public PrintDocument Printing
{
   m_printDocument = new PrintDocument();
   m_printDocument.PrintPage += new PrintPageEventHandler(OnPrintPage);
}

OnPrintPage的代码如下:

protected virtual void OnPrintPage(object sender, PrintPageEventArgs e)
 {
      //Image img = I have the things to be printing in the form of image.
      e.Graphics.DrawImage(img, new Point(0,0));
 }

在WPF:

我正在使用固定文档,通过使用以下代码我可以打印

PrintDialog print = new PrintDialog();
print.PrintDocument(FixedDocument.DocumentPaginator, "Print") //Where Fixed document contains the data to be printed.

这导致内存不足,无法继续执行程序。但我得到了修复文件没有任何问题。有什么解决方案。。。?我希望类似Windows窗体的东西也会出现在WPF中。。。

以类似于Winforms的WPF打印

当我的页面包含大量视觉元素(绘图/图像/复杂图表)时,我经常会得到这个。而不是一次打印完整的文档(这可能导致内存不足)

print.PrintDocument(FixedDocument.DocumentPaginator, "Print")

我打印了其中一页。

 PrintQueue selectedPrntQueue = printDialog.PrintQueue;     
 XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(selectedPrntQueue);
 SerializerWriterCollator collator = writer.CreateVisualsCollator();
 collator.BeginBatchWrite();
 var paginator = FixedDocument.DocumentPaginator;
 FixedPage fixedPage = paginator.GetFixedPage(printedPageCount)
 ContainerVisual newPage = new ContainerVisual();
 Size sz = new Size(pageSize.Height.Value, pageSize.Width.Value);
 fixedPage.Measure(sz);
 fixedPage.Arrange(new Rect(new Point(), sz));
 fixedPage.UpdateLayout();
 newPage.Children.Add(fixedPage);
 collator.Write(newPage);

打印了几页后,我不得不做GC(我的神奇数字是10)。您可能需要根据自己的要求对其进行调整。