Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
    // 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();
        }
    }
 public void RemovePackage()
 {
     if (_packageUri != null)
     {
         PackageStore.RemovePackage(_packageUri);
     }
 }
Exemplo n.º 4
0
        /// <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);
        }
Exemplo n.º 5
0
        }// end:OnClose()


        // --------------------------- CloseDocument --------------------------
        /// <summary>
        ///   Closes the document currently displayed in
        ///   the DocumentViewer control.</summary>
        public void CloseDocument()
        {
            // Remove the document from the DocumentViewer control.
            docViewer.Document = null;

            // If the package is open, close it.
            if (_xpsPackage != null)
            {
                _xpsPackage.Close();
                _xpsPackage = null;
            }

            if (_packageUri != null)
                PackageStore.RemovePackage(_packageUri);

            // Disable document-related selections when there's no document.
            menuFileClose.IsEnabled = false;
            menuFilePrint.IsEnabled = false;
            menuViewIncreaseZoom.IsEnabled = false;
            menuViewDecreaseZoom.IsEnabled = false;
            WriteStatus("Closed '" + _xpsDocumentName + "'");
            WritePrompt(
                "Click 'File | Open...' to select a file to open and view.");

            // Close the XrML file.
            CloseXrML();

        }// end:CloseDocument
Exemplo n.º 6
0
        public void SaveAs(bool UpdatePackageStore)
        {
            //Updated to take a bool to determine if the package store should be updated 081128
            //holds the uris to the Xps packages before they are updated in the
            //save as operation. 080405
            //here we also need to update the km entities parent doc ID link.
            List <Uri> oldPackageStoreUris = new List <Uri>();

            foreach (ejpStudy study in this._studies)
            {
                foreach (ejpXpsDocument xpsD in study.XpsDocuments)
                {
                    oldPackageStoreUris.Add(xpsD.PackageUri);
                    xpsD.XpsDocument.CoreDocumentProperties.Identifier =
                        Helpers.IdManipulation.GetNewGuid().ToString();
                }
            }

            EjpLib.AssignmentOperations.LocalAssignmentFileOperations.SaveAssignmentAs(this);

            //remove all the old PackageUris from the Store. 080405
            if (UpdatePackageStore)
            {
                foreach (Uri puri in oldPackageStoreUris)
                {
                    PackageStore.RemovePackage(puri);
                }
            }

            this.IsPersisted = true;
        }
Exemplo n.º 7
0
        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);
        }
        private void OnWindowClosing(object sender, CancelEventArgs e)
        {
            try
            {
                docViewer.Document = null;

                if (_xpsDocument != null)
                {
                    _xpsDocument.Close();
                    _xpsDocument = null;
                }

                if (_xpsDocPackage != null)
                {
                    _xpsDocPackage.Close();
                    _xpsDocPackage = null;
                }

                if (!String.IsNullOrEmpty(_fileName))
                {
                    PackageStore.RemovePackage(new Uri(_fileName));
                }
            }
            catch
            {
            }
        }
        /// <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));
        }
        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);
     }
 }
Exemplo n.º 12
0
        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;
            }));
        }
Exemplo n.º 13
0
        private void OnWindowUnloaded(object sender, RoutedEventArgs e)
        {
            try
            {
                docViewer.Document = null;

                if (_xpsDocument != null)
                {
                    _xpsDocument.Close();
                    _xpsDocument = null;
                }

                if (_xpsDocPackage != null)
                {
                    _xpsDocPackage.Close();
                    _xpsDocPackage = null;
                }

                if (!string.IsNullOrWhiteSpace(_fileName))
                {
                    PackageStore.RemovePackage(new Uri(_fileName));
                }
            }
            catch
            {
            }
        }
Exemplo n.º 14
0
        /// <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();
            }
        }
        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();
        }
Exemplo n.º 16
0
        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());
        }
Exemplo n.º 17
0
        }// end:OnClose()


        // --------------------------- CloseDocument --------------------------
        /// <summary>
        ///   Closes the document currently displayed in
        ///   the DocumentViewer control.</summary>
        public void CloseDocument()
        {
            if (_xpsFile != null)
            {
                ShowStatus("Closing '" + Filename(_xpsFile) + "'");
                DocViewer.Document = null;
                _xpsFile = null;
            }

            // If the package is open, close it.
            if (_xpsPackage != null)
            {
                _xpsPackage.Close();
                _xpsPackage = null;
            }

            // The package is closed, remove it from the store.
            if (_packageUri != null)
            {
                PackageStore.RemovePackage(_packageUri);
                _packageUri = null;
            }

            // Disable document-related selections when there's no document.
            menuFileClose.IsEnabled = false;
            menuFilePrint.IsEnabled = false;
            menuViewIncreaseZoom.IsEnabled = false;
            menuViewDecreaseZoom.IsEnabled = false;
            this.Title = "RightsManagedPackageViewer SDK Sample";
            ShowPrompt(
                "Click 'File | Open...' to select a file to open and view.");
            rightsBlock.Text = "";

        }// end:CloseDocument
Exemplo n.º 18
0
        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 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);
        }
Exemplo n.º 20
0
        }// end:OnClose()

        // --------------------------- CloseDocument --------------------------
        /// <summary>
        ///   Closes the document currently displayed in
        ///   the DocumentViewer control.</summary>
        public void CloseDocument()
        {
            // Shut down the annotationsHelper.
            _annotHelper.StopAnnotations();

            // Remove the document from the DocumentViewer control.
            docViewer.Document = null;

            // If the package is open, close it.
            if (_xpsPackage != null)
            {
                _xpsPackage.Close();
                _xpsPackage = null;
            }

            if (_packageUri != null)
            {
                PackageStore.RemovePackage(_packageUri);
            }

            // Disable document-related selections when there's no document.
            menuFileClose.IsEnabled        = false;
            menuFilePrint.IsEnabled        = false;
            menuViewAnnotations.IsEnabled  = false;
            menuViewIncreaseZoom.IsEnabled = false;
            menuViewDecreaseZoom.IsEnabled = false;
        }// end:CloseDocument
Exemplo n.º 21
0
        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);
            }
        }
Exemplo n.º 22
0
        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);
            }
        }
Exemplo n.º 23
0
        /// <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);
        }
Exemplo n.º 24
0
        public void SaveAs()
        {
            //SiliconStudio.DebugManagers.DebugReporter.Report(
            //		SiliconStudio.DebugManagers.MessageType.Information,
            //		"EjpLib - ejpAssignment",
            //		"Saving Assignment As" +
            //		"\nTitle: " + this.MetaData.Title +
            //		"\nPath: " + this._filePackagePath);

            //holds the uris to the Xps packages before they are updated in the
            //save as operation. 080405
            //here we also need to update the km entities parent doc ID link.
            List <Uri> oldPackageStoreUris = new List <Uri>();

            foreach (ejpStudy study in this._studies)
            {
                foreach (ejpXpsDocument xpsD in study.XpsDocuments)
                {
                    oldPackageStoreUris.Add(xpsD.PackageUri);
                    xpsD.XpsDocument.CoreDocumentProperties.Identifier =
                        Helpers.IdManipulation.GetNewGuid().ToString();
                }
            }

            EjpLib.AssignmentOperations.LocalAssignmentFileOperations.SaveAssignmentAs(this);

            //remove all the old PackageUris from the Store. 080405
            foreach (Uri puri in oldPackageStoreUris)
            {
                PackageStore.RemovePackage(puri);
            }

            this.IsPersisted = true;
        }
Exemplo n.º 25
0
        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);
                }
            }
        }
 private void Dispose(bool disposing)
 {
     if (disposing && !_disposed)
     {
         _disposed = true;
         GC.SuppressFinalize(this);
         _memoryStream.Close();
         PackageStore.RemovePackage(_documentUri);
     }
 }
Exemplo n.º 27
0
        /// <summary>
        /// Print the document
        /// </summary>
        private void Print()
        {
            // We need to build the flowdocument in code behind, otherwise there will be no paging with Lists and UIBlocks....
            var flowDocument = new FlowDocument();

            flowDocument.PageWidth  = 650;
            flowDocument.PageHeight = 900;
            var title = new Paragraph(new Run($"{CurrentFortressData.FortressName} emergency sheet")
            {
                FontSize = 25
            });
            var subtitle = new Paragraph(new Run("Category => Name => Username => Password")
            {
                FontSize = 12
            });

            flowDocument.Blocks.Add(title);
            flowDocument.Blocks.Add(subtitle);
            var list = new List();

            foreach (var printableVm in PrintablePasswordEntries)
            {
                var pwEntry = $"{printableVm.Category} - {printableVm.Name} - {printableVm.Username}:{Environment.NewLine}{printableVm.Password}";
                var para    = new Paragraph(new Run(pwEntry))
                {
                    Margin = new System.Windows.Thickness(12, 0, 12, 0)
                };
                list.ListItems.Add(new ListItem(para));
            }

            flowDocument.Blocks.Add(list);

            // It is crucial, that we create the xps file in memory only and never write it onto the harddrive.
            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 xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, packUri.ToString());

            var paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;

            new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false)
            .SaveAsXaml(paginator);

            Document = xpsDocument.GetFixedDocumentSequence();

            // Show the printable Document
            var printView = new PrintView(Document);

            printView.DataContext = this;
            printView.Show();
        }
Exemplo n.º 28
0
        private void ClosePrintPreview()
        {
            // Remove the package from the store
            PackageStore.RemovePackage(new Uri(PackagePath));

            xpsDocument.Close();
            package.Close();

            shellViewModel.ContentView = previousView;
            previousView = null;
            shellViewModel.IsPrintPreviewVisible = false;
            printPreviewCommand.RaiseCanExecuteChanged();
        }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            try
            {
                // create XPS file based on a WPF Visual, and store it in a memorystream
                MemoryStream      lMemoryStream = new MemoryStream();
                Package           package       = Package.Open(lMemoryStream, FileMode.Create);
                XpsDocument       doc           = new XpsDocument(package);
                XpsDocumentWriter writer        = XpsDocument.CreateXpsDocumentWriter(doc);
                writer.Write(WPF2PDF.CreateVisual());



                // now open this XPS stream in the NiXPS SDK, and export it as pdf
                //NOPackage lPackage = NOPackage.readPackageFromBuffer("file.xps", lMemoryStream.GetBuffer(), (uint)lMemoryStream.Length);
                //NOProgressReporter lReporter = new NOProgressReporter();
                //lPackage.getDocument(0).exportToPDF("file.pdf", lReporter);
                //NOPackage.destroyPackage(ref lPackage);



                //Create URI for Xps Package
                //Any Uri will actually be fine here. It acts as a place holder for the
                //Uri of the package inside of the PackageStore
                string inMemoryPackageName = string.Format("memorystream://{0}.xps", Guid.NewGuid());
                Uri    packageUri          = new Uri(inMemoryPackageName);

                //Add package to PackageStore
                PackageStore.AddPackage(packageUri, package);

                XpsDocument           xpsDoc = new XpsDocument(package, CompressionOption.Maximum, inMemoryPackageName);
                FixedDocumentSequence fixedDocumentSequence = xpsDoc.GetFixedDocumentSequence();

                PrintDialog dlg = new PrintDialog();
                dlg.PrintDocument(fixedDocumentSequence.DocumentPaginator, "Document title");


                PackageStore.RemovePackage(packageUri);
                xpsDoc.Close();

                doc.Close();
                package.Close();
            }
            catch (Exception e)
            {
                System.Console.Out.WriteLine("EXCEPTION: 0x" + string.Format("{0:X}", e.Message));
            }
            Console.WriteLine("Conversion to WPF done!");
            Console.ReadKey();
        }
Exemplo n.º 30
0
        //Closes an open document and tidies up.
        private void CloseFixedDocument()
        {
            if (hasOpenDocument)
            {
                StopFixedDocumentAnnotations();

                PackageStore.RemovePackage(documentUri);

                xpsDocument.Close();
                xpsDocument = null;

                xpsPackage.Close();
                xpsPackage = null;
            }
        }