Save WPF control as XPS and fit it into an A4 papersize page.

NET%20LogoA little code snippet to export to XPS a WPF control, for instance your view, and fit it into an A4 standard page, in example for printing purpose. (in this case, take care of the margins !!)

public void SaveCurrentViewToXPS()
{
	// Configure save file dialog box
	Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
	dlg.FileName = String.Format("MyFile{0:ddMMyyyyHHmmss}", DateTime.Now); // Default file name
	dlg.DefaultExt = ".xps"; // Default file extension
	dlg.Filter = "XPS Documents (.xps)|*.xps"; // Filter files by extension

	// Show save file dialog box
	Nullable<bool> result = dlg.ShowDialog();

	// Process save file dialog box results
	if (result == true)
	{
		// Save document
		string filename = dlg.FileName;

		// Initialize the xps document structure
		FixedDocument fixedDoc = new FixedDocument();
		PageContent pageContent = new PageContent();
		FixedPage fixedPage = new FixedPage();

		// Create the document and set the datacontext
		AnalysisView view = new AnalysisView();                
		view.DataContext = theControlDataContext;
		view.UpdateLayout();
		
		// Get the page size of an A4 document
		var pageSize = new Size(8.5 * 96.0, 11.0 * 96.0);
		
		// We just fit it horizontally, so only the width is set here
		//view.Height = pageSize.Height;
		view.Width = pageSize.Width;
		view.UpdateLayout();

		//Create first page of document
		fixedPage.Children.Add(view);
		((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
		fixedDoc.Pages.Add(pageContent);
		
		// Create the xps file and write it
		XpsDocument xpsd = new XpsDocument(filename, FileAccess.ReadWrite);
		XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd);
		xw.Write(fixedDoc);
		xpsd.Close();
	}
}

Published by Emmanuel Istace

Musician, Software developer and guitar instructor. https://emmanuelistace.be/

One thought on “Save WPF control as XPS and fit it into an A4 papersize page.

  1. i am trying to use the analysis view object, but i am getting a namespace error, im not sure what i need to reference in order to use the analysisView??

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: