Example #1
1
        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();
            }
        }
Example #2
0
        public static void Concat(string targetFileName, params string[] filesToConcat)
        {
            var fixedDocumentSequence = new FixedDocumentSequence();

            var tempFileName = Path.GetTempFileName();
            using (var target = new XpsDocument(tempFileName, FileAccess.Write))
            {
                var xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(target);

                if (filesToConcat != null)
                {
                    foreach (var doc in filesToConcat)
                    {
                        Add(doc, fixedDocumentSequence);
                    }
                }

                xpsDocumentWriter.Write(fixedDocumentSequence);
            }

            if (File.Exists(targetFileName))
            {
                File.Delete(targetFileName);
            }
            File.Move(tempFileName, targetFileName);
        }
Example #3
0
        private void window_Loaded(object sender, RoutedEventArgs e)
        {
            doc = new XpsDocument("ch19.xps", FileAccess.ReadWrite);
            docViewer.Document = doc.GetFixedDocumentSequence();

            service = AnnotationService.GetService(docViewer);
            if (service == null)
            {
                Uri annotationUri = PackUriHelper.CreatePartUri(new Uri("AnnotationStream", UriKind.Relative));
                Package package = PackageStore.GetPackage(doc.Uri);
                PackagePart annotationPart = null;
                if (package.PartExists(annotationUri))
                {                    
                    annotationPart = package.GetPart(annotationUri);
                }
                else                
                {                    
                    annotationPart = package.CreatePart(annotationUri, "Annotations/Stream");
                }

                // Load annotations from the package.
                AnnotationStore store = new XmlStreamStore(annotationPart.GetStream());
                service = new AnnotationService(docViewer);
                service.Enable(store);
                
            }
        }
Example #4
0
 private void Window_Loaded(object sender, EventArgs e)
 {            
     XpsDocument doc = new XpsDocument("test.xps", FileAccess.ReadWrite);
     docViewer.Document = doc.GetFixedDocumentSequence();
     
     doc.Close();
 }
 private void btnXmlWriter_Click(object sender, RoutedEventArgs e)
 {
     using (XpsDocument xpsDoc = new XpsDocument("Out.xps", FileAccess.Write))
     {
         IXpsFixedDocumentSequenceWriter sequenceWriter =
         xpsDoc.AddFixedDocumentSequence();
         IXpsFixedDocumentWriter docWriter =
         sequenceWriter.AddFixedDocument();
         IXpsFixedPageWriter pageWriter = docWriter.AddFixedPage();
         XmlWriter xmlWriter = pageWriter.XmlWriter;
         xmlWriter.WriteStartElement("FixedPage");
         xmlWriter.WriteAttributeString("xmlns",
                      "http://schemas.microsoft.com/xps/2005/06");
         xmlWriter.WriteAttributeString("Width", "600");
         xmlWriter.WriteAttributeString("Height", "400");
         xmlWriter.WriteAttributeString("xml:lang", "ko-KR");
         xmlWriter.WriteStartElement("Path");
         xmlWriter.WriteAttributeString("Data",
                             "M 10,10 L 150,200 500,300 555,387 z");
         xmlWriter.WriteAttributeString("Fill", "#ffff0000");
         xmlWriter.WriteEndElement();
         xmlWriter.WriteEndElement();
         pageWriter.Commit();
         docWriter.Commit();
         sequenceWriter.Commit();
     }
 }
        private void btnXpsDocumentWriter_Click(object sender, RoutedEventArgs e)
        {
            using (Package xpsPackage = Package.Open("Out.xps", FileMode.Create,
                           FileAccess.ReadWrite))
            using (XpsDocument doc = new XpsDocument(xpsPackage))
            {

                FixedPage page = new FixedPage();
                Canvas canvas = new Canvas();
                canvas.Width = 600;
                canvas.Height = 400;
                page.Children.Add(canvas);
                Rectangle rect = new Rectangle();
                Canvas.SetLeft(rect, 50);
                Canvas.SetTop(rect, 50);
                rect.Width = 200;
                rect.Height = 100;
                rect.Stroke = Brushes.Black;
                rect.StrokeThickness = 1;
                canvas.Children.Add(rect);
                XpsDocumentWriter documentWriter =
                XpsDocument.CreateXpsDocumentWriter(doc);
                documentWriter.Write(page);

                doc.CoreDocumentProperties.Description = "Rectangle Output";
            }
        }
Example #7
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;
            }
        }
 private void btnPrint_Click(object sender, EventArgs e)
 {
     //REFACTOR ME
     dtgParentReport.Update();
     System.Windows.Controls.PrintDialog printDialog = new System.Windows.Controls.PrintDialog();
     Nullable<bool> print = printDialog.ShowDialog();
     if (print == true)
     {
         try
         {
             XpsDocument xpsDocument = new XpsDocument("C:\\FixedDocumentSequence.xps", FileAccess.ReadWrite);
             FixedDocumentSequence fixedDocSeq = xpsDocument.GetFixedDocumentSequence();
             printDialog.PrintDocument(fixedDocSeq.DocumentPaginator, "Test print job");
         }
         catch (UnauthorizedAccessException e1)
         {
             const string message =
                 "Unauthoried to access that printer.";
             const string caption = "Unauthoried Access";
             var result = MessageBox.Show(message, caption,
                                         MessageBoxButtons.OK,
                                         MessageBoxIcon.Error);
         }
         catch (PrintDialogException e2)
         {
             const string message =
                 "Unknow error occurred.";
             const string caption = "Error Printing";
             var result = MessageBox.Show(message, caption,
                                         MessageBoxButtons.OK,
                                         MessageBoxIcon.Error);
         }
     }
 }
        public static XpsDocument ConvertWordToXps(string wordFilename, string xpsFilename)
        {
            // Create a WordApplication and host word document
            Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            try
            {
                wordApp.Documents.Open(wordFilename);

                // To Invisible the word document
                wordApp.Application.Visible = false;

                // Minimize the opened word document
                wordApp.WindowState = WdWindowState.wdWindowStateMinimize;

                Document doc = wordApp.ActiveDocument;

                doc.SaveAs(xpsFilename, WdSaveFormat.wdFormatXPS);

                XpsDocument xpsDocument = new XpsDocument(xpsFilename, FileAccess.Read);

                return xpsDocument;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occurs, The error message is  " + ex.ToString());
                return null;
            }
            finally
            {
                wordApp.Documents.Close();
                ((_Application)wordApp).Quit(WdSaveOptions.wdDoNotSaveChanges);
            }
        }
Example #10
0
        /// <summary>
        /// Exports the specified plot model to an xps file.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="fileName">The file name.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="background">The background color.</param>
        public static void Export(IPlotModel model, string fileName, double width, double height, OxyColor background)
        {
            using (var xpsPackage = Package.Open(fileName, FileMode.Create, FileAccess.ReadWrite))
            {
                using (var doc = new XpsDocument(xpsPackage))
                {
                    var canvas = new Canvas { Width = width, Height = height, Background = background.ToBrush() };
                    canvas.Measure(new Size(width, height));
                    canvas.Arrange(new Rect(0, 0, width, height));

                    var rc = new ShapesRenderContext(canvas);
#if !NET35
                    rc.TextFormattingMode = TextFormattingMode.Ideal;
#endif

                    model.Update(true);
                    model.Render(rc, width, height);

                    canvas.UpdateLayout();

                    var xpsdw = XpsDocument.CreateXpsDocumentWriter(doc);
                    xpsdw.Write(canvas);
                }
            }
        }
Example #11
0
        // Test
        public static string ExtractText(string path)
        {
            XpsDocument _xpsDocument = new XpsDocument(path, System.IO.FileAccess.Read);
            IXpsFixedDocumentSequenceReader fixedDocSeqReader
                = _xpsDocument.FixedDocumentSequenceReader;
            IXpsFixedDocumentReader _document = fixedDocSeqReader.FixedDocuments[0];

            IXpsFixedPageReader _page
                = _document.FixedPages[0];
            StringBuilder _currentText = new StringBuilder();
            System.Xml.XmlReader _pageContentReader = _page.XmlReader;
            if (_pageContentReader != null)
            {
                while (_pageContentReader.Read())
                {
                    if (_pageContentReader.Name == "Glyphs")
                    {
                        if (_pageContentReader.HasAttributes)
                        {
                            if (_pageContentReader.GetAttribute("UnicodeString") != null)
                            {
                                _currentText.
                                  Append(_pageContentReader.
                                  GetAttribute("UnicodeString") + "\n");
                            }
                        }
                    }
                }
            }
               return _currentText.ToString();
        }
Example #12
0
        public PreviewWindow(CustomDocumentPaginator documentPaginator)
        {
            InitializeComponent();

            //xps
            stream = new MemoryStream();

            Package package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite);

            var uri = new Uri(@"memorystream://myXps.xps");
            //already in packagestore, so remove
            if (PackageStore.GetPackage(uri) != null)
            {
                PackageStore.RemovePackage(uri);
            }
            PackageStore.AddPackage(uri, package);
            var xpsDoc = new XpsDocument(package);

            xpsDoc.Uri = uri;
            XpsDocument.CreateXpsDocumentWriter(xpsDoc).Write(documentPaginator);

            FixedDocumentSequence fds = xpsDoc.GetFixedDocumentSequence();

            dv1.Document = (IDocumentPaginatorSource)fds;
        }
        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());
        }
Example #14
0
        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();
        }
Example #15
0
        public static bool SaveXPS(FixedPage page, bool isSaved)
        {
            FixedDocument fixedDoc = new FixedDocument();//创建一个文档
            fixedDoc.DocumentPaginator.PageSize = new Size(96 * 8.5, 96 * 11);

            PageContent pageContent = new PageContent();
            ((IAddChild)pageContent).AddChild(page);
            fixedDoc.Pages.Add(pageContent);//将对象加入到当前文档中

            string containerName = GetXPSFromDialog(isSaved);
            if (containerName != null)
            {
                try
                {
                    File.Delete(containerName);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }

                XpsDocument _xpsDocument = new XpsDocument(containerName, FileAccess.Write);

                XpsDocumentWriter xpsdw = XpsDocument.CreateXpsDocumentWriter(_xpsDocument);
                xpsdw.Write(fixedDoc);//写入XPS文件
                _xpsDocument.Close();
                return true;
            }
            else return false;
        }
Example #16
0
        private static CreateXpsFileResult InternalCreateFileFromXaml(FrameworkElement template, object dataContext)
        {
            string xpsFile = Path.GetTempFileName() + ".xps";

            using (var container = Package.Open(xpsFile, FileMode.Create))
            using (var document = new XpsDocument(container, CompressionOption.SuperFast))
            {
                var coupon = template;

                coupon.DataContext = dataContext;
                coupon.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                coupon.UpdateLayout();

                var ticket = new PrintTicket()
                {
                    PageMediaSize = new PageMediaSize(coupon.DesiredSize.Width, coupon.DesiredSize.Height)
                };

                XpsDocument.CreateXpsDocumentWriter(document).Write(coupon, ticket);

                return new CreateXpsFileResult()
                {
                    Path = xpsFile,
                    Ticket = ticket
                };
            }
        }
 void Window2_Loaded(object sender, RoutedEventArgs e)
 {
     //throw new NotImplementedException();
     XpsDocument xpsdoc = new XpsDocument("xml.xps", System.IO.FileAccess.Read);
     FixedDocumentSequence fds = xpsdoc.GetFixedDocumentSequence();
     documentViewer.Document = fds.References[0].GetDocument(true);
 }
Example #18
0
        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();
        }
Example #19
0
        private void SaveToFile()
        {
            if (Directory.Exists(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\\renderedData") == false)
            { Directory.CreateDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\\renderedData"); }

            string destination = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\\renderedData\\" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + " " +
                DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + " " + Environment.UserName + " 2dView";

            using (var stream = new FileStream(destination+".xps", FileMode.Create))
            {
                using (var package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (var xpsDoc = new XpsDocument(package, CompressionOption.Maximum))
                    {
                        var rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                        var paginator = ((IDocumentPaginatorSource)FlowDocViewer.Document).DocumentPaginator;
                        rsm.SaveAsXaml(paginator);
                        rsm.Commit();
                    }
                }
                stream.Position = 0;

                var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(stream);
                XpsConverter.Convert(pdfXpsDoc, destination + ".pdf", 0);
            }


        }
Example #20
0
 public override void Show(System.Windows.Controls.ContentControl contentControl, object writer)
 {
     this.m_XpsDocument = new XpsDocument(this.FullFileName, System.IO.FileAccess.Read);
     System.Windows.Controls.DocumentViewer documentViewer = new System.Windows.Controls.DocumentViewer();
     documentViewer.Loaded += new System.Windows.RoutedEventHandler(DocumentViewer_Loaded);
     documentViewer.Document = this.m_XpsDocument.GetFixedDocumentSequence();
     contentControl.Content = documentViewer;
 }
Example #21
0
 private static void ShowXpsPreview(XpsDocument xpsDocument)
 {
     var previewWindow = new Window();
     var docViewer = new DocumentViewer();
     previewWindow.Content = docViewer;
     docViewer.Document = xpsDocument.GetFixedDocumentSequence();
     previewWindow.ShowDialog();
 }
 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);
 }
 /// <summary>
 /// Saving the current report's content as an XPS file.
 /// </summary>
 /// <param name="doc">Retrieve it from xps.GetFixedDocumentSequence() or documentViewer.Document</param>
 /// <param name="fileName"></param>
 public static void Export(this FixedDocumentSequence doc, string fileName)
 {
     using (var xpsd = new XpsDocument(fileName, FileAccess.ReadWrite))
     {
         //it needs a ref. to System.Printing asm.
         var xw = XpsDocument.CreateXpsDocumentWriter(xpsd); 
         xw.Write(doc);
     }
 }
        private void HelpView_OnLoaded(object sender, RoutedEventArgs e)
        {
            var directory = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
            directory = Path.Combine(directory, "UserGuide");
            var fileName = Path.Combine(directory, "HowToUseGuide.xps");
            var doc = new XpsDocument(fileName, FileAccess.Read);

            HelpDocumentViewer.Document = doc.GetFixedDocumentSequence();
        }
Example #25
0
        public static DeckModel OpenXPS(string file)
        {
            try
            {
                Misc.ProgressBarForm progressForm = new UW.ClassroomPresenter.Misc.ProgressBarForm("Opening \"" + file + "\"...");
                progressForm.Show();

                //Open Xps Document
                XpsDocument xpsDocument = null;

                xpsDocument = new XpsDocument(file, FileAccess.Read);

                //Create two DocumentPaginators for the XPS document. One is for local display, the other one is for the delivery to students.
                DocumentPaginator paginator = xpsDocument.GetFixedDocumentSequence().DocumentPaginator;

                //Create Deck Model
                Guid deckGuid = Guid.NewGuid();
                DeckModel deck = new DeckModel(deckGuid, DeckDisposition.Empty, file);

                using (Synchronizer.Lock(deck.SyncRoot))
                {
                    deck.IsXpsDeck = true;

                    //Iterate over all pages
                    for (int i = 0; i < paginator.PageCount; i++)
                    {
                        DocumentPage page = paginator.GetPage(i);

                        SlideModel newSlideModel = CreateSlide(page, deck);

                        //Create a new Entry + reference SlideModel
                        TableOfContentsModel.Entry newEntry = new TableOfContentsModel.Entry(Guid.NewGuid(), deck.TableOfContents, newSlideModel);
                        //Lock the TOC
                        using (Synchronizer.Lock(deck.TableOfContents.SyncRoot))
                        {
                            //Add Entry to TOC
                            deck.TableOfContents.Entries.Add(newEntry);
                        }

                        //Update the Progress Bar
                        progressForm.UpdateProgress(0, paginator.PageCount , i+1);
                    }
                }

                //Close Progress Bar
                progressForm.Close();

                return deck;
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine(e.ToString());
            }
            GC.Collect();

            return null;
        }
 public void ViewDocument(string fileName)
 {
     if (System.IO.File.Exists(fileName) == true)
     {
         XpsDocument xpsDocument = new XpsDocument(fileName, System.IO.FileAccess.Read);
         this.Viewer.Document = xpsDocument.GetFixedDocumentSequence();
         xpsDocument.Close();
     }
 }
Example #27
0
        public void OnLoaded(object sender, RoutedEventArgs args)
        {
            XpsDocument document = new XpsDocument(Window1.CombineFileInCurrentDirectory("CSharp 3.0 Specification.xps"), System.IO.FileAccess.Read);

            FixedDocument doc = new FixedDocument();
            FixedDocumentSequence fixedDoc = document.GetFixedDocumentSequence();

            viewer.Document = fixedDoc;
            viewer.FitToHeight();
        }
Example #28
0
        public MarkingTool(MainUI main)
        {
            this.InitializeComponent();

            // Insert code required on object creation below this point.

            this.main = main;
            doc = main.curDoc.getXPSCopy();
            if (doc != null)
                docView.Document = doc.GetFixedDocumentSequence();
        }
Example #29
0
        public static Boolean Creer(DocumentPaginator document, String Chemin)
        {
            if (String.IsNullOrWhiteSpace(Chemin))
            {
                return(false);
            }

            try
            {
                // Convertion du document en xps
                MemoryStream strm = new MemoryStream();
                Package      pkg  = Package.Open(strm, FileMode.OpenOrCreate);
                String       pack = "pack://" + Guid.NewGuid().ToString() + ".xps";
                PackageStore.AddPackage(new Uri(pack), pkg);
                XpsDocument             xpsDoc = new XpsDocument(pkg, CompressionOption.Maximum, pack);
                XpsSerializationManager xpsSM  = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                xpsSM.SaveAsXaml(document);

                // Enregistrement du xps dans un fichier tmp
                String      tmpXpsFileName = Path.Combine(Path.GetTempPath(), "Gestion_" + DateTime.Now.Ticks + ".xps");
                XpsDocument xpsd           = new XpsDocument(tmpXpsFileName, FileAccess.ReadWrite);
                System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd);
                xw.Write(xpsDoc.GetFixedDocumentSequence());
                xpsd.Close();

                PdfSharp.Xps.XpsConverter.Convert(tmpXpsFileName, Chemin, 0);

                //// Convertion du xps en pdf
                //PdfDocument pdfDoc = new PdfDocument();
                //pdfDoc.LoadFromXPS(tmpXpsFileName);
                //Byte[] pdfFile;
                //using (MemoryStream stream = new MemoryStream())
                //{
                //    pdfDoc.SaveToStream(stream);
                //    pdfFile = stream.ToArray();
                //}

                //// Ecriture du fichier
                //ByteArrayToFile(Chemin, pdfFile);

                //Byte[] pdfFile;
                //using (MemoryStream stream = new MemoryStream())
                //{
                //    PdfSharp.Xps.XpsModel.XpsDocument xpsDocument = PdfSharp.Xps.XpsModel.XpsDocument.Open(tmpXpsFileName);
                //    PdfSharp.Xps.XpsConverter.ConvertToPdfInMemory(xpsDocument, stream, 0);
                //    xpsDocument.Close();
                //    pdfFile = stream.ToArray();
                //}

                // Ecriture du fichier
                //ByteArrayToFile(Chemin, pdfFile);

                // Suppression du fichier tmp
                File.Delete(tmpXpsFileName);

                return(true);
            }
            catch { }

            return(false);
        }
Example #30
0
        /// <summary>
        /// Implements the PDF file to XPS file conversion.
        /// </summary>
        public static void Convert(string xpsFilename, string pdfFilename, int docIndex, bool createComparisonDocument)
        {
            if (String.IsNullOrEmpty(xpsFilename))
            {
                throw new ArgumentNullException("xpsFilename");
            }

            if (String.IsNullOrEmpty(pdfFilename))
            {
                pdfFilename = xpsFilename;
                if (IOPath.HasExtension(pdfFilename))
                {
                    pdfFilename = pdfFilename.Substring(0, pdfFilename.LastIndexOf('.'));
                }
                pdfFilename += ".pdf";
            }

            XpsDocument xpsDocument = null;

            try
            {
                xpsDocument = XpsDocument.Open(xpsFilename);
                FixedDocument fixedDocument = xpsDocument.GetDocument();
                PdfDocument   pdfDocument   = new PdfDocument();
                PdfRenderer   renderer      = new PdfRenderer();

                int pageIndex = 0;
                foreach (FixedPage page in fixedDocument.Pages)
                {
                    if (page == null)
                    {
                        continue;
                    }
                    Debug.WriteLine(String.Format("  doc={0}, page={1}", docIndex, pageIndex));
                    PdfPage pdfPage = renderer.CreatePage(pdfDocument, page);
                    renderer.RenderPage(pdfPage, page);
                    pageIndex++;

#if DEBUG
                    // stop at page...
                    if (pageIndex == 50)
                    {
                        break;
                    }
#endif
                }
                pdfDocument.Save(pdfFilename);
                xpsDocument.Close();
                xpsDocument = null;

                if (createComparisonDocument)
                {
                    System.Windows.Xps.Packaging.XpsDocument       xpsDoc = new System.Windows.Xps.Packaging.XpsDocument(xpsFilename, FileAccess.Read);
                    System.Windows.Documents.FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence();
                    if (docSeq == null)
                    {
                        throw new InvalidOperationException("docSeq");
                    }

                    XPdfForm    form = XPdfForm.FromFile(pdfFilename);
                    PdfDocument pdfComparisonDocument = new PdfDocument();


                    pageIndex = 0;
                    foreach (PdfPage page in pdfDocument.Pages)
                    {
                        if (page == null)
                        {
                            continue;
                        }
                        Debug.WriteLine(String.Format("  doc={0}, page={1}", docIndex, pageIndex));

                        PdfPage pdfPage = /*renderer.CreatePage(pdfComparisonDocument, page);*/ pdfComparisonDocument.AddPage();
                        double  width   = page.Width;
                        double  height  = page.Height;
                        pdfPage.Width  = page.Width * 2;
                        pdfPage.Height = page.Height;


                        DocumentPage docPage = docSeq.DocumentPaginator.GetPage(pageIndex);
                        //byte[] png = PngFromPage(docPage, 96);

                        BitmapSource bmsource = BitmapSourceFromPage(docPage, 96 * 2);
                        XImage       image    = XImage.FromBitmapSource(bmsource);

                        XGraphics gfx = XGraphics.FromPdfPage(pdfPage);
                        form.PageIndex = pageIndex;
                        gfx.DrawImage(form, 0, 0, width, height);
                        gfx.DrawImage(image, width, 0, width, height);

                        //renderer.RenderPage(pdfPage, page);
                        pageIndex++;

#if DEBUG
                        // stop at page...
                        if (pageIndex == 50)
                        {
                            break;
                        }
#endif
                    }

                    string pdfComparisonFilename = pdfFilename;
                    if (IOPath.HasExtension(pdfComparisonFilename))
                    {
                        pdfComparisonFilename = pdfComparisonFilename.Substring(0, pdfComparisonFilename.LastIndexOf('.'));
                    }
                    pdfComparisonFilename += "-comparison.pdf";

                    pdfComparisonDocument.ViewerPreferences.FitWindow = true;
                    //pdfComparisonDocument.PageMode = PdfPageMode.
                    pdfComparisonDocument.PageLayout = PdfPageLayout.SinglePage;
                    pdfComparisonDocument.Save(pdfComparisonFilename);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                if (xpsDocument != null)
                {
                    xpsDocument.Close();
                }
                throw;
            }
            finally
            {
                if (xpsDocument != null)
                {
                    xpsDocument.Close();
                }
            }
        }
Example #31
0
        }// end:OnOpen()

        // --------------------------- OpenDocument ---------------------------
        /// <summary>
        ///   Loads and displays a given XPS document file.</summary>
        /// <param name="filename">
        ///   The path and filename of the XPS document
        ///   to load and display.</param>
        /// <returns>
        ///   true if the document loads successfully; otherwise false.</returns>
        public bool OpenDocument(string filename)
        {
            // Save the document path and filename.
            _xpsDocumentPath = filename;

            // Extract the document filename without the path.
            _xpsDocumentName = filename.Remove(0, filename.LastIndexOf('\\') + 1);

            _packageUri = new Uri(filename, UriKind.Absolute);
            try
            {
                _xpsDocument = new XpsDocument(filename, FileAccess.Read);
            }
            catch (System.IO.FileFormatException)
            {
                string msg = filename + "\n\nThe specified file " +
                             "in not a valid unprotected XPS document.\n\n" +
                             "The file is possibly encrypted with rights management.  " +
                             "Please see the RightsManagedPackageViewer\nsample that " +
                             "shows how to access and view a rights managed XPS document.";
                MessageBox.Show(msg, "Invalid File Format",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }

            // Get the document's PackageStore into which
            // new user annotations will be added and saved.
            _xpsPackage = PackageStore.GetPackage(_packageUri);
            if ((_xpsPackage == null) || (_xpsDocument == null))
            {
                MessageBox.Show("Unable to get Package from file.");
                return(false);
            }

            // Get the FixedDocumentSequence from the open document.
            FixedDocumentSequence fds = _xpsDocument.GetFixedDocumentSequence();

            if (fds == null)
            {
                string msg = filename +
                             "\n\nThe document package within the specified " +
                             "file does not contain a FixedDocumentSequence.";
                MessageBox.Show(msg, "Package Error");
                return(false);
            }

            // Load the FixedDocumentSequence to the DocumentViewer control.
            docViewer.Document = fds;

            // Enable document menu controls.
            menuFileClose.IsEnabled        = true;
            menuFilePrint.IsEnabled        = true;
            menuFileRights.IsEnabled       = true;
            menuViewIncreaseZoom.IsEnabled = true;
            menuViewDecreaseZoom.IsEnabled = true;

            // Give the DocumentViewer focus.
            docViewer.Focus();

            WriteStatus("Opened '" + _xpsDocumentName + "'");
            WritePrompt("Click 'File | Rights...' to select an " +
                        "eXtensible Rights Markup (XrML) permissions file.");
            return(true);
        }// end:OpenDocument()
Example #32
0
        private void Load()
        {
            XpsDocument doc = new XpsDocument("Documents/ConvertationIntoDatabase.xps", System.IO.FileAccess.Read);

            documentViewer.Document = doc.GetFixedDocumentSequence();
        }
Example #33
0
        private void PrintImage(string fileName, Int32Rect crop, int quantity)
        {
            Console.WriteLine("    Print image " + fileName + " in " + quantity.ToString() + " copies.");

            PrintTicket ticket = _printer.UserPrintTicket;
            Size        paper  = new Size(Math.Max(ticket.PageMediaSize.Width.Value, ticket.PageMediaSize.Height.Value), Math.Min(ticket.PageMediaSize.Width.Value, ticket.PageMediaSize.Height.Value));
            Size        format = new Size(Math.Max(_width, _height) * 96 / 25.4, Math.Min(_width, _height) * 96 / 25.4);

            double printableWidth;
            double printableHeight;

            if (format.Width <= paper.Width && format.Height <= paper.Height)
            {
                printableWidth  = format.Width;
                printableHeight = format.Height;
            }
            else if (format.Width <= paper.Height && format.Height <= paper.Width)
            {
                printableWidth  = format.Height;
                printableHeight = format.Width;
            }
            else
            {
                printableWidth  = paper.Width;
                printableHeight = paper.Height;
            }

            // Swap printable width and height if page orientation is portarait
            if (ticket.PageOrientation == PageOrientation.Portrait || ticket.PageOrientation == PageOrientation.ReversePortrait)
            {
                double temp = printableWidth;
                printableWidth  = printableHeight;
                printableHeight = temp;
            }

            fileName = _orderFolder + fileName;

            // Create FixedDocument containing the image
            var fixedDocument = new FixedDocument();
            var pageContent   = new PageContent();
            var fixedPage     = new FixedPage();
            var image         = CreateImage(fileName, printableWidth, printableHeight, crop);

            fixedPage.Width  = printableWidth;
            fixedPage.Height = printableHeight;
            fixedPage.Children.Add(image);
            ((IAddChild)pageContent).AddChild(fixedPage);
            fixedDocument.Pages.Add(pageContent);

            // Save FixedDocument to XPS file
            string xpsFilePath = fileName + _width.ToString() + "x" + _height.ToString() + ".xps";

            using (FileStream outputStream = File.Create(xpsFilePath))
            {
                var package     = Package.Open(outputStream, FileMode.Create);
                var xpsDoc      = new XpsDocument(package, CompressionOption.Normal);
                var xpsWriter   = XpsDocument.CreateXpsDocumentWriter(xpsDoc);
                var fixedDocSeq = new FixedDocumentSequence();
                var docRef      = new DocumentReference();
                docRef.BeginInit();
                docRef.SetDocument(fixedDocument);
                docRef.EndInit();
                ((IAddChild)fixedDocSeq).AddChild(docRef);

                xpsWriter.Write(fixedDocSeq.DocumentPaginator);

                xpsDoc.Close();
                package.Close();
            }

            // Add the XPS file to print queue
            for (int i = 0; i < quantity; i++)
            {
                _printer.AddJob("Photo Kiosk", xpsFilePath, false);
                _success = true;
            }
        }
Example #34
0
        private void LoadDocument()
        {
            var doc = new XpsDocument(FilepathXps, FileAccess.Read);

            Document = doc.GetFixedDocumentSequence();
        }
Example #35
0
 public TheoryViewModel()
 {
     xpsDocument    = new XpsDocument("Resources/Theory.xps", FileAccess.Read);
     TheoryDocument = xpsDocument.GetFixedDocumentSequence();
 }
Example #36
0
        /// <summary>
        /// 将试题添加到Dictionary
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        private async System.Threading.Tasks.Task AddToListAsync(int index)
        {
            XpsDocument xpsDoc = await ConvertWordToXPSAsync(this._dicTerms[index].FullName);

            this._dicTermDocs.Add(index, xpsDoc);
        }
Example #37
0
        public static string SaveXPS1(Visual page, bool isSaved, string strType)
        {
            //bool isExit = false;
            //DependencyObject parent = page.Parent;
            //if (parent != null)
            //{
            //    if (strType == "printPage" && page.Name == "printPage")
            //    {
            //        isExit = true;
            //        return true;
            //    }
            //    if (strType == "w2" && page.Name == "w2")
            //    {
            //        isExit = true;
            //        return true;
            //    }
            //    return false;
            //}
            //else
            //{
            //    if (!isExit)
            //    {
            //创建一个文档
            //FixedDocument fixedDoc = new FixedDocument();
            //fixedDoc.DocumentPaginator.PageSize = new Size(96 * 8.5, 96 * 11);

            //PageContent pageContent = new PageContent();
            //page.Name = strType;
            //((IAddChild)pageContent).AddChild(page);
            //fixedDoc.Pages.Add(pageContent);//将对象加入到当前文档中


            string containerName = GetXPSFromDialog(isSaved, strType);

            if (containerName != null)
            {
                try
                {
                    File.Delete(containerName);
                }
                catch (Exception e)
                {
                    //  MessageWindow3.Show(e.Message);
                }

                XpsDocument       _xpsDocument = new XpsDocument(containerName, FileAccess.Write);
                XpsDocumentWriter xpsdw        = XpsDocument.CreateXpsDocumentWriter(_xpsDocument);
                //VisualsToXpsDocument xpsdw1 = (VisualsToXpsDocument)xpsdw.CreateVisualsCollator();


                xpsdw.Write(page);//写入XPS文件
                //xpsdw1.Write(page);
                //xpsdw1.EndBatchWrite();
                //xpsdw.Write(((IDocumentPaginatorSource)page).DocumentPaginator);


                _xpsDocument.Close();
            }
            return(containerName);
            //}
            //else
            //{
            //    return false;
            //}
            //}
        }
Example #38
0
        }// end:OnAddStructure()

        // ----------------------- AddDocumentStructure -----------------------
        /// <summary>
        ///   Writes a structured XPS document given an unstructured document
        ///   and a file list of XAML document structure elements to add.</summary>
        /// <param name="xpsUnstructuredFile">
        ///   The path and filename of the unstructured XPS document.</param>
        /// <param name="xamlStructureFile">
        ///   A file list of XAML document structures to add.</param>
        /// <param name="xpsTargetFile">
        ///   The path and filename for the new structured
        ///    XPS document to write.</param>
        /// <remarks>
        ///   If xpsTargetFile exists, it is first deleted and
        ///   then a new structured XPS document written.</remarks>
        private void AddDocumentStructure(
            string xpsUnstructuredFile,       // source unstructured document
            string[] xamlStructureFile,       // structure definition resources
            string xpsTargetFile)             // target structured XPS document
        {
            // Close the current document if one is open.
            CloseDocument();

            ShowStatus("\nCreating new structured XPS\n       " +
                       "document '" + Filename(xpsTargetFile) + "'.");

            // If the new target XPS file exists, prompt to confirm ok to replace.
            if (File.Exists(xpsTargetFile))
            {
                MessageBoxResult result = MessageBox.Show("'" + xpsTargetFile +
                                                          "' already exists.\nDo you want to delete and replace it?",
                                                          "Ok to replace '" + Filename(xpsTargetFile) + "'?",
                                                          MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result != MessageBoxResult.Yes)
                {
                    return;
                }
                ShowStatus("   Deleting old '" +
                           Filename(xpsTargetFile) + "'.");
                File.Delete(xpsTargetFile);
            }

            ShowStatus("   Copying '" + Filename(xpsUnstructuredFile) +
                       "'\n       to '" + Filename(xpsTargetFile) + "'.");
            File.Copy(xpsUnstructuredFile, xpsTargetFile);

            ShowStatus("   Opening '" + Filename(xpsTargetFile) +
                       "'\n       (currently without structure).");
            //<SnippetDocStrucAddStructure>
            //<SnippetDocStrucXpsDocument>
            XpsDocument xpsDocument = null;

            try
            {
                xpsDocument =
                    new XpsDocument(xpsTargetFile, FileAccess.ReadWrite);
            }
            catch (System.IO.FileFormatException)
            {
                string msg = xpsUnstructuredFile + "\n\nThe specified file " +
                             "does not appear to be a valid XPS document.";
                MessageBox.Show(msg, "Invalid File Format",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                ShowStatus("   Invalid XPS document format.");
                return;
            }
            //</SnippetDocStrucXpsDocument>

            //<SnippetDocStrucFixedDoc>
            ShowStatus("   Getting FixedDocumentSequenceReader.");
            IXpsFixedDocumentSequenceReader fixedDocSeqReader =
                xpsDocument.FixedDocumentSequenceReader;

            ShowStatus("   Getting FixedDocumentReaders.");
            ICollection <IXpsFixedDocumentReader> fixedDocuments =
                fixedDocSeqReader.FixedDocuments;

            ShowStatus("   Getting FixedPageReaders.");
            IEnumerator <IXpsFixedDocumentReader> enumerator =
                fixedDocuments.GetEnumerator();

            enumerator.MoveNext();
            ICollection <IXpsFixedPageReader> fixedPages =
                enumerator.Current.FixedPages;

            // Add a document structure to each fixed page.
            int i = 0;

            foreach (IXpsFixedPageReader fixedPageReader in fixedPages)
            {
                XpsResource pageStructure;
                ShowStatus("   Adding page structure resource:\n       '" +
                           Filename(_fixedPageStructures[i]) + "'");
                try
                {   // Add a new StoryFragment to hold the page structure.
                    pageStructure = fixedPageReader.AddStoryFragment();
                }
                catch (System.InvalidOperationException)
                {
                    MessageBox.Show(xpsUnstructuredFile +
                                    "\n\nDocument structure cannot be added.\n\n" +
                                    Filename(xpsUnstructuredFile) + " might already " +
                                    "contain an existing document structure.",
                                    "Cannot Add Document Structure",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    break;
                }

                // Copy the page structure to the new StoryFragment.
                WriteResource(pageStructure, _fixedPageStructures[i++]);
            }

            ShowStatus("   Saving and closing the new document.\n");
            xpsDocument.Close();
            //</SnippetDocStrucFixedDoc>
            //</SnippetDocStrucAddStructure>

            // Open the new structured document.
            OpenDocument(xpsTargetFile);

            ShowDescription(_descriptionString[4] + _descriptionString[5]);
            ShowPrompt(_descriptionString[5]);
        }// end:AddDocumentStructure
Example #39
0
        //public void openthisinviewer(int index)
        //{
        //    XpsDocument xpsdoc = new XpsDocument(_pageurls[index], System.IO.FileAccess.Read);
        //    this.documentViewer.Document = xpsdoc.GetFixedDocumentSequence();

        //}

        public string SaveDocumentPagesToImages(string dirPath)
        {

            XpsDocument doc = new XpsDocument(dirPath, FileAccess.Read);
            FixedDocumentSequence document = doc.GetFixedDocumentSequence();
            


            string newpath = "";
            MemoryStream[] streams = null;
            try
            {
                int pageCount = document.DocumentPaginator.PageCount ;
                DocumentPage[] pages = new DocumentPage[pageCount];
                for (int i = 0; i < pageCount; i++)
                    pages[i] = document.DocumentPaginator.GetPage(i);

                streams = new MemoryStream[pages.Count()];

                for (int i = 0; i < pages.Count(); i++)
                {
                    DocumentPage source = pages[i];
                    streams[i] = new MemoryStream();

                    RenderTargetBitmap renderTarget =
                       new RenderTargetBitmap((int)source.Size.Width,
                                               (int)source.Size.Height,
                                               96, // WPF (Avalon) units are 96dpi based
                                               96,
                                               System.Windows.Media.PixelFormats.Default);

                    renderTarget.Render(source.Visual);

                    JpegBitmapEncoder encoder = new JpegBitmapEncoder();  // Choose type here ie: JpegBitmapEncoder, etc
                    encoder.Rotation = Rotation.Rotate270;
                    encoder.QualityLevel = 100;
                    encoder.Frames.Add(BitmapFrame.Create(renderTarget));

                    encoder.Save(streams[i]);
                    newpath = dirPath.Replace(".xps", ".jpg");
                    FileStream file = new FileStream(newpath, FileMode.CreateNew);
                    file.Write(streams[i].GetBuffer(), 0, (int)streams[i].Length);
                    file.Close();
                    
                    streams[i].Position = 0;

                }
            }
            catch (Exception e1)
            {
                throw e1;
               
            }
            finally
            {
                if (streams != null)
                {
                    foreach (MemoryStream stream in streams)
                    {
                        stream.Close();
                        stream.Dispose();
                        doc.Close();
                        
                    }
                }
            }

            return newpath;
        }
Example #40
0
        }// end:OnOpen()

        // --------------------------- OpenDocument ---------------------------
        /// <summary>
        ///   Loads, displays, and enables user annotations
        ///   a given XPS document file.</summary>
        /// <param name="filename">
        ///   The path and filename of the XPS document
        ///   to load, display, and annotate.</param>
        /// <returns>
        ///   true if the document loads successfully; otherwise false.</returns>
        public bool OpenDocument(string filename)
        {
            // Load an XPS document into a DocumentViewer
            // and enable user Annotations.
            _xpsDocumentPath = filename;

            _packageUri = new Uri(filename, UriKind.Absolute);
            try
            {
                _xpsDocument = new XpsDocument(filename, FileAccess.Read);
            }
            catch (System.UnauthorizedAccessException)
            {   // If FileAccess is ReadWrite or Write.
                string msg = filename +
                             "\n\nThe specified file is Read-Only which " +
                             "prevents storing user annotations.";
                MessageBox.Show(msg, "Read-Only file",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }

            // Get the document's PackageStore into which
            // new user annotations will be added and saved.
            _xpsPackage = PackageStore.GetPackage(_packageUri);
            if ((_xpsPackage == null) || (_xpsDocument == null))
            {
                MessageBox.Show("Unable to get Package from file.");
                return(false);
            }

            // Get the FixedDocumentSequence from the open document.
            FixedDocumentSequence fds = _xpsDocument.GetFixedDocumentSequence();

            if (fds == null)
            {
                string msg = filename +
                             "\n\nThe document package within the specified " +
                             "file does not contain a FixedDocumentSequence.";
                MessageBox.Show(msg, "Package Error");
                return(false);
            }

            // Load the FixedDocumentSequence to the DocumentViewer control.
            docViewer.Document = fds;

            // Enable document menu controls.
            menuFileClose.IsEnabled        = true;
            menuFilePrint.IsEnabled        = true;
            menuViewAnnotations.IsEnabled  = true;
            menuViewIncreaseZoom.IsEnabled = true;
            menuViewDecreaseZoom.IsEnabled = true;

            // Enable user annotations on the document.
            Uri fixedDocumentSeqUri = GetFixedDocumentSequenceUri();

            if (menuViewAnnotations.IsChecked)
            {
                StartAnnotations();
            }

            // Give the DocumentViewer focus.
            docViewer.Focus();

            return(true);
        }// end:OpenDocument()
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow"/> class.
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            //-----------------------------------------------------------------

            if (this.settings.IsUpgraded == false)
            {
                this.settings.Upgrade();
                this.settings.IsUpgraded = true;
                this.settings.Save();
            }

            //if(string.IsNullOrEmpty( this.settings.UDPHost ))
            //{
            //    MB.Warning( "The value in the configuration file for the setting UDPHost is invalid!\nPlease correct the value and restart the application." );
            //    this.settings.UDPHost = "127.0.0.1";
            //}

            //if(this.settings.UDPPortSending < 1025 || this.settings.UDPPortSending > 65535)
            //{
            //    MB.Warning( "The value in the configuration file for the setting UDPPort is invalid!\nPlease correct the value and restart the application." );
            //    this.settings.UDPPortSending = 4242;
            //}

            //if(this.settings.UDPDelay < 0 || this.settings.UDPDelay > 10000)
            //{
            //    MB.Warning( "The value in the configuration file for the setting UDPDelay is invalid!\nPlease correct the value and restart the application." );
            //    this.settings.UDPDelay = 500;
            //}

            if (this.settings.MapZoomLevel < 1 || this.settings.MapZoomLevel > 20)
            {
                MB.Warning("The value in the configuration file for the setting MapZoomLevel is invalid!\nPlease correct the value and restart the application.");
                this.settings.MapZoomLevel = 18;
            }

            //-----------------------------------------------------------------

            this.DataContext = this;

            //-----------------------------------------------------------------

            if (Properties.Settings.Default.LastOpenFiles == null)
            {
                Properties.Settings.Default.LastOpenFiles = new StringCollection();
            }

            //-----------------------------------------------------------------

            InitMapControl();
            InitMapProvider();
            InitCommands();
            InitFileOpenSaveDialogs();
            InitTextEditorControls();

            //-----------------------------------------------------------------

            SetTitle();
            UpdateFileHistory();

            //-----------------------------------------------------------------

            this.lcvRFDevices = CollectionViewSource.GetDefaultView(this.RFDeviceViewModelCollection) as ListCollectionView;

            if (this.lcvRFDevices != null)
            {
                this.lcvRFDevices.IsLiveFiltering = true;
                this.lcvRFDevices.Filter          = IsWantedRFDevice;
            }

            //-----------------------------------------------------------------

            this.dgcbcRxTxType.ItemsSource = RxTxTypes.Values;

            List <RxTxType> lRxTxTypes = new List <RxTxType> {
                RxTxType.Empty
            };

            lRxTxTypes.AddRange(RxTxTypes.Values);
            this.cbRxTxType.ItemsSource = lRxTxTypes;

            this.cbAntennaType.ItemsSource = DisplayableEnumeration.GetCollection <AntennaType>();

            //-----------------------------------------------------------------

            this.RFDeviceTemplateCollection.Add(EMPTY_TEMPLATE);

            this.MetaInformation.PropertyChanged += MetaInformation_PropertyChanged;

            //-----------------------------------------------------------------

            using (XpsDocument xps = new XpsDocument("MarkdownCheatsheet.xps", FileAccess.Read))
            {
                this.dvMarkdownCheatsheet.Document = xps.GetFixedDocumentSequence();
            }
            this.dvMarkdownCheatsheet.FitToWidth();

            //-----------------------------------------------------------------

#if DEBUG
            //MessageMocker(@"O:\SIGENCE-ObiWanLansi-Tools\MessageHandler\java\messages\JammerDetection.xml");

            HelpConfigFactory.CreateTemplate(Properties.Settings.Default.HelpPath);

            this.RFDeviceTemplateCollection.Add(new RFDeviceTemplate(new RFDevice {
                Name = "GPS Jammer", Id = 1
            }));
            this.RFDeviceTemplateCollection.Add(new RFDeviceTemplate(new RFDevice {
                Name = "FMBroadcast", Id = 2
            }));
            this.RFDeviceTemplateCollection.Add(new RFDeviceTemplate(new RFDevice {
                Name = "NFMRadio", Id = 3
            }));
            this.RFDeviceTemplateCollection.Add(new RFDeviceTemplate(new RFDevice {
                Name = "AIS Sender", Id = 4
            }));

            this.RFDeviceTemplateCollection.Add(new RFDeviceTemplate(new RFDevice {
                Name = "B200 Mini", Id = -2
            }));
            this.RFDeviceTemplateCollection.Add(new RFDeviceTemplate(new RFDevice {
                Name = "HackRF", Id = -3
            }));
            this.RFDeviceTemplateCollection.Add(new RFDeviceTemplate(new RFDevice {
                Name = "TwinRx", Id = -4
            }));

            //LoadTemplates( @"D:\EigeneDateien\Entwicklung.GitHub\SIGENCE-Scenario-Tool\Examples\Templates.stt" );
            //ImportSettings(@"D:\EigeneDateien\Entwicklung.GitHub\SIGENCE-Scenario-Tool\Examples\mysettings.sts");

            //-----------------------------------------------------------------

            //try
            //{
            //    string strFilename = $"{Tool.StartupPath}\\tuebingen-regbez-latest.osm.sqlite";
            //    this.GeoNodeCollection = GeoNodeCollection.GetCollection(strFilename);
            //}
            //catch (Exception ex)
            //{
            //    MB.Error(ex);
            //}

            //this.lcvGeoNodes = CollectionViewSource.GetDefaultView(this.GeoNodeCollection) as ListCollectionView;

            //if (this.lcvGeoNodes != null)
            //{
            //    this.lcvGeoNodes.IsLiveFiltering = true;
            //    this.lcvGeoNodes.Filter = IsWantedGeoNode;
            //}

            //-----------------------------------------------------------------

            //CreateRandomizedRFDevices(10, true);

            //AddRFDevice( new RFDevice { PrimaryKey = Guid.Empty, Id = -1, Latitude = 1974, Longitude = 1974, StartTime = -1974 } );

            //AddRFDevice( new RFDevice
            //{
            //    Id = 42,
            //    DeviceSource = DeviceSource.User,
            //    Latitude = 47.666557,
            //    Longitude = 9.386941,
            //    AntennaType = AntennaType.HyperLOG60200,
            //    RxTxType = RxTxTypes.FMBroadcast,
            //    CenterFrequency_Hz = 90_000_000,
            //    Bandwidth_Hz = 30_000
            //} );

            //AddRFDevice( new RFDevice
            //{
            //    Id = -42,
            //    DeviceSource = DeviceSource.User,
            //    Latitude = 47.666100,
            //    Longitude = 9.172648,
            //    AntennaType = AntennaType.OmniDirectional,
            //    RxTxType = RxTxTypes.IdealSDR,
            //    CenterFrequency_Hz = 90_000_000,
            //    Bandwidth_Hz = 30_000
            //} );

            //CreateHeatmap();
            //CreateExampleRFDevices();

            //CreateRandomizedRFDevices(42);
            //OpenDeviceEditDialog(RFDevice.DUMMY);

            //-----------------------------------------------------------------

            RFDevice receiver = RFDevice.CreateDummy();
            receiver.Id        = -42;
            receiver.Longitude = 9.386941 + 0.1;
            receiver.Yaw       = 45;
            AddRFDevice(receiver);

            RFDevice refdevice = RFDevice.CreateDummy();
            refdevice.Id        = 0;
            refdevice.Longitude = 9.386941 + 0.2;
            refdevice.Yaw       = 45;
            AddRFDevice(refdevice);

            RFDevice sender = RFDevice.CreateDummy();
            sender.Id        = 42;
            sender.Longitude = 9.386941 + 0.3;
            sender.Yaw       = 45;
            AddRFDevice(sender);

            //-----------------------------------------------------------------

            //SaveFile( @"D:\BigData\GitHub\SIGENCE-Scenario-Tool\Examples\TestScenario.stf" );
            //LoadFile(@"D:\EigeneDateien\Entwicklung.GitHub\SIGENCE-Scenario-Tool\Examples\TestScenario.stf");

            //SaveFile( @"C:\Transfer\TestScenario.stf" );
            //LoadFile( @"C:\Transfer\TestScenario.stf" );


            //Reset();
            //LoadFile(@"D:\EigeneDateien\Entwicklung.GitHub\SIGENCE-Scenario-Tool\Examples\TestWrongAntennaType.stf");
            //LoadFile(@"D:\EigeneDateien\Entwicklung.GitHub\SIGENCE-Scenario-Tool\Examples\LongLineForSimulationPlayer.stf");

            //-----------------------------------------------------------------

            //RFDeviceList devicelist = GetDeviceList();

            //ExportRFDevices( devicelist, new FileInfo( @"D:\EigeneDateien\Entwicklung.GitHub\SIGENCE-Scenario-Tool\Examples\TestScenario.csv" ) );
            //ExportRFDevices( devicelist, new FileInfo( @"D:\EigeneDateien\Entwicklung.GitHub\SIGENCE-Scenario-Tool\Examples\TestScenario.xml" ) );
            //ExportRFDevices( devicelist, new FileInfo( @"D:\EigeneDateien\Entwicklung.GitHub\SIGENCE-Scenario-Tool\Examples\TestScenario.json" ) );
            //ExportRFDevices( devicelist, new FileInfo( @"D:\EigeneDateien\Entwicklung.GitHub\SIGENCE-Scenario-Tool\Examples\TestScenario.xlsx" ) );

            //-----------------------------------------------------------------

            this.QuickCommands.Add("new");
            this.QuickCommands.Add("rand 20");
            this.QuickCommands.Add("export csv");
            this.QuickCommands.Add("set rxtxtype unknown");
            this.QuickCommands.Add("set name nasenbär");
            this.QuickCommands.Add("remove");
            this.QuickCommands.Add("save");
            this.QuickCommands.Add("exit");

            //-----------------------------------------------------------------

            //OpenScenarioSimulationPlayer();

            //-----------------------------------------------------------------

            //InitMetaInformation();

            //this.tiEditDescription.IsSelected = true;
            //this.tiMetaInformation.IsSelected = true;


            //UpdateScenarioDescriptionMarkdown();

            ////string strMarkdown = $"{Tool.StartupPath}\\ExampleScenarioDescription.md";

            //this.MetaInformation.Version = "1.0";
            //this.MetaInformation.ApplicationContext = "Scenario Meta Information Test";
            //this.MetaInformation.ContactPerson = "Jörg Lanser";

            ////this.MetaInformation.Description = File.ReadAllText($"{Tool.StartupPath}\\ExampleScenarioDescription.md");
            ////this.MetaInformation.Stylesheet = "h1 { border: 1px solid red; }";
            //this.MetaInformation.SetDescriptionAndStylesheet(File.ReadAllText($"{Tool.StartupPath}\\ExampleScenarioDescription.md"), "h1 { border: 1px solid red; }");

            ////this.MetaInformation.Attachements.Add(new Attachement(new FileInfo($"{Tool.StartupPath}\\ExampleScenarioDescription.md"), AttachementType.Embedded));
            ////this.MetaInformation.Attachements.Add(new Attachement(new FileInfo($"{Tool.StartupPath}\\HelloWorld.py"), AttachementType.Embedded));
            ////this.MetaInformation.Attachements.Add(new Attachement(new FileInfo($"{Tool.StartupPath}\\CheatSheet.pdf"), AttachementType.Link));
            ////this.MetaInformation.Attachements.Add(new Attachement(new FileInfo($"{Tool.StartupPath}\\CheatSheet.xps"), AttachementType.Link));
            ////this.MetaInformation.Attachements.Add(new Attachement(new FileInfo($"{Tool.StartupPath}\\streets_bw.sqlite"), AttachementType.Link));

            //this.tecDescription.Text = this.MetaInformation.Description;
            //this.tecStyleSheet.Text = this.MetaInformation.Stylesheet;

            //this.tiMetaInformation.IsSelected = true;

            //-----------------------------------------------------------------

            //RFDevice device = new RFDevice().WithId(0).WithName("Hello").WithStartTime(5);
            //MB.Information(device.ToXml().ToString());
#else
            this.mMainMenu.Items.Remove(this.miTest);
            //this.tcTabControl.Items.Remove(this.tiGeoNodes);
            //this.tcTabControl.Items.Remove(this.tiMetaInformation);
#endif
        }
 public static void Print(FrameworkElement element)
 {
     XpsDocument xpsDoc = convertVisualToXps(element);
 }
Example #43
0
        /// <summary>
        /// Window has been activated
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">event details</param>
        private void Window_Activated(object sender, EventArgs e)
        {
            if (!_firstActivated)
            {
                return;
            }

            _firstActivated = false;

            Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(delegate
            {
                try
                {
                    ReportDocument reportDocument = new ReportDocument();

                    StreamReader reader          = new StreamReader(new FileStream(@"Templates\DemoReport.xaml", FileMode.Open, FileAccess.Read));
                    reportDocument.XamlData      = reader.ReadToEnd();
                    reportDocument.XamlImagePath = Path.Combine(Environment.CurrentDirectory, @"Templates\");
                    reader.Close();

                    DateTime dateTimeStart = DateTime.Now; // start time measure here

                    List <ReportData> listData = new List <ReportData>();
                    for (int i = 0; i < 2; i++) // generates multiple reports
                    {
                        ReportData data = new ReportData();

                        // set constant document values
                        data.ReportDocumentValues.Add("PrintDate", dateTimeStart); // print date is now
                        data.ReportDocumentValues.Add("ReportNumber", (i + 1));    // report number

                        // sample table "Ean"
                        DataTable table = new DataTable("Ean");
                        table.Columns.Add("Position", typeof(string));
                        table.Columns.Add("Item", typeof(string));
                        table.Columns.Add("EAN", typeof(string));
                        table.Columns.Add("Count", typeof(int));
                        table.Columns.Add("Test", typeof(double));
                        Random rnd = new Random(1234 + i);
                        int count  = rnd.Next(10) * (rnd.Next(2) + 1);
                        for (int j = 1; j <= count; j++)
                        {
                            // randomly create some articles
                            table.Rows.Add(new object[] { j, "Item " + (j + (1000 * (i + 1))).ToString("0000"), "123456790123", rnd.Next(9) + 1, 1.23456 });
                        }
                        data.DataTables.Add(table);
                        listData.Add(data);
                    }

                    XpsDocument xps         = reportDocument.CreateXpsDocument(listData);
                    documentViewer.Document = xps.GetFixedDocumentSequence();

                    // show the elapsed time in window title
                    Title += " - generated in " + (DateTime.Now - dateTimeStart).TotalMilliseconds + "ms";
                }
                catch (Exception ex)
                {
                    // show exception
                    MessageBox.Show(ex.Message + "\r\n\r\n" + ex.GetType() + "\r\n" + ex.StackTrace, ex.GetType().ToString(), MessageBoxButton.OK, MessageBoxImage.Stop);
                }
                finally
                {
                    busyDecorator.IsBusyIndicatorHidden = true;
                }
            }));
        }
Example #44
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            XpsDocument xps = new XpsDocument("Hilfe zum Pokémoneditor.xps", System.IO.FileAccess.Read);

            documentViewer1.Document = xps.GetFixedDocumentSequence();
        }
        public override void ExportTable(SIDocument doc, string filename)
        {
            var current = (uint)0;
            var total   = (uint)doc.Package.Rounds.Sum(round => round.Themes.Count);

            var document = new FlowDocument {
                PagePadding = new Thickness(0.0), ColumnWidth = double.PositiveInfinity, FontFamily = new FontFamily("Times New Roman")
            };
            var packageCaption = new Paragraph {
                KeepWithNext = true, Margin = new Thickness(10.0, 5.0, 0.0, 0.0)
            };

            var textP = new Run {
                FontSize = 30, FontWeight = FontWeights.Bold, Text = doc.Package.Name
            };

            packageCaption.Inlines.Add(textP);

            document.Blocks.Add(packageCaption);

            foreach (var round in doc.Package.Rounds)
            {
                var caption = new Paragraph {
                    KeepWithNext = true, Margin = new Thickness(10.0, 5.0, 0.0, 0.0)
                };

                var textC = new Run {
                    FontSize = 24, FontWeight = FontWeights.Bold, Text = round.Name
                };

                caption.Inlines.Add(textC);
                document.Blocks.Add(caption);

                var table = new Table {
                    CellSpacing = 0.0, BorderBrush = Brushes.Black, BorderThickness = new Thickness(0.0, 0.5, 0.0, 0.5)
                };
                var rowGroup     = new TableRowGroup();
                var columnNumber = round.Themes.Max(theme => theme.Questions.Count);

                for (int i = 0; i < columnNumber; i++)
                {
                    table.Columns.Add(new TableColumn());
                }

                foreach (var theme in round.Themes)
                {
                    var row = new TableRow();
                    foreach (var quest in theme.Questions)
                    {
                        var cell = new TableCell {
                            BorderBrush = Brushes.Black, BorderThickness = new Thickness(0.5), TextAlignment = TextAlignment.Center
                        };

                        var paragraph = new Paragraph {
                            Margin = new Thickness(10.0), KeepTogether = true
                        };

                        paragraph.Inlines.Add(string.Format(round.Type == RoundTypes.Standart ? "{0}, {1}" : "{0}", theme.Name, quest.Price));
                        paragraph.Inlines.Add(new LineBreak());
                        if (quest.Type.Name != QuestionTypes.Simple)
                        {
                            if (quest.Type.Name == QuestionTypes.Sponsored)
                            {
                                paragraph.Inlines.Add("ВОПРОС ОТ СПОНСОРА");
                            }
                            else if (quest.Type.Name == QuestionTypes.Auction)
                            {
                                paragraph.Inlines.Add("ВОПРОС-АУКЦИОН");
                            }
                            else if (quest.Type.Name == QuestionTypes.Cat)
                            {
                                paragraph.Inlines.Add("КОТ В МЕШКЕ");
                                paragraph.Inlines.Add(new LineBreak());
                                paragraph.Inlines.Add(string.Format("{0}, {1}", quest.Type[QuestionTypeParams.Cat_Theme], quest.Type[QuestionTypeParams.Cat_Cost]));
                            }
                            else if (quest.Type.Name == QuestionTypes.BagCat)
                            {
                                paragraph.Inlines.Add("КОТ В МЕШКЕ");
                                var knows = quest.Type[QuestionTypeParams.BagCat_Knows];
                                var cost  = quest.Type[QuestionTypeParams.Cat_Cost];
                                if (cost == "0")
                                {
                                    cost = "Минимум или максимум в раунде";
                                }

                                if (knows == QuestionTypeParams.BagCat_Knows_Value_Never)
                                {
                                    paragraph.Inlines.Add(new LineBreak());
                                    paragraph.Inlines.Add(string.Format("Сумма начисляется без вопроса: {0}", cost));
                                    continue;
                                }

                                paragraph.Inlines.Add(new LineBreak());
                                paragraph.Inlines.Add(string.Format("{0}, {1}", quest.Type[QuestionTypeParams.Cat_Theme], cost));

                                if (knows == QuestionTypeParams.BagCat_Knows_Value_Before)
                                {
                                    paragraph.Inlines.Add(new LineBreak());
                                    paragraph.Inlines.Add("Тема и стоимость оглашаются до передачи");
                                }

                                if (quest.Type[QuestionTypeParams.BagCat_Self] == QuestionTypeParams.BagCat_Self_Value_True)
                                {
                                    paragraph.Inlines.Add(new LineBreak());
                                    paragraph.Inlines.Add("Кота можно оставить себе");
                                }
                            }
                            else // Неподдерживаемый тип
                            {
                                paragraph.Inlines.Add(quest.Type.Name);
                                foreach (var param in quest.Type.Params)
                                {
                                    paragraph.Inlines.Add(new LineBreak());
                                    paragraph.Inlines.Add(string.Format(STR_Definition, param.Name, param.Value));
                                }
                            }

                            paragraph.Inlines.Add(new LineBreak());
                        }

                        paragraph.Inlines.Add(new LineBreak());
                        paragraph.Inlines.Add(quest.Scenario.ToString());

                        cell.Blocks.Add(paragraph);
                        row.Cells.Add(cell);
                    }
                    rowGroup.Rows.Add(row);

                    current++;

                    // прогресс current из total
                }
                table.RowGroups.Add(rowGroup);
                document.Blocks.Add(table);
            }

            using (var package = System.IO.Packaging.Package.Open(filename, FileMode.Create))
            {
                using (var xpsDocument = new XpsDocument(package))
                {
                    using (var manager = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false))
                    {
                        var paginator = ((IDocumentPaginatorSource)document).DocumentPaginator;
                        paginator.PageSize = new Size(1056.0, 816.0); // A4
                        manager.SaveAsXaml(paginator);
                        manager.Commit();
                    }
                }
            }
        }
Example #46
0
        private static string PrintToPDF(FrameworkElement kundeInfo, ScrollViewer scrollViewer, string lagreTilUrl, bool liggende)
        {
            if (kundeInfo == null && scrollViewer == null)
            {
                return("");
            }

            string prisforslagXPSuri = Path.Combine(Hjelpeklasser.GlobaleUrier.standardMappe2(), "Prisforslag.xps");
            string prisforslagPDFuri = Path.Combine(Hjelpeklasser.GlobaleUrier.standardMappe2(), "Prisforslag.pdf");

            if (!string.IsNullOrEmpty(lagreTilUrl))
            {
                prisforslagPDFuri = lagreTilUrl;
            }

            if (File.Exists(prisforslagXPSuri))
            {
                File.Delete(prisforslagXPSuri);
            }
            XpsDocument       _xpsDocument = new XpsDocument(prisforslagXPSuri, FileAccess.ReadWrite);
            XpsDocumentWriter xpsdw        = XpsDocument.CreateXpsDocumentWriter(_xpsDocument);

            Size docSize;

            if (liggende)
            {
                docSize = new Size(1122.24, 793.59874015748028);
            }
            else
            {
                docSize = new Size(793.59874015748028, 1122.24);
            }

            double leftMargin   = 84.5; //Margins.Left - area.OriginWidth;
            double topMargin    = 84.5; ///Margins.Top - area.OriginHeight;
            double rightMargin  = 84.5; //Margins.Right - (docSize.Width - area.ExtentWidth - area.OriginWidth);
            double bottomMargin = 84.5; //Margins.Bottom - (docSize.Height - area.ExtentHeight - area.OriginHeight);
            Size   outputSize   = new Size(
                docSize.Width - leftMargin - rightMargin,
                docSize.Height - topMargin - bottomMargin);


            SerializerWriterCollator batchPrinter = xpsdw.CreateVisualsCollator();

            batchPrinter.BeginBatchWrite();

            if (kundeInfo != null)
            {
                printKundeinfoToPdf(batchPrinter, kundeInfo, outputSize, leftMargin, topMargin);
            }
            if (scrollViewer != null && scrollViewer.Content != null)
            {
                printScrollViewer(batchPrinter, scrollViewer, outputSize, leftMargin, topMargin);
            }

            batchPrinter.EndBatchWrite();

            _xpsDocument.Close();
            PdfSharp.Xps.XpsConverter.Convert(prisforslagXPSuri, prisforslagPDFuri, 0);



            return(prisforslagPDFuri);
        }
Example #47
0
        private void OnPrintPreview(object sender, ExecutedRoutedEventArgs e)
        {
            PrintDialog printDialog = new PrintDialog();

            printDialog.PageRangeSelection   = PageRangeSelection.AllPages;
            printDialog.UserPageRangeEnabled = true;
            bool?dialogResult = printDialog.ShowDialog();

            if (dialogResult != null && dialogResult.Value == false)
            {
                return;
            }

            FlowDocument printSource = this.CreateFlowDocumentForEditor();

            // Save all the existing settings.
            double    pageHeight  = printSource.PageHeight;
            double    pageWidth   = printSource.PageWidth;
            Thickness pagePadding = printSource.PagePadding;
            double    columnGap   = printSource.ColumnGap;
            double    columnWidth = printSource.ColumnWidth;

            // Make the FlowDocument page match the printed page.
            printSource.PageHeight  = printDialog.PrintableAreaHeight;
            printSource.PageWidth   = printDialog.PrintableAreaWidth;
            printSource.PagePadding = new Thickness(20);
            printSource.ColumnGap   = Double.NaN;
            printSource.ColumnWidth = printDialog.PrintableAreaWidth;

            Size pageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight);

            MemoryStream xpsStream        = new MemoryStream();
            Package      package          = Package.Open(xpsStream, FileMode.Create, FileAccess.ReadWrite);
            string       packageUriString = "memorystream://data.xps";

            PackageStore.AddPackage(new Uri(packageUriString), package);

            XpsDocument       xpsDocument = new XpsDocument(package, CompressionOption.Normal, packageUriString);
            XpsDocumentWriter writer      = XpsDocument.CreateXpsDocumentWriter(xpsDocument);

            DocumentPaginator paginator = ((IDocumentPaginatorSource)printSource).DocumentPaginator;

            paginator.PageSize = pageSize;
            paginator.ComputePageCount();

            writer.Write(paginator);

            // Reapply the old settings.
            printSource.PageHeight  = pageHeight;
            printSource.PageWidth   = pageWidth;
            printSource.PagePadding = pagePadding;
            printSource.ColumnGap   = columnGap;
            printSource.ColumnWidth = columnWidth;

            PrintPreviewWindow printPreview = new PrintPreviewWindow();

            printPreview.Width  = this.ActualWidth;
            printPreview.Height = this.ActualHeight;
            printPreview.Owner  = Application.Current.MainWindow;

            printPreview.LoadDocument(xpsDocument, package, packageUriString);

            printPreview.Show();
        }
Example #48
0
        private void Window_Activated(object sender, EventArgs e)
        {
            try
            {
                ReportDocument reportDocument = new ReportDocument();

                StreamReader reader = new StreamReader(new FileStream(@"Templates\SpareSalesByCodePeriodReport.xaml", FileMode.Open, FileAccess.Read));
                reportDocument.XamlData      = reader.ReadToEnd();
                reportDocument.XamlImagePath = System.IO.Path.Combine(Environment.CurrentDirectory, @"Templates\");
                reader.Close();

                ReportData data = new ReportData();
                DataAccess da   = new DataAccess();
                string     BCC  = da.getBasicCurrencyCode();

                // Таблица ТОВАРЫ В НАКЛАДНОЙ
                DataTable dt = new DataTable("mtable");

                // описываем столбцы таблицы
                dt.Columns.Add("Num", typeof(int));
                dt.Columns.Add("WarehouseName", typeof(string));
                dt.Columns.Add("OutgoNum", typeof(string));
                dt.Columns.Add("AccountName", typeof(string));
                dt.Columns.Add("OutgoDate", typeof(string));
                dt.Columns.Add("Q", typeof(int));
                dt.Columns.Add("P", typeof(double));
                dt.Columns.Add("VAT", typeof(string));
                dt.Columns.Add("T", typeof(double));

                // забиваем таблицу данными
                List <SpareInSpareOutgoView> LIST2 = da.GetSpareInSpareOutgoByCodePeriod(Spare.id, dateFrom, dateTo, WarehouseID);
                decimal asum = 0;
                try
                {
                    for (int i = 0; i < LIST2.Count; i++)
                    {
                        asum += LIST2[i].total_sum;
                        string      AN      = LIST2[i].AccountName;
                        string      od      = LIST2[i].OutgoDate.Value.ToShortDateString();
                        string      on      = "нет";
                        int         OutgoID = LIST2[i].spare_outgo_id;
                        spare_outgo so      = da.SpareOutgoGet(OutgoID);
                        if (so != null)
                        {
                            on = so.IDN.ToString();
                        }
                        dt.Rows.Add(new object[] {
                            i + 1,
                            LIST2[i].WarehouseName,
                            on,
                            AN,
                            od,
                            LIST2[i].quantity,
                            LIST2[i].purchase_price,
                            LIST2[i].VatRateName,
                            LIST2[i].total_sum
                        });
                    }
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                string str_ts  = RSDN.RusCurrency.Str(asum, "BYR");
                string strDate = dateFrom.Day.ToString();
                string mnth    = "";
                switch (dateFrom.Month)
                {
                case 1:
                    mnth = "января";
                    break;

                case 2:
                    mnth = "февраля";
                    break;

                case 3:
                    mnth = "марта";
                    break;

                case 4:
                    mnth = "апреля";
                    break;

                case 5:
                    mnth = "мая";
                    break;

                case 6:
                    mnth = "июня";
                    break;

                case 7:
                    mnth = "июля";
                    break;

                case 8:
                    mnth = "августа";
                    break;

                case 9:
                    mnth = "сентября";
                    break;

                case 10:
                    mnth = "октября";
                    break;

                case 11:
                    mnth = "ноября";
                    break;

                case 12:
                    mnth = "декабря";
                    break;
                }
                strDate += " " + mnth + " " + dateFrom.Year + " г.";

                data.ReportDocumentValues.Add("ReportDate1", strDate); // print date is now

                // =======================
                strDate = dateTo.Day.ToString();
                mnth    = "";
                switch (dateTo.Month)
                {
                case 1:
                    mnth = "января";
                    break;

                case 2:
                    mnth = "февраля";
                    break;

                case 3:
                    mnth = "марта";
                    break;

                case 4:
                    mnth = "апреля";
                    break;

                case 5:
                    mnth = "мая";
                    break;

                case 6:
                    mnth = "июня";
                    break;

                case 7:
                    mnth = "июля";
                    break;

                case 8:
                    mnth = "августа";
                    break;

                case 9:
                    mnth = "сентября";
                    break;

                case 10:
                    mnth = "октября";
                    break;

                case 11:
                    mnth = "ноября";
                    break;

                case 12:
                    mnth = "декабря";
                    break;
                }
                strDate += " " + mnth + " " + dateTo.Year + " г.";
                data.ReportDocumentValues.Add("ReportDate2", strDate); // print date is now

                data.ReportDocumentValues.Add("SpareName", Spare.name);
                data.ReportDocumentValues.Add("SpareCodeShatem", Spare.codeShatem);
                data.ReportDocumentValues.Add("SpareCode", Spare.code);
                data.ReportDocumentValues.Add("asum", asum);
                data.DataTables.Add(dt);

                DateTime    dateTimeStart = DateTime.Now; // start time measure here
                XpsDocument xps           = reportDocument.CreateXpsDocument(data);
                documentViewer.Document = xps.GetFixedDocumentSequence();
            }
            catch (Exception ex)
            {
                // show exception
                MessageBox.Show(ex.Message + "\r\n\r\n" + ex.GetType() + "\r\n" + ex.StackTrace, ex.GetType().ToString(), MessageBoxButton.OK, MessageBoxImage.Stop);
            }
        }
Example #49
0
        private void Load()
        {
            XpsDocument doc = new XpsDocument("Documents/LastStepAfterLoading.xps", System.IO.FileAccess.Read);

            documentViewer.Document = doc.GetFixedDocumentSequence();
        }
        private void RunReportHelper()
        {
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Send, (SendOrPostCallback) delegate { View.StartSyncAnimation(); }, null);

            SqlConnection con = new SqlConnection(PosSettings.Default.possiteConnectionString); //DataModule.CurrDataSourcePath);

            try
            {
                con.Open();
                string query = "select store_name, trans_item.trans_no, trans_item.line_no as sales_line, tax_id, tax_desc, rate, " +
                               "taxable_amount, tax_amount, sku, item_desc, quantity, amount, ext_amount, promotion_amount, " +
                               "trans.store_no, cast ([possite].[dbo].[ufn_GetDateOnly](start_time) as varchar(12) )  as trans_date " +
                               "from trans_item join trans " +
                               "on (trans_item.trans_no= trans.trans_no and trans_item.organization_no= trans.organization_no and  " +
                               "trans.store_no = trans_item.store_no ) " +
                               "join retail_store on " +
                               "(trans.store_no=retail_store.store_no and trans.organization_no = retail_store.organization_no) " +
                               "left outer join trans_promotion  " +
                               "on (trans_item.organization_no = trans_promotion.organization_no and trans_item.store_no = trans_promotion.store_no and trans_item.trans_no = trans_promotion.trans_no and trans_item.line_no = trans_promotion.line_no ) " +
                               "left outer join trans_tax " +
                               "on (trans_item.trans_no = trans_tax.trans_no and  trans_item.line_no = trans_tax.line_no and " +
                               " trans_item.organization_no = trans_tax.organization_no and trans_item.store_no = trans_tax.store_no  ) " +
                               "where trans.state=2 " +
                               " and trans_item.state = 2 " +
                               " and trans.organization_no >= @organizationFrom and trans.organization_no <= @organizationTo " +
                               " and trans.store_no >= @storeFrom and trans.store_no <= @storeTo " +
                               " and [possite].[dbo].[ufn_GetDateOnly](start_time) >= @salesDateFrom and [possite].[dbo].[ufn_GetDateOnly](start_time) <= @salesDateTo " +
                               "order by store_name, trans_date, trans_item.trans_no, trans_item.line_no ";

                SqlCommand comm = new SqlCommand(query, con);
                comm.Parameters.Add("@organizationFrom", SqlDbType.Char).Value  = View.OrganizationNoFrom;
                comm.Parameters.Add("@organizationTo", SqlDbType.Char).Value    = View.OrganizationNoTo;
                comm.Parameters.Add("@storeFrom", SqlDbType.Char).Value         = View.StoreNoFrom;
                comm.Parameters.Add("@storeTo", SqlDbType.Char).Value           = View.StoreNoTo;
                comm.Parameters.Add("@salesDateFrom", SqlDbType.DateTime).Value = View.SalesDateFrom;
                comm.Parameters.Add("@salesDateTo", SqlDbType.DateTime).Value   = View.SalesDateTo;
                SqlDataAdapter dataAdapter = new SqlDataAdapter(comm);
                DataTable      dataTable1  = new DataTable("trans_items");
                dataAdapter.Fill(dataTable1);
                SqlDataReader dataReader = comm.ExecuteReader();


                ReportData       rData = DataEngine.Load(dataReader, new string[] { "store_name", "trans_date" });
                ReportDefinition rDef  = new ReportDefinition();
                rDef.ReportName = "TaxDetails";

                rDef.Page.Margin = new Size(40, 70);
                //Header definition
                rDef.HeaderTemplate = "<Section><Paragraph TextAlignment=\"Center\" FontWeight=\"Bold\" FontSize=\"12\">Tax Details Report</Paragraph></Section>";


                //Table definition
                rDef.TableDefinition = "<Table>" +
                                       "<Table.Columns> " +
                                       "<TableColumn Width=\"*\"/>" +
                                       "<TableColumn Width=\"2*\"/> " +
                                       "<TableColumn Width=\".5*\"/> " +
                                       "<TableColumn Width=\"*\"/> " +
                                       "<TableColumn Width=\"*\"/> " +
                                       "<TableColumn Width=\"*\"/> " +
                                       "<TableColumn Width=\".5*\"/> " +
                                       "<TableColumn Width=\"*\"/> " +
                                       "</Table.Columns> " +
                                       "</Table>";


                //Item definition
                rDef.ItemTemplate = "<TableRow>" +
                                    "<TableCell >" +
                                    "<Paragraph FontSize=\"12\">" +
                                    "<c:FormattedRun PropertyName=\"trans_no\"/>" + "/" + "<c:FormattedRun PropertyName=\"sales_line\"/>" +
                                    "</Paragraph>" +
                                    "</TableCell>" +
                                    "<TableCell >" +
                                    "<Paragraph FontSize=\"12\">" +
                                    "<c:FormattedRun PropertyName=\"item_desc\"/>" +
                                    "</Paragraph>" +
                                    "</TableCell>" +

                                    "<TableCell >" +
                                    "<Paragraph TextAlignment=\"Right\" FontSize=\"12\">" +
                                    "<c:FormattedRun PropertyName=\"rate\"/>" +
                                    "</Paragraph>" +
                                    "</TableCell>" +
                                    "<TableCell >" +
                                    "<Paragraph TextAlignment=\"Right\" FontSize=\"12\">" +
                                    "<c:FormattedRun PropertyName=\"taxable_amount\"/>" +
                                    "</Paragraph>" +
                                    "</TableCell>" +
                                    "<TableCell >" +
                                    "<Paragraph TextAlignment=\"Right\" FontSize=\"12\">" +
                                    "<c:FormattedRun PropertyName=\"tax_amount\"/>" +
                                    "</Paragraph>" +
                                    "</TableCell>" +
                                    "<TableCell >" +
                                    "<Paragraph TextAlignment=\"Right\" FontSize=\"12\">" +
                                    "<c:FormattedRun PropertyName=\"amount\"/>" +
                                    "</Paragraph>" +
                                    "</TableCell>" +
                                    "<TableCell >" +
                                    "<Paragraph TextAlignment=\"Right\" FontSize=\"12\">" +
                                    "<c:FormattedRun PropertyName=\"promotion_amount\"/>" +
                                    "</Paragraph>" +
                                    "</TableCell>" +
                                    "<TableCell >" +
                                    "<Paragraph TextAlignment=\"Right\" FontSize=\"12\">" +
                                    "<c:FormattedRun PropertyName=\"ext_amount\"/>" +
                                    "</Paragraph>" +
                                    "</TableCell>" +
                                    "</TableRow>";

                //Footer definition
                rDef.FooterTemplate = "<Section><Paragraph TextAlignment=\"Center\" FontSize=\"12\">*** End of tax detail report ***</Paragraph></Section>";


                rDef.Page.HeaderTemplate = "<Section>" +
                                           "<Paragraph TextAlignment=\"Right\" FontSize=\"12\" >" +
                                           "Page @PageNumber from @PageCount" +
                                           "</Paragraph>" +
                                           "</Section>";
                string strDate = System.DateTime.Now.ToShortDateString();
                string strTime = System.DateTime.Now.ToShortTimeString();
                rDef.Page.FooterTemplate = "<Section>" +
                                           "<Paragraph TextAlignment=\"Right\" FontSize=\"12\" >" +
                                           "Date: " + strDate + "  " + "Time: " + strTime +
                                           "</Paragraph>" +
                                           "</Section>";



                //Group definitions
                GroupDefinition def1 = new GroupDefinition();
                def1.HeaderTemplate = "<TableRowGroup>" +
                                      "<TableRow>" +
                                      "<TableCell ColumnSpan=\"3\">" +
                                      "<Paragraph FontWeight=\"Bold\" FontSize=\"12\">Store: " +
                                      "<c:FormattedRun PropertyName=\"store_name\"/> " +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "</TableRow>" +
                                      "<TableRow>" +
                                      "<TableCell>" +
                                      "<Paragraph FontWeight=\"Bold\" FontSize=\"12\">Receipt no</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph FontWeight=\"Bold\" FontSize=\"12\">Item desc.</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph FontWeight=\"Bold\" TextAlignment=\"Right\"  FontSize=\"12\">Rate</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph FontWeight=\"Bold\" TextAlignment=\"Right\"  FontSize=\"12\">Taxable amount</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph FontWeight=\"Bold\" TextAlignment=\"Right\"  FontSize=\"12\">Tax</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph FontWeight=\"Bold\" TextAlignment=\"Right\"   FontSize=\"12\">Price</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph FontWeight=\"Bold\" TextAlignment=\"Right\"  FontSize=\"12\">Disc.</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph FontWeight=\"Bold\" TextAlignment=\"Right\"  FontSize=\"12\">Amount</Paragraph>" +
                                      "</TableCell>" +
                                      "</TableRow>" +
                                      "</TableRowGroup>";



                def1.FooterTemplate = "<TableRowGroup > " +
                                      "<TableRow>" +
                                      "<TableCell ColumnSpan=\"3\">" +
                                      "<Paragraph FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "Total for:" +
                                      "<c:FormattedRun PropertyName=\"store_name\"/> " +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "<c:FormattedRun PropertyName=\"taxable_amount\"/>" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "<c:FormattedRun PropertyName=\"tax_amount\"/>" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "<c:FormattedRun PropertyName=\"ext_amount\"/>" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "</TableRow>" +
                                      "<TableRow>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "---------" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "---------" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "----------" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "</TableRow>" +
                                      "</TableRowGroup>";


                def1.NewPageOnGroupBreak = true;


                GroupDefinition def2 = new GroupDefinition();
                def2.HeaderTemplate = "<TableRowGroup>" +
                                      "<TableRow>" +
                                      "<TableCell ColumnSpan=\"3\">" +
                                      "<Paragraph FontWeight=\"Bold\" FontSize=\"12\">Date: " +
                                      "<c:FormattedRun PropertyName=\"trans_date\"/>" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "</TableRow>" +
                                      "</TableRowGroup>";



                def2.FooterTemplate = "<TableRowGroup > " +
                                      "<TableRow>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "---------" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "---------" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "----------" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "</TableRow>" +
                                      "<TableRow>" +
                                      "<TableCell ColumnSpan=\"2\">" +
                                      "<Paragraph FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "Total for:" +
                                      "<c:FormattedRun PropertyName=\"trans_date\"/>" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "<c:FormattedRun PropertyName=\"taxable_amount\"/>" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "<c:FormattedRun PropertyName=\"tax_amount\"/>" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "<c:FormattedRun PropertyName=\"ext_amount\"/>" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "</TableRow>" +
                                      "<TableRow>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "---------" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "---------" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "</TableCell>" +
                                      "<TableCell>" +
                                      "<Paragraph TextAlignment=\"Right\" FontWeight=\"Bold\" FontSize=\"12\">" +
                                      "---------" +
                                      "</Paragraph>" +
                                      "</TableCell>" +
                                      "</TableRow>" +
                                      "</TableRowGroup>";


                def2.NewPageOnGroupBreak = false;



                List <GroupDefinition> grpDef = new List <GroupDefinition>();
                grpDef.Add(def1);
                grpDef.Add(def2);

                rDef.Groups = grpDef;



                ReportEngine repEngine = _container.Resolve <ReportEngine>() as ReportEngine;

                xpsRep = repEngine.CreateReport(rDef, rData);
                con.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Send, (SendOrPostCallback) delegate { this.DisplayReport(); }, null);
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Send, (SendOrPostCallback) delegate { View.EndSyncAnimation(); }, null);
        }
Example #51
0
        /// <summary>
        /// build a html document based on an xps file
        /// </summary>
        /// <param name="path">path where the xps will be found and the html will be generated</param>
        private void BuildDocumentHTML(object args)
        {
            BuildDocumentHTMLArgs bdha = args as BuildDocumentHTMLArgs;
            String             path    = bdha.path;
            ProcessingProgress pp      = bdha.pp;

            XpsDocument xpsDoc = new XpsDocument(path + DD + "document.xps", System.IO.FileAccess.Read, CompressionOption.Normal);

            FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence();

            System.IO.StreamWriter fileO = new System.IO.StreamWriter(path + DD + "document.html", false);
            fileO.WriteLine("<html><body>");

            //~~~~~~~~~~~~~progress~~~~~~~~~~~~~//
            pp.OverallOperationTotalElements = docSeq.DocumentPaginator.PageCount;
            pp.OverallOperationElement       = 0;
            //~~~~~~~~~~~~~progress~~~~~~~~~~~~~//

            // You can get the total page count from docSeq.PageCount
            for (int pageNum = 0; pageNum < docSeq.DocumentPaginator.PageCount; ++pageNum)
            {
                //~~~~~~~~~~~~~progress~~~~~~~~~~~~~//
                pp.CurrentOperationName          = "Page " + (pageNum + 1);
                pp.CurrentOperationTotalElements = 3;
                pp.CurrentOperationElement       = 0;
                //~~~~~~~~~~~~~progress~~~~~~~~~~~~~//

                DocumentPage       docPage      = docSeq.DocumentPaginator.GetPage(pageNum);
                BitmapImage        bitmap       = new BitmapImage();
                RenderTargetBitmap renderTarget =
                    new RenderTargetBitmap((int)docPage.Size.Width,
                                           (int)docPage.Size.Height,
                                           96,  // WPF (Avalon) units are 96dpi based
                                           96,
                                           System.Windows.Media.PixelFormats.Default);

                renderTarget.Render(docPage.Visual);

                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(renderTarget));

                //~~~~~~~~~~~~~progress~~~~~~~~~~~~~//
                pp.CurrentOperationElement = 1;
                //~~~~~~~~~~~~~progress~~~~~~~~~~~~~//

                FileStream pageOutStream = new FileStream(path + DD + "page" + (pageNum + 1) + ".png", FileMode.Create, FileAccess.Write);
                encoder.Save(pageOutStream);
                pageOutStream.Close();

                //~~~~~~~~~~~~~progress~~~~~~~~~~~~~//
                pp.CurrentOperationElement = 2;
                //~~~~~~~~~~~~~progress~~~~~~~~~~~~~//

                fileO.WriteLine("<div align=\"center\"><img src=\"" + path + DD + "page" + (pageNum + 1) + ".png\"/></div>");

                //~~~~~~~~~~~~~progress~~~~~~~~~~~~~//
                pp.CurrentOperationElement = 3;
                pp.OverallOperationElement = pageNum + 1;
                //~~~~~~~~~~~~~progress~~~~~~~~~~~~~//
            }
            fileO.WriteLine("</body></html>");
            fileO.Flush();
            fileO.Close();
            docSeq = null;
            xpsDoc.Close();
            xpsDoc = null;
        }
Example #52
0
        /// <summary>
        /// Return a List of Signer in the package
        /// </summary>
        /// <returns>
        /// Package Path (string), Signer Name (string), Signer URI (string), Signer Issuer (string)
        /// </returns>
        public Signers GetDigitalSigners()
        {
            Signers sigs = new Signers();

            sigs.Path = signers.Path;

            List <X509Certificate2> certificateList      = new List <X509Certificate2>();
            List <XmlSignaturePart> xmlSignaturePartList = this.GetDigitalSignatures();

            if (DocumentType.Equals(Types.XpsDocument))
            {
                //To collect the information of the signature we used XPS like a System.IO.Packaging

                xpsDocument.Close();
                package = Package.Open(signers.Path, FileMode.Open, FileAccess.Read);

                PackageDigitalSignatureManager _signatures = null;
                _signatures = new PackageDigitalSignatureManager(package);
                _signatures.CertificateOption = CertificateEmbeddingOption.InSignaturePart;

                // Add the signers in the list
                foreach (PackageDigitalSignature signature in _signatures.Signatures)
                {
                    string           name   = signature.Signer.Subject.Replace("CN=", "");
                    string           uri    = signature.SignaturePart.Uri.ToString();
                    string           date   = signature.SigningTime.ToString();
                    string           issuer = signature.Signer.Issuer.Replace("CN=", "");
                    string           serial = signature.Signer.GetSerialNumberString();
                    X509Certificate2 signatureCertificate = (X509Certificate2)signature.Signer;

                    sigs.Add(name, uri, issuer, date, serial, signatureCertificate);
                }
                package.Close();
                xpsDocument = new XpsDocument(signers.Path, FileAccess.ReadWrite);
                return(sigs);
            }
            else if (DocumentType.Equals(Types.PdfDocument))
            {
                if (this.pdfSignatureList == null)
                {
                    try
                    {
                        this.pdfSignatureList = CertificadoDigital.Validate.validateFile(pdfDocumentPath);
                    }
                    catch (CertificadoDigital.NoSignatureFoundException nsfe) { }
                }

                if (this.pdfSignatureList != null)
                {
                    foreach (CertificadoDigital.Signature sig in this.pdfSignatureList)
                    {
                        string name   = sig.OfficeTemplateSubject().Replace("CN=", "");
                        string uri    = null;
                        string date   = sig.DateTime.ToString();
                        string issuer = sig.OfficeTemplateIssuer().Replace("CN=", "");
                        string serial = sig.Certificates[0].Serial;

                        sigs.Add(name, uri, issuer, date, serial, sig.X509Certificate);
                    }
                }

                return(sigs);
            }
            else
            {
                PackageDigitalSignatureManager _signatures = null;
                _signatures = new PackageDigitalSignatureManager(package);
                _signatures.CertificateOption = CertificateEmbeddingOption.InSignaturePart;

                // Add the signers in the list
                foreach (PackageDigitalSignature signature in _signatures.Signatures)
                {
                    string           name   = signature.Signer.Subject.Replace("CN=", "");
                    string           uri    = signature.SignaturePart.Uri.ToString();
                    string           date   = signature.SigningTime.ToString();
                    string           issuer = signature.Signer.Issuer.Replace("CN=", "");
                    string           serial = signature.Signer.GetSerialNumberString();
                    X509Certificate2 signatureCertificate = (X509Certificate2)signature.Signer;

                    sigs.Add(name, uri, issuer, date, serial, signatureCertificate);
                }
                return(sigs);
            }
        }
        public override IXpsDocumentWrapper GetHelp()
        {
            var document = new XpsDocument(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Help.xps"), FileAccess.Read);

            return(new XpsDocumentWrapper(document));
        }
Example #54
0
        public Файл ВыводОтчета(string НазваниеОтчета, string ИсходныйКод, string ИсходныйФорматОтчета, ФорматОтчета ФорматОтчета, ШаблонОтчета.Ориентация Ориентация, DataSet ds, Хранилище Хранилище, string user, string domain)
        {
            var file = null as Файл;

            try
            {
                if (ds == null)
                {
                    new Exception("Не определен DataSet");
                }

                var extension = string.Empty;
                var mime      = MimeType.НеОпределен;
                switch (ИсходныйФорматОтчета)
                {
                case "Xps":
                    extension = "xps";
                    mime      = MimeType.Xps;
                    break;

                case "Excel":
                    extension = "xls";
                    mime      = MimeType.Excel;
                    break;

                case "Word":
                    extension = "doc";
                    mime      = MimeType.Word;
                    break;

                case "Text Plain":
                    extension = "txt";
                    mime      = MimeType.Text;
                    break;

                case "Excel-PDF":
                case "Word-PDF":
                    extension = "pdf";
                    break;

                default:
                    throw new Exception("Не верно указан 'Исходный формат отчета'");
                }
                file = new Файл()
                {
                    Name = string.Format("{0}_{1:yyyymmdd_HHmmss}.{2}", FileNameValid(НазваниеОтчета), DateTime.Now, extension), MimeType = mime
                };
                var task = new System.Threading.Tasks.Task(() =>
                {
                    try
                    {
                        using (var msXml = new MemoryStream())
                        {
                            var processor   = new Saxon.Api.Processor();
                            var compiler    = processor.NewXsltCompiler();
                            var transformer = compiler.Compile(new StringReader(ИсходныйКод)).Load();
                            var dest        = new Saxon.Api.TextWriterDestination(XmlTextWriter.Create(msXml));

                            transformer.InitialContextNode = processor.NewDocumentBuilder().Build(new XmlDataDocument(ds));
                            transformer.Run(dest);

                            switch (ИсходныйФорматОтчета)
                            {
                            case "Xps":
                                {
                                    file.MimeType = MimeType.Xps;
                                    switch (ФорматОтчета)
                                    {
                                        #region Отчет Xaml (по-умолчанию)
                                    case ФорматОтчета.Xaml:
                                    case ФорматОтчета.ПоУмолчанию:
                                        {
                                            file.Stream = msXml.ToArray();
                                        }
                                        break;
                                        #endregion

                                        #region Отчет Xps
                                    case ФорматОтчета.Xps:
                                    default:
                                        {
                                            var documentUri = Path.GetTempFileName();
                                            try
                                            {
                                                msXml.Position = 0;
                                                var sourceDoc  = XamlReader.Load(msXml) as IDocumentPaginatorSource;

                                                var doc = new XpsDocument(documentUri, FileAccess.Write, CompressionOption.Normal);
                                                var xsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
                                                var pgn = sourceDoc.DocumentPaginator;
                                                // 1cm = 38px
                                                switch (Ориентация)
                                                {
                                                case ШаблонОтчета.Ориентация.Альбом:
                                                    {
                                                        pgn.PageSize = new System.Windows.Size(29.7 * (96 / 2.54), 21 * (96 / 2.54));
                                                    }
                                                    break;

                                                case ШаблонОтчета.Ориентация.Книга:
                                                default:
                                                    {
                                                        pgn.PageSize = new System.Windows.Size(21 * (96 / 2.54), 29.7 * (96 / 2.54));
                                                    }
                                                    break;
                                                }
                                                //необходимо фиксированно указать размер колонки документа иначе при
                                                //построении часть данных будет срезано
                                                if (sourceDoc is FlowDocument)
                                                {
                                                    ((FlowDocument)sourceDoc).ColumnWidth = pgn.PageSize.Width;
                                                }
                                                xsm.SaveAsXaml(pgn);

                                                doc.Close();
                                                file.Stream = System.IO.File.ReadAllBytes(documentUri);
                                            }
                                            finally
                                            {
                                                if (System.IO.File.Exists(documentUri))
                                                {
                                                    System.IO.File.Delete(documentUri);
                                                }
                                            }
                                        }
                                        break;
                                        #endregion
                                    }
                                }
                                break;

                            case "TextPlain":
                                {
                                    file.MimeType = MimeType.Text;
                                    file.Stream   = msXml.ToArray();
                                }
                                break;

                            case "Word-PDF":
                                {
                                    #region generate
                                    object paramSourceDocPath = Path.GetTempFileName();
                                    object paramMissing       = System.Type.Missing;

                                    System.IO.File.WriteAllBytes((string)paramSourceDocPath, msXml.ToArray());
                                    if (!System.IO.File.Exists((string)paramSourceDocPath))
                                    {
                                        throw new Exception(string.Format("Исходный файл для генерации отчета не найден '{0}'", paramSourceDocPath));
                                    }

                                    var wordApplication     = null as Microsoft.Office.Interop.Word.Application;
                                    var wordDocument        = null as Document;
                                    var paramExportFilePath = GetTempFilePathWithExtension(".pdf");
                                    try
                                    {
                                        wordApplication = new Microsoft.Office.Interop.Word.Application()
                                        {
                                            DisplayAlerts = WdAlertLevel.wdAlertsNone
                                        };

                                        var paramExportFormat       = WdExportFormat.wdExportFormatPDF;
                                        var paramOpenAfterExport    = false;
                                        var paramExportOptimizeFor  = WdExportOptimizeFor.wdExportOptimizeForPrint;
                                        var paramExportRange        = WdExportRange.wdExportAllDocument;
                                        var paramStartPage          = 0;
                                        var paramEndPage            = 0;
                                        var paramExportItem         = WdExportItem.wdExportDocumentContent;
                                        var paramIncludeDocProps    = true;
                                        var paramKeepIRM            = true;
                                        var paramCreateBookmarks    = WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                                        var paramDocStructureTags   = true;
                                        var paramBitmapMissingFonts = true;
                                        var paramUseISO19005_1      = false;

                                        // Open the source document.
                                        wordDocument = wordApplication.Documents.Open(
                                            ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing);

                                        // Export it in the specified format.
                                        if (wordDocument != null)
                                        {
                                            wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                                             paramExportFormat, paramOpenAfterExport,
                                                                             paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                                             paramEndPage, paramExportItem, paramIncludeDocProps,
                                                                             paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                                             paramBitmapMissingFonts, paramUseISO19005_1,
                                                                             ref paramMissing);
                                        }

                                        if (!System.IO.File.Exists(paramExportFilePath))
                                        {
                                            throw new Exception(string.Format("Word-PDF: Файл отчета не найден '{0}'", paramExportFilePath));
                                        }

                                        if (Enum.IsDefined(typeof(MimeType), ИсходныйФорматОтчета))
                                        {
                                            file.MimeType = (MimeType)Enum.Parse(typeof(MimeType), ИсходныйФорматОтчета);
                                        }

                                        file.Stream = System.IO.File.ReadAllBytes(paramExportFilePath);
                                    }
                                    finally
                                    {
                                        // Close and release the Document object.
                                        if (wordDocument != null)
                                        {
                                            wordDocument.Close(false, ref paramMissing, ref paramMissing);
                                            wordDocument = null;
                                        }

                                        // Quit Word and release the ApplicationClass object.
                                        if (wordApplication != null)
                                        {
                                            wordApplication.Quit(false, ref paramMissing, ref paramMissing);
                                            wordApplication = null;

                                            GC.Collect();
                                            GC.WaitForPendingFinalizers();
                                            GC.Collect();
                                        }

                                        if (System.IO.File.Exists((string)paramSourceDocPath))
                                        {
                                            System.IO.File.Delete((string)paramSourceDocPath);
                                        }
                                        if (System.IO.File.Exists(paramExportFilePath))
                                        {
                                            System.IO.File.Delete(paramExportFilePath);
                                        }

                                        //var sb = new StringBuilder();
                                        //sb.AppendLine((string)paramSourceDocPath);
                                        //sb.AppendLine(paramExportFilePath);
                                        //ConfigurationClient.WindowsLog(sb.ToString(), "", domain);
                                    }
                                    #endregion
                                }
                                break;

                            case "Excel-PDF":
                                {
                                    #region generate
                                    object paramSourceDocPath = Path.GetTempFileName();
                                    object paramMissing       = System.Type.Missing;

                                    System.IO.File.WriteAllBytes((string)paramSourceDocPath, msXml.ToArray());
                                    if (!System.IO.File.Exists((string)paramSourceDocPath))
                                    {
                                        throw new Exception(string.Format("Исходный файл для генерации отчета не найден '{0}'", paramSourceDocPath));
                                    }

                                    var excelApplication = new Microsoft.Office.Interop.Excel.Application()
                                    {
                                        DisplayAlerts = false
                                    };
                                    var excelDocument = null as Workbook;

                                    var paramExportFilePath   = GetTempFilePathWithExtension(".pdf");
                                    var paramExportFormat     = XlFixedFormatType.xlTypePDF;
                                    var paramExportQuality    = XlFixedFormatQuality.xlQualityStandard;
                                    var paramOpenAfterPublish = false;
                                    var paramIncludeDocProps  = true;
                                    var paramIgnorePrintAreas = true;
                                    var paramFromPage         = System.Type.Missing;
                                    var paramToPage           = System.Type.Missing;

                                    try
                                    {
                                        // Open the source document.
                                        excelDocument = excelApplication.Workbooks.Open(
                                            (string)paramSourceDocPath, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing);

                                        // Export it in the specified format.
                                        if (excelDocument != null)
                                        {
                                            excelDocument.ExportAsFixedFormat(paramExportFormat,
                                                                              paramExportFilePath, paramExportQuality,
                                                                              paramIncludeDocProps, paramIgnorePrintAreas, paramFromPage,
                                                                              paramToPage, paramOpenAfterPublish,
                                                                              paramMissing);
                                        }

                                        if (!System.IO.File.Exists(paramExportFilePath))
                                        {
                                            throw new Exception(string.Format("Файл отчета не найден '{0}'", paramExportFilePath));
                                        }

                                        if (Enum.IsDefined(typeof(MimeType), ИсходныйФорматОтчета))
                                        {
                                            file.MimeType = (MimeType)Enum.Parse(typeof(MimeType), ИсходныйФорматОтчета);
                                        }

                                        file.Stream = System.IO.File.ReadAllBytes(paramExportFilePath);
                                    }
                                    finally
                                    {
                                        // Close and release the Document object.
                                        if (excelDocument != null)
                                        {
                                            excelDocument.Close(false, paramMissing, paramMissing);
                                            excelDocument = null;
                                        }

                                        // Quit Word and release the ApplicationClass object.
                                        if (excelApplication != null)
                                        {
                                            excelApplication.Quit();
                                            excelApplication = null;
                                        }

                                        if (System.IO.File.Exists((string)paramSourceDocPath))
                                        {
                                            System.IO.File.Delete((string)paramSourceDocPath);
                                        }
                                        if (System.IO.File.Exists(paramExportFilePath))
                                        {
                                            System.IO.File.Delete(paramExportFilePath);
                                        }

                                        GC.Collect();
                                        GC.WaitForPendingFinalizers();
                                        GC.Collect();
                                        GC.WaitForPendingFinalizers();
                                    }
                                    #endregion
                                }
                                break;

                            default:
                                {
                                    if (Enum.IsDefined(typeof(MimeType), ИсходныйФорматОтчета))
                                    {
                                        file.MimeType = (MimeType)Enum.Parse(typeof(MimeType), ИсходныйФорматОтчета);
                                    }

                                    file.Stream = msXml.ToArray();
                                }
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ConfigurationClient.WindowsLog(ex.ToString(), user, domain, "ВыводОтчета");
                    }
                });
                task.Start();
                task.Wait();
            }
            catch (Exception ex)
            {
                ConfigurationClient.WindowsLog(ex.ToString(), user, domain, "ВыводОтчета");
            }
            return(file);
        }
        public void TestRenderingTypographySamples()
        {
#if true
            string path = "SampleXpsDocuments_1_0/MXDW";
            string dir  = (path);
            if (dir == null)
            {
                Assert.Inconclusive("Path not found: " + path + ". Follow instructions in ../../../SampleXpsDocuments_1_0/!readme.txt to download samples from the Internet.");
                return;
            }
            if (!Directory.Exists(dir))
            {
                Assert.Inconclusive("Path not found: " + path + ". Follow instructions in ../../../SampleXpsDocuments_1_0/!readme.txt to download samples from the Internet.");
                return;
            }

            string[] files = Directory.GetFiles(dir, "*Poster.xps", SearchOption.TopDirectoryOnly);

            if (files.Length == 0)
            {
                Assert.Inconclusive("No sample file found.");
                return;
            }

            foreach (string filename in files)
            {
                //if (!filename.EndsWith("CalibriPoster.xps"))
                //  continue;

                Debug.WriteLine(filename);
                try
                {
                    XpsDocument xpsDoc = XpsDocument.Open(filename);

                    int docIndex = 0;
                    foreach (FixedDocument doc in xpsDoc.Documents)
                    {
                        PdfDocument pdfDocument = new PdfDocument();
                        //PdfRenderer renderer = new PdfRenderer();
                        XpsConverter converter = new XpsConverter(pdfDocument, xpsDoc);

                        int pageIndex = 0;
                        foreach (FixedPage page in doc.Pages)
                        {
                            Debug.WriteLine(String.Format("  doc={0}, page={1}", docIndex, pageIndex));

                            // HACK: API is senseless
                            PdfPage pdfPage = converter.CreatePage(pageIndex);
                            converter.RenderPage(pdfPage, pageIndex);
                            pageIndex++;
                        }

                        string pdfFilename = IOPath.GetFileNameWithoutExtension(filename);
                        if (docIndex != 0)
                        {
                            pdfFilename += docIndex.ToString();
                        }
                        pdfFilename += ".pdf";
                        pdfFilename  = IOPath.Combine(IOPath.GetDirectoryName(filename), pdfFilename);

                        pdfDocument.Save(pdfFilename);
                        docIndex++;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    GetType();
                }
            }
#else
            //string data = "2.11592697149066,169.466971230985 7.31945717924454E-09,161.067961604689";
            //TokenizerHelper helper = new TokenizerHelper(data);
            //string t = helper.NextTokenRequired();
            //t = helper.NextTokenRequired();
            //t = helper.NextTokenRequired();
            //t = helper.NextTokenRequired();

            string[] files = Directory.GetFiles("../../../../../testing/PdfSharp.Xps.UnitTests/Typography", "*.xps", SearchOption.AllDirectories);

            //files = Directory.GetFiles(@"G:\!StLa\PDFsharp-1.10\OpenSource\PDFsharp\WPF\SampleXpsDocuments_1_0\FontPoster", "*.xps", SearchOption.AllDirectories);

            if (files.Length == 0)
            {
                throw new Exception("No sample file found.");
            }

            foreach (string filename in files)
            {
                // No negative tests here
                if (filename.Contains("\\ConformanceViolations\\"))
                {
                    continue;
                }

                //if (!filename.EndsWith("CalibriPoster.xps"))
                //  continue;

                Debug.WriteLine(filename);
                try
                {
#if true
                    XpsDocument xpsDoc = XpsDocument.Open(filename);

                    int docIndex = 0;
                    foreach (FixedDocument doc in xpsDoc.Documents)
                    {
                        PdfDocument pdfDocument = new PdfDocument();
                        //PdfRenderer renderer = new PdfRenderer();
                        XpsConverter converter = new XpsConverter(pdfDocument, xpsDoc);

                        int pageIndex = 0;
                        foreach (FixedPage page in doc.Pages)
                        {
                            Debug.WriteLine(String.Format("  doc={0}, page={1}", docIndex, pageIndex));

                            // HACK: API is senseless
                            PdfPage pdfPage = converter.CreatePage(pageIndex);
                            converter.RenderPage(pdfPage, pageIndex);
                            pageIndex++;
                        }

                        string pdfFilename = IOPath.GetFileNameWithoutExtension(filename);
                        if (docIndex != 0)
                        {
                            pdfFilename += docIndex.ToString();
                        }
                        pdfFilename += ".pdf";
                        pdfFilename  = IOPath.Combine(IOPath.GetDirectoryName(filename), pdfFilename);

                        pdfDocument.Save(pdfFilename);
                        docIndex++;
                    }
#else
                    int         docIndex = 0;
                    XpsDocument xpsDoc   = XpsDocument.Open(filename);
                    foreach (FixedDocument doc in xpsDoc.Documents)
                    {
                        PdfDocument pdfDoc   = new PdfDocument();
                        PdfRenderer renderer = new PdfRenderer();

                        int pageIndex = 0;
                        foreach (FixedPage page in doc.Pages)
                        {
                            Debug.WriteLine(String.Format("  doc={0}, page={1}", docIndex, pageIndex));
                            PdfPage pdfPage = renderer.CreatePage(pdfDoc, page);
                            renderer.RenderPage(pdfPage, page);
                            pageIndex++;
                        }

                        string pdfFilename = IOPath.GetFileNameWithoutExtension(filename);
                        if (docIndex != 0)
                        {
                            pdfFilename += docIndex.ToString();
                        }
                        pdfFilename += ".pdf";
                        pdfFilename  = IOPath.Combine(IOPath.GetDirectoryName(filename), pdfFilename);

                        pdfDoc.Save(pdfFilename);
                        docIndex++;
                    }
#endif
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    GetType();
                }
            }
#endif
        }
Example #56
0
        private void Load()
        {
            XpsDocument doc = new XpsDocument("Documents/TabRazrab.xps", System.IO.FileAccess.Read);

            documentViewer.Document = doc.GetFixedDocumentSequence();
        }
Example #57
0
        private void SaveDocument(string fileName, FixedDocument document)
        {
            //Delete any existing file.
            File.Delete(fileName);

            //Create a new XpsDocument at the given location.
            XpsDocument xpsDocument =
                new XpsDocument(fileName, FileAccess.ReadWrite);

            //Create a new XpsDocumentWriter for the XpsDocument object.
            xdw = XpsDocument.CreateXpsDocumentWriter(xpsDocument);

            //We want to be notified of when the progress changes.
            xdw.WritingProgressChanged +=
                delegate(object sender, WritingProgressChangedEventArgs e)
            {       //Update the value of the progress bar.
                pbSaveProgress.Value = e.Number;
            };

            //We want to be notified of when the operation is complete.
            xdw.WritingCompleted +=
                delegate(object sender, WritingCompletedEventArgs e)
            {
                //We're finished with the XPS document so close it.
                //This step is important.
                xpsDocument.Close();

                string msg = "Saving complete.";

                if (e.Error != null)
                {
                    msg =
                        string.Format("An error occurred whilst " +
                                      "saving the document.\n\n{0}",
                                      e.Error.Message);
                }
                else if (e.Cancelled)
                {
                    //Delete the incomplete file.
                    File.Delete(fileName);

                    msg =
                        string.Format("Saving cancelled by user.");
                }

                //Inform the user of the print operation's exit status.
                MessageBox.Show(msg,
                                "Recipe_07_11",
                                MessageBoxButton.OK,
                                MessageBoxImage.Information);

                spProgressMask.Visibility = Visibility.Collapsed;
            };

            //Show the long operation mask with the cancel button and progress bar.
            spProgressMask.Visibility = Visibility.Visible;
            pbSaveProgress.Maximum    = document.Pages.Count;
            pbSaveProgress.Value      = 0;

            //Write the document to the Xps file asynchronously.
            xdw.WriteAsync(document);
        }
Example #58
0
        //[TestMethod]
        public void TestRenderingAllSamples()
        {
            string dir   = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); // Directory.GetCurrentDirectory();
            int    slash = dir.LastIndexOf("\\");

            while ((slash = dir.LastIndexOf("\\")) != -1)
            {
                if (dir.EndsWith("PdfSharp"))
                {
                    break;
                }
                dir = dir.Substring(0, slash);
            }
            dir += "/testing/SampleXpsDocuments_1_0";
#if true
            string[] files = Directory.GetFiles(dir, "*.xps", SearchOption.AllDirectories);
#else
            string[] files = Directory.GetFiles("../../../XPS-TestDocuments", "*.xps", SearchOption.AllDirectories);
#endif
            //files = Directory.GetFiles(@"G:\!StLa\PDFsharp-1.20\SourceCode\PdfSharp\testing\SampleXpsDocuments_1_0\MXDW", "*.xps", SearchOption.AllDirectories);
            //files = Directory.GetFiles(@"G:\!StLa\PDFsharp-1.20\SourceCode\PdfSharp\testing\SampleXpsDocuments_1_0\Handcrafted", "*.xps", SearchOption.AllDirectories);
            //files = Directory.GetFiles(@"G:\!StLa\PDFsharp-1.20\SourceCode\PdfSharp\testing\SampleXpsDocuments_1_0\Showcase", "*.xps", SearchOption.AllDirectories);
            files = Directory.GetFiles(@"G:\!StLa\PDFsharp-1.20\SourceCode\PdfSharp\testing\SampleXpsDocuments_1_0\QualityLogicMinBar", "*.xps", SearchOption.AllDirectories);


            if (files.Length == 0)
            {
                throw new Exception("No sample file found. Copy sample files to the \"SampleXpsDocuments_1_0\" folder!");
            }

            foreach (string filename in files)
            {
                // No negative tests here
                if (filename.Contains("\\ConformanceViolations\\"))
                {
                    continue;
                }

                //if (filename.Contains("\\Showcase\\"))
                //  continue;

                //if (!filename.Contains("Vista"))
                //  continue;

                Debug.WriteLine(filename);
                try
                {
                    int         docIndex = 0;
                    XpsDocument xpsDoc   = XpsDocument.Open(filename);
                    foreach (FixedDocument doc in xpsDoc.Documents)
                    {
                        try
                        {
                            PdfDocument pdfDoc   = new PdfDocument();
                            PdfRenderer renderer = new PdfRenderer();

                            int pageIndex = 0;
                            foreach (FixedPage page in doc.Pages)
                            {
                                if (page == null)
                                {
                                    continue;
                                }
                                Debug.WriteLine(String.Format("  doc={0}, page={1}", docIndex, pageIndex));
                                PdfPage pdfPage = renderer.CreatePage(pdfDoc, page);
                                renderer.RenderPage(pdfPage, page);
                                pageIndex++;

                                // stop at page...
                                if (pageIndex == 50)
                                {
                                    break;
                                }
                            }

                            string pdfFilename = IOPath.GetFileNameWithoutExtension(filename);
                            if (docIndex != 0)
                            {
                                pdfFilename += docIndex.ToString();
                            }
                            pdfFilename += ".pdf";
                            pdfFilename  = IOPath.Combine(IOPath.GetDirectoryName(filename), pdfFilename);

                            pdfDoc.Save(pdfFilename);
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("Exception: " + ex.Message);
                        }
                        docIndex++;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    GetType();
                }
            }
        }
Example #59
-1
        private bool ConvertWordDocToXPSDoc(string wordDocName)
        {
            // Create a WordApplication and add Document to it
            Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
            wordApplication.Documents.Add(wordDocName);
            Document doc = wordApplication.ActiveDocument;
            // You must make sure you have Microsoft.Office.Interop.Word.Dll version 12.
            // Version 11 or previous versions do not have WdSaveFormat.wdFormatXPS option
            try
            {
                string xpsDocName = @"http://www.jjgjt.com/download/1.xps";
                doc.SaveAs(xpsDocName, WdSaveFormat.wdFormatXPS);
                wordApplication.Quit();
                //XpsDocument xpsDoc = new XpsDocument(xpsDocName, System.IO.FileAccess.Read);
                XpsDocument xpsDoc = new XpsDocument(xpsDocName, System.IO.FileAccess.Read);

                documentViewer1.Document = xpsDoc.GetFixedDocumentSequence();
                return true;
            }
            catch (Exception exp)
            {
                string str = exp.Message;
                return false;
            }
        }
Example #60
-1
        public static void PrintPreview(Window owner, FormData data)
        {
            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);

                    PackageStore.AddPackage(packageUri, package);

                    XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Maximum, packageUriString);
                    XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
                    Form visual = new Form(data);

                    PrintTicket printTicket = new PrintTicket();
                    printTicket.PageMediaSize = A4PaperSize;
                    writer.Write(visual, printTicket);
                    FixedDocumentSequence document = xpsDocument.GetFixedDocumentSequence();
                    xpsDocument.Close();

                    PrintPreviewWindow printPreviewWnd = new PrintPreviewWindow(document);
                    printPreviewWnd.Owner = owner;
                    printPreviewWnd.ShowDialog();
                    PackageStore.RemovePackage(packageUri);
                }
            }
        }