public PrintPreviewWindow(FlowDocument source) { this.InitializeComponent(); source.ColumnWidth = double.PositiveInfinity; // Create a package for the XPS document MemoryStream packageStream = new(); Package package = Package.Open(packageStream, FileMode.Create, FileAccess.ReadWrite); // Create a XPS document with the path "pack://temp.xps" PackageStore.AddPackage(new Uri(this.packagePath), package); XpsDocument xpsDocument = new(package, CompressionOption.SuperFast, this.packagePath); // Serialize the XPS document XpsSerializationManager serializer = new(new XpsPackagingPolicy(xpsDocument), false); DocumentPaginator paginator = ((IDocumentPaginatorSource)source).DocumentPaginator; serializer.SaveAsXaml(paginator); // Get the fixed document sequence FixedDocumentSequence documentSequence = xpsDocument.GetFixedDocumentSequence(); this.documentViewer.Document = documentSequence; this.documentViewer.FitToHeight(); }
private static XpsDocument convertVisualToXps(FrameworkElement visual) { visual.Measure(new Size(Int32.MaxValue, Int32.MaxValue)); Size visualSize = visual.DesiredSize; visual.Arrange(new Rect(new Point(0, 0), visualSize)); MemoryStream stream = new MemoryStream(); string pack = "pack://temp.xps"; Uri uri = new Uri(pack); DocumentPaginator paginator; XpsDocument xpsDoc; using (Package container = Package.Open(stream, FileMode.Create)) { PackageStore.AddPackage(uri, container); using (xpsDoc = new XpsDocument(container, CompressionOption.Fast, pack)) { XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false); rsm.SaveAsXaml(visual); paginator = ((IDocumentPaginatorSource)xpsDoc.GetFixedDocumentSequence()).DocumentPaginator; paginator.PageSize = visualSize; } PackageStore.RemovePackage(uri); } return(xpsDoc); }
public void Print() { MemoryStream xpsStream = new MemoryStream(); Package pack = Package.Open(xpsStream, FileMode.CreateNew); string inMemPackageName = "memorystream://myXps.xps"; Uri packageUri = new Uri(inMemPackageName); PackageStore.AddPackage(packageUri, pack); XpsDocument xpsDoc = new XpsDocument(pack, CompressionOption.SuperFast, inMemPackageName); XpsDocumentWriter xpsDocWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc); FixedDocument doc = CreatePawnTicket(); //DocumentPaginator documentPaginator = (FlowDocument)IDocumentPaginatorSource).DocumentPaginator; //documentPaginator = New DocumentPaginatorWrapper(documentPaginator, pageSize, margin, documentStatus, firstPageHeaderPath, primaryHeaderPath) xpsDocWriter.Write(doc); //Package package = //XpsDocument xpsd = new XpsDocument((filename, FileAccess.ReadWrite); // //XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd); // xw.Write(doc); // xpsd.Close(); }
/// <summary> /// Helper method to create page header or footer from flow document template /// </summary> /// <param name="data">enumerable report data</param> /// <param name="fileName">file to save XPS to</param> /// <returns></returns> public XpsDocument CreateXpsDocument(IEnumerable <ReportData> data, string fileName) { if (data == null) { throw new ArgumentNullException("data"); } int count = 0; ReportData firstData = null; foreach (ReportData rd in data) { if (firstData == null) { firstData = rd; } count++; } if (count == 1) { return(CreateXpsDocument(firstData)); // we have only one ReportData object -> use the normal ReportPaginator instead } Package pkg = Package.Open(fileName, FileMode.Create, FileAccess.ReadWrite); string pack = "pack://report.xps"; PackageStore.RemovePackage(new Uri(pack)); PackageStore.AddPackage(new Uri(pack), pkg); XpsDocument doc = new XpsDocument(pkg, _xpsCompressionOption, pack); XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false); MultipleReportPaginator rp = new MultipleReportPaginator(this, data); rsm.SaveAsXaml(rp); rsm.Commit(); pkg.Close(); return(new XpsDocument(fileName, FileAccess.Read)); }
public static FixedDocumentSequence PaintDrawingVisual(DrawingVisual drawingVisual, PageMediaSize pageMediaSize) { FixedDocumentSequence document = null; using (var xpsStream = new MemoryStream()) { using (var package = Package.Open(xpsStream, FileMode.Create, FileAccess.ReadWrite)) { var packageUriString = "memorystream://data.xps"; var packageUri = new Uri(packageUriString); PackageStore.AddPackage(packageUri, package); var xpsDocument = new XpsDocument(package, CompressionOption.Maximum, packageUriString); var writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); var printTicket = new PrintTicket(); printTicket.PageMediaSize = pageMediaSize; writer.Write(drawingVisual, printTicket); document = xpsDocument.GetFixedDocumentSequence(); xpsDocument.Close(); PackageStore.RemovePackage(packageUri); } } return(document); }
public IEnumerable <Bitmap> ToBitmap(Parameters parameters) { var pages = new List <Bitmap>(); var thread = new Thread(() => { const string inMemoryPackageName = "memorystream://inmemory.xps"; var packageUri = new Uri(inMemoryPackageName); using (var package = Package.Open(_xpsDocumentInMemoryStream)) { PackageStore.AddPackage(packageUri, package); _xpsDocument = new XpsDocument(package, CompressionOption.Normal, inMemoryPackageName); _xpsDocumentPaginator = _xpsDocument.GetFixedDocumentSequence().DocumentPaginator; for (var docPageNumber = 0; docPageNumber < PageCount; docPageNumber++) { pages.Add(ProcessPage(parameters, docPageNumber)); } PackageStore.RemovePackage(packageUri); _xpsDocument.Close(); _xpsDocument = null; } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); return(pages); }
/// <summary> /// Helper method to create page header or footer from flow document template /// </summary> /// <param name="data">enumerable report data</param> /// <returns></returns> /// <exception cref="ArgumentNullException">data</exception> public XpsDocument CreateXpsDocument(IEnumerable <ReportData> data) { if (data == null) { throw new ArgumentNullException("data"); } int count = 0; ReportData firstData = null; foreach (ReportData rd in data) { if (firstData == null) { firstData = rd; } count++; } if (count == 1) { return(CreateXpsDocument(firstData)); // we have only one ReportData object -> use the normal ReportPaginator instead } MemoryStream ms = new MemoryStream(); Package pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); string pack = "pack://report.xps"; PackageStore.RemovePackage(new Uri(pack)); PackageStore.AddPackage(new Uri(pack), pkg); XpsDocument doc = new XpsDocument(pkg, CompressionOption.NotCompressed, pack); XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false); DocumentPaginator paginator = ((IDocumentPaginatorSource)CreateFlowDocument()).DocumentPaginator; MultipleReportPaginator rp = new MultipleReportPaginator(this, data); rsm.SaveAsXaml(rp); return(doc); }
public void LoadXps() { //构造一个基于内存的xps document //MemoryStream ms = new MemoryStream(); Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); Uri DocumentUri = new Uri("pack://InMemoryDocument.xps"); PackageStore.RemovePackage(DocumentUri); PackageStore.AddPackage(DocumentUri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, DocumentUri.AbsoluteUri); //将flow document写入基于内存的xps document中去 XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); if (this.isFixedPage) { writer.Write((FixedPage)m_doc); } else { writer.Write(((IDocumentPaginatorSource)m_doc).DocumentPaginator); } //获取这个基于内存的xps document的fixed document docViewer.Document = xpsDocument.GetFixedDocumentSequence(); //关闭基于内存的xps document xpsDocument.Close(); }
} // end:Constructor() #endregion #region Public Methods /// <summary> /// Update the file package reference that this XpsDocument /// is loaded from. /// </summary> public void UpdatePackageReference(Stream data, string path) { SiliconStudio.DebugManagers.DebugReporter.Report( SiliconStudio.DebugManagers.MessageType.Information, "Updating Package Reference", "\nPath: " + path); this._xpsDocumentPath = path; this._packageUri = new Uri(path, UriKind.Absolute); data.Seek(0, SeekOrigin.Begin); this._xpsPackage = Package.Open(data, FileMode.Open, FileAccess.ReadWrite); try { PackageStore.AddPackage(this._packageUri, this._xpsPackage); this._xpsDocument = new XpsDocument(this._xpsPackage, CompressionOption.Maximum, path); this.GetFixedDocumentSequenceUri(); } catch (Exception ex) { SiliconStudio.DebugManagers.DebugReporter.Report( SiliconStudio.DebugManagers.MessageType.Error, "Failed to Update Package Reference", "\nPath: " + path + "\nError: " + ex.Message); throw; } }
private void ShowPrintPreview() { // We have to clone the FlowDocument before we use different pagination settings for the export. RichTextDocument document = (RichTextDocument)fileService.ActiveDocument; FlowDocument clone = document.CloneContent(); clone.ColumnWidth = double.PositiveInfinity; // Create a package for the XPS document MemoryStream packageStream = new MemoryStream(); package = Package.Open(packageStream, FileMode.Create, FileAccess.ReadWrite); // Create a XPS document with the path "pack://temp.xps" PackageStore.AddPackage(new Uri(PackagePath), package); xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, PackagePath); // Serialize the XPS document XpsSerializationManager serializer = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false); DocumentPaginator paginator = ((IDocumentPaginatorSource)clone).DocumentPaginator; serializer.SaveAsXaml(paginator); // Get the fixed document sequence FixedDocumentSequence documentSequence = xpsDocument.GetFixedDocumentSequence(); // Create and show the print preview view PrintPreviewViewModel printPreviewViewModel = printPreviewViewModelFactory.CreateExport().Value; printPreviewViewModel.Document = documentSequence; previousView = shellViewModel.ContentView; shellViewModel.ContentView = printPreviewViewModel.View; shellViewModel.IsPrintPreviewVisible = true; printPreviewCommand.RaiseCanExecuteChanged(); }
public static byte[] XpsDocumentToBytes(FixedDocumentSequence fds) { string uriString = "pack://" + Guid.NewGuid().ToString() + ".xps"; Uri uri = new Uri(uriString); MemoryStream stream = new MemoryStream(); Package package = Package.Open(stream, FileMode.Create); PackageStore.AddPackage(uri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Maximum, uriString); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); writer.Write(fds); xpsDocument.Close(); package.Close(); stream.Close(); PackageStore.RemovePackage(uri); MemoryStream mainstream = new MemoryStream(); BinaryWriter br = new BinaryWriter(mainstream); byte[] data = stream.ToArray(); br.Write(uriString); br.Write(data.Length); br.Write(data); br.Flush(); mainstream.Close(); return(mainstream.ToArray()); }
private void ButtonClickToParse(object sender, RoutedEventArgs e) { documentMenu.Visibility = Visibility.Visible; tableHistoryMenu.Visibility = Visibility.Collapsed; var fixedDocument = new FixedDocument(); var pageContent = new PageContent(); var fixedPage = new FixedPage(); DataGrid dataGrid = new DataGrid(); using (ShopContext shopContext = new ShopContext()) { dataGrid.ItemsSource = shopContext.HistoryBuy.ToList(); } fixedPage.Children.Add(dataGrid); pageContent.Child = fixedPage; fixedDocument.Pages.Add(pageContent); var stream = new MemoryStream(); var uri = new Uri("pack://document.xps"); var package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite); PackageStore.AddPackage(uri, package); var xpsDoc = new XpsDocument(package, CompressionOption.NotCompressed, uri.AbsoluteUri); var docWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc); docWriter.Write(fixedDocument); documentViewer.Document = xpsDoc.GetFixedDocumentSequence(); }
private void cmdShowFlow_Click(object sender, RoutedEventArgs e) { // Load the XPS content into memory. MemoryStream ms = new MemoryStream(); Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); Uri DocumentUri = new Uri("pack://InMemoryDocument.xps"); PackageStore.AddPackage(DocumentUri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, DocumentUri.AbsoluteUri); // Load the XPS content into a temporary file (alternative approach). //if (File.Exists("test2.xps")) File.Delete("test2.xps"); // XpsDocument xpsDocument = new XpsDocument("test2.xps", FileAccess.ReadWrite); using (FileStream fs = File.Open("FlowDocument1.xaml", FileMode.Open)) { FlowDocument doc = (FlowDocument)XamlReader.Load(fs); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); writer.Write(((IDocumentPaginatorSource)doc).DocumentPaginator); // Display the new XPS document in a viewer. docViewer.Document = xpsDocument.GetFixedDocumentSequence(); xpsDocument.Close(); } }
static int _wpfPayloadCount; // used to disambiguate between all acts of loading from different WPF payloads. internal static object LoadElement(Stream stream) { Package package = Package.Open(stream, FileMode.Open, FileAccess.Read); WpfPayload wpfPayload = new WpfPayload(package); PackagePart xamlEntryPart = wpfPayload.GetWpfEntryPart(); int newWpfPayoutCount = _wpfPayloadCount++; Uri payloadUri = new Uri("payload://wpf" + newWpfPayoutCount, UriKind.Absolute); Uri entryPartUri = PackUriHelper.Create(payloadUri, xamlEntryPart.Uri); // gives an absolute uri of the entry part Uri packageUri = PackUriHelper.GetPackageUri(entryPartUri); // extracts package uri from combined package+part uri PackageStore.AddPackage(packageUri, wpfPayload.Package); // Register the package ParserContext parserContext = new ParserContext(); parserContext.BaseUri = entryPartUri; object xamlObject = XamlReader.Load(xamlEntryPart.GetStream(), parserContext); // Remove the temporary uri from the PackageStore PackageStore.RemovePackage(packageUri); return(xamlObject); }
private void DownloadXpsDoc(Uri theUri, string Name) { System.Net.WebClient client = new WebClient(); try { //Download the document byte[] XpsBytes = client.DownloadData(theUri); MemoryStream xpsStream = new MemoryStream(XpsBytes); Package package = Package.Open(xpsStream); //Create URI for the package Uri packageUri = new Uri(theUri.ToString()); //Need to add the Package to the PackageStore PackageStore.AddPackage(packageUri, package); //Create instance of XpsDocument XpsDocument document = new XpsDocument(package, CompressionOption.Maximum, theUri.ToString()); //Do the operation on document here //Here I am viewing the document in the DocViewer FixedDocumentSequence fixedDocumentSequence = document.GetFixedDocumentSequence(); //To view in the DocViewer DocReader.Document = fixedDocumentSequence as IDocumentPaginatorSource; //Remember to keep the Package object in PackageStore until all operations complete on document. //Remove the package from store PackageStore.RemovePackage(packageUri); //Close the Document document.Close(); } catch (XamlParseException ex) { MessageBox.Show(ex.Message, "XamlParseException", MessageBoxButton.OK); } }
private async void DisplayFile(string file) { string rawXamlText; using (StreamReader streamReader = File.OpenText(file)) { rawXamlText = streamReader.ReadToEnd(); } var flowDocument = XamlReader.Load(new XmlTextReader(new StringReader(rawXamlText))) as FlowDocument; DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator; Package package = Package.Open(new MemoryStream(), FileMode.Create, FileAccess.ReadWrite); var packUri = new Uri("pack://temp.xps"); PackageStore.RemovePackage(packUri); PackageStore.AddPackage(packUri, package); var xps = new XpsDocument(package, CompressionOption.NotCompressed, packUri.ToString()); XpsDocument.CreateXpsDocumentWriter(xps).Write(paginator); FixedDocument fixedDocument = xps.GetFixedDocumentSequence().References[0].GetDocument(true); await Dispatcher.BeginInvoke( new Action(() => { documentViewer.Document = fixedDocument; documentViewer.Zoom = 125; })); }
public static void SaveToPdf(this FlowDocument flowDoc, string filename) { MemoryStream xamlStream = new MemoryStream(); XamlWriter.Save(flowDoc, xamlStream); File.WriteAllBytes("d:\\file.xaml", xamlStream.ToArray()); IDocumentPaginatorSource text = flowDoc as IDocumentPaginatorSource; xamlStream.Close(); MemoryStream memoryStream = new MemoryStream(); Package pkg = Package.Open(memoryStream, FileMode.Create, FileAccess.ReadWrite); string pack = "pack://temp.xps"; PackageStore.AddPackage(new Uri(pack), pkg); XpsDocument doc = new XpsDocument(pkg, CompressionOption.SuperFast, pack); XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false); DocumentPaginator pgn = text.DocumentPaginator; rsm.SaveAsXaml(pgn); MemoryStream xpsStream = new MemoryStream(); var writer = new XpsSerializerFactory().CreateSerializerWriter(xpsStream); writer.Write(doc.GetFixedDocumentSequence()); MemoryStream outStream = new MemoryStream(); NiXPS.Converter.XpsToPdf(xpsStream, outStream); File.WriteAllBytes("file.pdf", outStream.ToArray()); }
/// <summary> /// CHOOSING PRINT TO PAPER OR PRINT TO WINDOWS /// </summary> /// <param name="doc"></param> private void PrintToReal(FlowDocument doc) { // Create IDocumentPaginatorSource from FlowDocument IDocumentPaginatorSource idpSource = doc; if (!isShowReview) { // Call PrintDocument method to send document to printer printDlg.PrintDocument(idpSource.DocumentPaginator, "bill printing"); } else { // convert FlowDocument to FixedDocument var paginator = idpSource.DocumentPaginator; var package = Package.Open(new MemoryStream(), FileMode.Create, FileAccess.ReadWrite); var packUri = new Uri("pack://temp.xps"); PackageStore.RemovePackage(packUri); PackageStore.AddPackage(packUri, package); var xps = new XpsDocument(package, CompressionOption.NotCompressed, packUri.ToString()); XpsDocument.CreateXpsDocumentWriter(xps).Write(paginator); FixedDocument fdoc = xps.GetFixedDocumentSequence().References[0].GetDocument(true); DocumentViewer previewWindow = new DocumentViewer { Document = fdoc }; Window printpriview = new Window(); printpriview.Content = previewWindow; printpriview.Title = "Print Preview"; printpriview.Show(); } }
// Print Preview public void PrintPreview(FixedDocument fixeddocument, CancellationToken ct) { // Was cancellation already requested? if (ct.IsCancellationRequested) { ct.ThrowIfCancellationRequested(); } MemoryStream ms = new MemoryStream(); using (Package p = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite)) { Uri u = new Uri("pack://TemporaryPackageUri.xps"); PackageStore.AddPackage(u, p); XpsDocument doc = new XpsDocument(p, CompressionOption.Maximum, u.AbsoluteUri); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc); //writer.Write(fixeddocument.DocumentPaginator); Dispatcher.Invoke(new Action <DocumentPaginator>(writer.Write), fixeddocument.DocumentPaginator); FixedDocumentSequence fixedDocumentSequence = doc.GetFixedDocumentSequence(); var previewWindow = new PrintPreview(fixedDocumentSequence); Action closeAction = () => previewWindow.Close(); ct.Register(() => previewWindow.Dispatcher.Invoke(closeAction) ); previewWindow.ShowDialog(); PackageStore.RemovePackage(u); doc.Close(); } }
} // end:Constructor() public ejpXpsDocument(Stream data, string path, bool isExternalToAssignment, Guid parentStudyId) { SiliconStudio.DebugManagers.DebugReporter.Report( SiliconStudio.DebugManagers.MessageType.Information, "Creating new Document", "Creating ejp wrapper for xps document with path: " + path); this._isExternalToAssignment = isExternalToAssignment; this._xpsDocumentPath = path; this._packageUri = new Uri(path, UriKind.Absolute); data.Seek(0, SeekOrigin.Begin); this._xpsPackage = Package.Open(data, FileMode.Open, FileAccess.ReadWrite); try { PackageStore.AddPackage(this._packageUri, this._xpsPackage); this._xpsDocument = new XpsDocument(this._xpsPackage, CompressionOption.Maximum, path); this.GetFixedDocumentSequenceUri(); } catch (Exception ex) { SiliconStudio.DebugManagers.DebugReporter.Report( SiliconStudio.DebugManagers.MessageType.Error, "Failed to create Xps Document Instance", "\nPath: " + path + "\nIs External To Assignment: " + isExternalToAssignment.ToString() + "\nError: " + ex.Message); throw; } } // end:Constructor()
private void Page_Loaded(object sender, RoutedEventArgs e) { // Getting a Stream out of the Resource file, strDocument string strDocument = "View.Help.legendgenerator_english.xps"; string strSchemaPath = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + "." + strDocument; Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(strSchemaPath); // Getting the length of the Stream we just obtained int length = (int)stream.Length; // Setting up a new MemoryStream and Byte Array MemoryStream ms = new MemoryStream(); ms.Capacity = (int)length; byte[] buffer = new byte[length]; // Copying the Stream to the Byte Array (Buffer) stream.Read(buffer, 0, length); // Copying the Byte Array (Buffer) to the MemoryStream ms.Write(buffer, 0, length); // Setting up a new Package based on the MemoryStream Package pkg = Package.Open(ms); // Putting together a Uri for the Package using the document name (strDocument) string strMemoryPackageName = string.Format("memorystream://{0}.xps", "legendgenerator_english.xps"); Uri packageUri = new Uri(strMemoryPackageName); // Adding the Package to PackageStore using the Uri if (PackageStore.GetPackage(packageUri) == null) { PackageStore.AddPackage(packageUri, pkg); } // Finally, putting together the XpsDocument doc = new XpsDocument(pkg, CompressionOption.Maximum, strMemoryPackageName); // Feeding the DocumentViewer, which was declared at Design Time as a variable called "viewer" documentViewer1.Document = doc.GetFixedDocumentSequence(); documentViewer1.FitToWidth(); documentViewer1.FitToHeight(); }
public static void PrintXps(FlowDocument document, bool printDirect = true) { try { Uri DocumentUri = new Uri("pack://currentTicket.xps"); var ms = new MemoryStream(); { using (Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite)) { PackageStore.AddPackage(DocumentUri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, DocumentUri.AbsoluteUri); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); writer.Write(((IDocumentPaginatorSource)document).DocumentPaginator); if (printDirect) { PrintXpsToPrinter(xpsDocument); } PackageStore.RemovePackage(DocumentUri); xpsDocument.Close(); package.Close(); } } } catch (Exception ex) { // log the exceptions LogService.Error("Print Error", ex); } }
public static XpsDocument GetXpsDocument(FlowDocument document) { //Uri DocumentUri = new Uri("pack://currentTicket_" + new Random().Next(1000).ToString() + ".xps"); Uri docUri = new Uri("pack://tempTicket.xps"); var ms = new MemoryStream(); { Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); PackageStore.RemovePackage(docUri); PackageStore.AddPackage(docUri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, docUri.AbsoluteUri); XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false); DocumentPaginator docPage = ((IDocumentPaginatorSource)document).DocumentPaginator; //docPage.PageSize = new System.Windows.Size(PageWidth, PageHeight); //docPage.PageSize = new System.Windows.Size(document.PageWidth, document.PageHeight); rsm.SaveAsXaml(docPage); return(xpsDocument); } }
public void LoadXps() { MemoryStream ms = new MemoryStream(); Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); Uri DocumentUri = new Uri("pack://InMemoryDocument.xps"); try { //构造一个基于内存的xps document PackageStore.RemovePackage(DocumentUri); PackageStore.AddPackage(DocumentUri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, DocumentUri.AbsoluteUri); //将flow document写入基于内存的xps document中去 XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); writer.Write(((IDocumentPaginatorSource)m_doc).DocumentPaginator); //获取这个基于内存的xps document的fixed document docViewer.Document = xpsDocument.GetFixedDocumentSequence(); //关闭基于内存的xps document xpsDocument.Close(); } catch (Exception ex) { MessageBox.Show("异常(LoadXps):\n" + ex.Message); } }
/// <summary> /// Helper method to create page header o footer from flow document template /// </summary> /// <param name="fd"></param> /// <param name="pageDef"></param> /// <returns></returns> public static XpsDocument CreateXpsDocument(FlowDocument fd, PageDefinition pageDef) { const string pack = "pack://report.xps"; //var ms = new MemoryStream(); //Package pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); //PackageStore.RemovePackage(new Uri(pack)); //PackageStore.AddPackage(new Uri(pack), pkg); //var doc = new XpsDocument(pkg, CompressionOption.SuperFast, pack); //var rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false); //DocumentPaginator paginator = ((IDocumentPaginatorSource)fd).DocumentPaginator; //var rp = new ReportPaginator(paginator, new Size(96/2.54*21, 96/2.54*28.7), pageDef);//PrintHelper.GetPageSize() //rsm.SaveAsXaml(rp); //return doc; var ms = new MemoryStream(); var package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); var doc = new XpsDocument(package, CompressionOption.SuperFast, pack); PackageStore.AddPackage(new Uri(pack), package); DocumentPaginator paginator = ((IDocumentPaginatorSource)fd).DocumentPaginator; XpsDocument.CreateXpsDocumentWriter(doc).Write(paginator); //ReplacePngsWithJpegs(package); //var fixedDoc = doc.GetFixedDocumentSequence(); //fixedDoc.DocumentPaginator.PageSize = GetPaperSize(reportPaperSize); return(doc); }
/// <summary> /// Loads xaml content from a WPF package. /// </summary> /// <param name="stream"> /// Stream that must be accessible for reading and structured as /// a WPF container: part XamlEntryPart is expected as one of /// its entry parts. /// </param> /// <returns> /// Returns a xaml element loaded from the entry part of the package. /// </returns> /// <exception cref="ArgumentNullException"> /// Throws parsing exception when the xaml content does not comply with the xaml schema. /// </exception> /// <exception cref="ArgumentException"> /// Throws validation exception when the package is not well structured. /// </exception> /// <exception cref="Exception"> /// Throws uri exception when the pachageBaseUri is not correct absolute uri. /// </exception> /// <remarks> /// USED IN LEXICON VIA REFLECTION /// </remarks> internal static object LoadElement(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } object xamlObject; try { WpfPayload wpfPayload = WpfPayload.OpenWpfPayload(stream); // Now load the package using (wpfPayload.Package) { // Validate WPF paypoad and get its entry part PackagePart xamlEntryPart = wpfPayload.ValidatePayload(); // Define a unique uri for this instance of PWF payload. // Uniqueness is required to make sure that cached images are not mixed up. int newWpfPayoutCount = Interlocked.Increment(ref _wpfPayloadCount); Uri payloadUri = new Uri("payload://wpf" + newWpfPayoutCount, UriKind.Absolute); Uri entryPartUri = PackUriHelper.Create(payloadUri, xamlEntryPart.Uri); // gives an absolute uri of the entry part Uri packageUri = PackUriHelper.GetPackageUri(entryPartUri); // extracts package uri from combined package+part uri PackageStore.AddPackage(packageUri, wpfPayload.Package); // Register the package // Set this temporary uri as a base uri for xaml parser ParserContext parserContext = new ParserContext(); parserContext.BaseUri = entryPartUri; // Call xaml parser xamlObject = XamlReader.Load(xamlEntryPart.GetStream(), parserContext); // Remove the temporary uri from the PackageStore PackageStore.RemovePackage(packageUri); } } catch (XamlParseException e) { // Incase of xaml parsing or package structure failure // we return null. Invariant.Assert(e != null); //to make compiler happy about not using a variable e. This variable is useful in debugging process though - to see a reason of a parsing failure xamlObject = null; } catch (System.IO.FileFormatException) { xamlObject = null; } catch (System.IO.FileLoadException) { xamlObject = null; } catch (System.OutOfMemoryException) { xamlObject = null; } return(xamlObject); }
public static void PrintPreview(Window owner, object data, bool IsSinglePage = false) { using (MemoryStream xpsStream = new MemoryStream()) { using (Package package = Package.Open(xpsStream, FileMode.Create, FileAccess.ReadWrite)) { string packageUriString = "memorystream://data.xps"; Uri packageUri = new Uri(packageUriString); if (PackageStore.GetPackage(packageUri) != null) { PackageStore.RemovePackage(packageUri); } PackageStore.AddPackage(packageUri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.NotCompressed, packageUriString); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); // Form visual = new Form(); // PrintTicket printTicket = new PrintTicket(); // printTicket.PageMediaSize = A4PaperSize; // var d = PrintOnMultiPage(data, true); //((IDocumentPaginatorSource)data).DocumentPaginator if (!IsSinglePage) { writer.Write(PrintOnMultiPage(data, true)); } else { writer.Write(Print((Visual)data, true)); } FixedDocumentSequence document = xpsDocument.GetFixedDocumentSequence(); xpsDocument.Close(); PrintPreviewWindow printPreviewWnd = new PrintPreviewWindow(document); printPreviewWnd.Owner = owner; printPreviewWnd.ShowDialog(); PackageStore.RemovePackage(packageUri); } } }
public InProcXpsDocumentWrapper() { _memoryStream = new MemoryStream(); var package = Package.Open(_memoryStream, FileMode.Create, FileAccess.ReadWrite); _documentUri = new Uri("pack://" + Guid.NewGuid() + ".xps"); PackageStore.AddPackage(_documentUri, package); Document = new XpsDocument(package, CompressionOption.NotCompressed, _documentUri.AbsoluteUri); }
private void CreateButtonClick(object sender, RoutedEventArgs e) { Logger.Write("Entering CreateButtonClick method"); var tab = TabControl.SelectedItem as TabItem; if (tab != null) { var reportProperty = tab.Content as UserControl; if (reportProperty != null) { // Create report IReport reportTemplate = null; IEnumerable <ReportItem> workItems = null; var selectedItem = TabControl.SelectedItem as TabItem; var project = projects[selectedItem]; reportTemplate = project.SelectedReport; simpleTracker.TrackEventAsync("Report", reportTemplate.Description); workItems = project.WorkItems; simpleTracker.TrackEventAsync("Workitems", workItems.Count().ToString()); var ms = new MemoryStream(); var pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); var pack = string.Format("pack://{0}.xps", Guid.NewGuid()); PackageStore.AddPackage(new Uri(pack), pkg); var compressionOption = CompressionOption.NotCompressed; var document = new XpsDocument(pkg, compressionOption, pack); var report = reportTemplate.Create(workItems); var writer = XpsDocument.CreateXpsDocumentWriter(document); writer.Write(report.DocumentPaginator); // Create doc var doc = new DocumentViewer { Document = document.GetFixedDocumentSequence() }; // Remove toolbar from DocumentViewer var contentHost = doc.Template.FindName("PART_ContentHost", doc) as ScrollViewer; if (contentHost != null) { var grid = contentHost.Parent as Grid; if (grid != null) { grid.Children.RemoveAt(0); } } doc.FitToMaxPagesAcross(1); tab.Content = doc; TabSelectionChanged(null, null); } } }
private void RegisterAtPackageStoreWith(Package package, Uri packageUri) { if (PackageStoreContains(packageUri)) { UnregisterFromPackagestore(packageUri); } PackageStore.AddPackage(packageUri, package); }