1
我正在嘗試實現WPF打印功能。只要用戶不想在一頁上打印更多的內容,它就會工作。我的應用程序使用戶能夠在運行時創建xaml。現在我想讓他打印他創建的xaml控件。wpf打印多頁xaml控件
我檢查了所有xaml控件的總高度,由pageheight和ceiled分開,因此我知道需要打印多少頁。
接下來,我爲每個頁面創建一個FrameworkElements列表(請參閱下面的邏輯),並將每個List(每個List代表一個頁面)存儲在一個數組中。
最後,我想創建一個包含每個頁面的預覽,並使用戶能夠打印所有頁面。爲了做到這一點,我不得不把頁面放在一起到一個文件,但我不知道如何。請看看我的代碼:
Package package = Package.Open("test.xps", FileMode.Create);
// Create new xps document based on the package opened
XpsDocument doc = new XpsDocument(package);
// Create an instance of XpsDocumentWriter for the document
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
// Write the canvas (as Visual) to the document
double height = element.ActualHeight;
double width = element.ActualWidth;
System.Windows.Controls.PrintDialog printDlg = new System.Windows.Controls.PrintDialog();
Size pageSize = new Size(printDlg.PrintableAreaWidth, printDlg.PrintableAreaHeight);
int pageCount = (int)Math.Ceiling(height/pageSize.Height);
if (pageSize.Height < height) {
var grid = element as Grid;
var children = grid.Children;
List<FrameworkElement>[] pages = new List<FrameworkElement>[pageCount-1];
int i = 0;
double currentHeight = 0;
foreach (FrameworkElement c in children) {
currentHeight += c.RenderSize.Height;
if (currentHeight < pageSize.Height) {
pages[i] = new List<FrameworkElement>();
pages[i].Add(c);
}
else {
i++;
currentHeight = 0;
pages[i] = new List<FrameworkElement>();
pages[i].Add(c);
}
}
for (int j = 0; j < pageCount; j++) {
var collator = writer.CreateVisualsCollator();
collator.BeginBatchWrite();
foreach (FrameworkElement c in pages[j]) {
collator.Write(c);
}
collator.EndBatchWrite();
}
}
doc.Close();
package.Close();
string filename = @"C:\Users\rzimmermann\Documents\Visual Studio 2012\Projects\MvvmLightPrintFunction\MvvmLightPrintFunction\bin\Debug\test.xps";
DocumentViewer viewer = new DocumentViewer();
doc = new XpsDocument(filename, FileAccess.Read);
viewer.Document = doc.GetFixedDocumentSequence();
Window ShowWindow = new Window();
ShowWindow.Width = 400;
ShowWindow.Height = 300;
ShowWindow.Content = viewer;
ShowWindow.Show();
非常感謝。
自從我做了它已經太久了,但正如我記得爲每個頁面創建一個FixedPage http://msdn.microsoft.com/en-us/library/system.windows.documents.fixedpage.aspx。 – kenny