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());
        }
Exemple #2
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();
        }
Exemple #3
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);
            }


        }
 public static void Create(IDocumentPaginatorSource paginator)
 {
     using (var container = Package.Open(@"C:\temp\" + GetFileName(), FileMode.Create))
     {
         using (var xpsDoc = new XpsDocument(container, CompressionOption.Maximum))
         {
             var xpsSM = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
             xpsSM.SaveAsXaml(paginator);
         }
     }
 }
Exemple #5
0
        public static int SaveAsXps(IDocumentPaginatorSource docref)
        {
            object doc;

            doc = docref;

            //FileInfo fileInfo = new FileInfo(fileName);

            //using (FileStream file = fileInfo.OpenRead())
            //{

            //    System.Windows.Markup.ParserContext context = new System.Windows.Markup.ParserContext();

            //    context.BaseUri = new Uri(fileInfo.FullName, UriKind.Absolute);

            //    doc = System.Windows.Markup.XamlReader.Load(file, context);

            //}

            string fileName = @"c:\a.xps";

            if (!(doc is IDocumentPaginatorSource))
            {

                Console.WriteLine("DocumentPaginatorSource expected");

                return -1;

            }

            using (Package container = Package.Open(fileName + ".xps", FileMode.Create))
            {

                using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Maximum))
                {

                    XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);

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

                    // 8 inch x 6 inch, with half inch margin

                    paginator = new DocumentPaginatorWrapper(paginator, new Size(768, 676), new Size(24, 24));

                    rsm.SaveAsXaml(paginator);

                }

            }

            Console.WriteLine("{0} generated.", fileName + ".xps");

            return 0;
        }
Exemple #6
0
 public static void SaveFlowAsXpsInFile(FlowDocument flowDocument)
 {
     using (Package container = Package.Open("journal.xps", FileMode.Create))
     {
         using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Maximum))
         {
             XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
             DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
             paginator = new DocumentPaginatorWrapper(paginator, new Size(768, 676), new Size(48, 48));
             rsm.SaveAsXaml(paginator);
         }
     }
 }
Exemple #7
0
        /// <summary>
        /// Saves a flow document as an XPS file
        /// </summary>
        /// <param name="document">The document to be sabed.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="pageWidth">Width of the page.</param>
        /// <param name="pageHeight">Height of the page.</param>
        public static void SaveAsXps(this FlowDocument document, string fileName, double pageWidth = 816, double pageHeight = 1056)
        {
            if (!fileName.ToLower().EndsWith(".xps"))
                fileName += ".xps";

            using (var container = Package.Open(fileName, FileMode.Create))
            using (var xpsDoc = new XpsDocument(container, CompressionOption.Maximum))
            {
                var rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                var paginator = new DocumentPaginatorEx(document, new Size(pageWidth, pageHeight), new PageRange());
                rsm.SaveAsXaml(paginator);
            }
        }
		public static void SaveAsXps(string path, FlowDocument document)
		{
			using (var package = Package.Open(path, FileMode.Create))
			{
				using (var xpsDoc = new XpsDocument(
					package, CompressionOption.Maximum))
				{
					var xpsSm = new XpsSerializationManager(
						new XpsPackagingPolicy(xpsDoc), false);
					var dp = ((IDocumentPaginatorSource)document).DocumentPaginator;
					xpsSm.SaveAsXaml(dp);
				}
			}
		}
        protected override void SaveCore(IDocument document, string fileName)
        {
            // We have to clone the FlowDocument before we use different pagination settings for the export.
            RichTextDocument richTextDocument = document as RichTextDocument;
            FlowDocument clone = richTextDocument.CloneContent();

            using (Package package = Package.Open(fileName, FileMode.Create))
            using (XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Maximum))
            {
                XpsSerializationManager serializer = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false);
                DocumentPaginator paginator = ((IDocumentPaginatorSource)clone).DocumentPaginator;
                serializer.SaveAsXaml(paginator);
            }
        }
 /// <summary>
 /// Converting the current report's content to a ByteArray.
 /// It's suitable for storing the XPS content of the rpt in a database.
 /// </summary>
 /// <param name="doc">Retrieve it from xps.GetFixedDocumentSequence() or documentViewer.Document</param>
 /// <returns></returns>
 public static byte[] Export(this FixedDocumentSequence doc)
 {
     using (var ms = new MemoryStream())
     {
         using (var package = Package.Open(ms, FileMode.CreateNew))
         {
             using (var xpsd = new XpsDocument(package, CompressionOption.Maximum))
             {
                 var xpsSm = new XpsSerializationManager(new XpsPackagingPolicy(xpsd), false);
                 xpsSm.SaveAsXaml(doc.DocumentPaginator);
                 xpsSm.Commit();
                 return ms.ToArray();
             }
         }
     }
 }
        /// <summary>
        /// Helper method to create page header or footer from flow document template
        /// </summary>
        /// <param name="data">report data</param>
        /// <param name="fileName">file to save XPS to</param>
        /// <returns></returns>
        public XpsDocument CreateXpsDocument(ReportData data, string fileName)
        {
            Package pkg  = Package.Open(fileName, FileMode.Create, FileAccess.ReadWrite);
            string  pack = "pack://report.xps";

            PackageStore.RemovePackage(new Uri(pack));
            PackageStore.AddPackage(new Uri(pack), pkg);
            XpsDocument             doc = new XpsDocument(pkg, _xpsCompressionOption, pack);
            XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);

            ReportPaginator rp = new ReportPaginator(this, data);

            rsm.SaveAsXaml(rp);
            rsm.Commit();
            pkg.Close();
            return(new XpsDocument(fileName, FileAccess.Read));
        }
Exemple #12
0
 public static XpsDocument CreateXpsDocumentFromString(string xamlFlowDoc)
 {
     object doc;
     doc = XamlReader.Parse(xamlFlowDoc);
     MemoryStream ms = new MemoryStream();
     Package pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
     string pack = "pack://report.xps";
     PackageStore.RemovePackage(new Uri(pack));
     PackageStore.AddPackage(new Uri(pack), pkg);
     XpsDocument xpsDoc = new XpsDocument(pkg, CompressionOption.NotCompressed, pack);
     XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
     DocumentPaginator paginator = ((IDocumentPaginatorSource)doc).DocumentPaginator;
     //paginator = new PimpedPaginator(paginator,);
     paginator = new DocumentPaginatorWrapper(paginator, new Size(768, 676), new Size(48, 48));
     rsm.SaveAsXaml(paginator);
     return xpsDoc;
 }
Exemple #13
0
        public void SaveAsXps(string fileName, FlowDocument document)
        {
            using (System.IO.Packaging.Package container = System.IO.Packaging.Package.Open(fileName, FileMode.Create))
            {
                using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Maximum))
                {
                    XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);

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

                    //16.5=6.4960=623.616
                    //11=4.3307=415.74
                    paginator = new DocumentPaginatorWrapper(paginator, new Size(416, 624), new Size(15, 15));

                    rsm.SaveAsXaml(paginator);
                }
            }
        }
Exemple #14
0
        public static void SaveAsXps2(string xamlFlowDoc, string xpsDocumentName)
        {
            object doc;
            doc = XamlReader.Parse(xamlFlowDoc);

            using (Package container = Package.Open(xpsDocumentName, FileMode.Create))
            {
                using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.NotCompressed))
                {
                    XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                    //var paginator = new PimpedPaginator((FlowDocument)doc, new PimpedPaginator.Definition());
                    DocumentPaginator paginator = ((IDocumentPaginatorSource)doc).DocumentPaginator;
                    paginator = new ReportPaginator(paginator);
                    //paginator = new DocumentPaginatorWrapper(paginator, new Size(768, 676), new Size(48, 48));
                    rsm.SaveAsXaml(paginator);
                }
            }
        }
        public static MemoryStream FlowDocumentToXPS(FlowDocument flowDocument, int width, int height)
        {
            MemoryStream stream = new MemoryStream();

            using (Package package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite))
            {
                using (XpsDocument xpsDoc = new XpsDocument(package, CompressionOption.Maximum))
                {
                    XpsSerializationManager rsm       = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                    DocumentPaginator       paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
                    paginator.PageSize = new System.Windows.Size(width, height);
                    rsm.SaveAsXaml(paginator);
                    rsm.Commit();
                }
            }
            stream.Position = 0;
            return(stream);
        }
 private void SaveDocument([NotNull] IDocumentPaginatorSource document)
 {
     using (var package = Package.Open(_output, FileMode.Create, FileAccess.ReadWrite))
         using (var xps = new XpsDocument(package, CompressionOption.Maximum))
             using (var policy = new XpsPackagingPolicy(xps))
                 using (var serializer = new XpsSerializationManager(policy, false)) {
                     //document.DocumentPaginator.PageSize = new System.Windows.Size(100, 100);
                     serializer.SaveAsXaml(document.DocumentPaginator);
                     serializer.Commit();
                 }
     if (_leaveOpen)
     {
         _output.Flush();
     }
     else
     {
         _output.Dispose();
     }
 }
Exemple #17
0
        /// <summary> Saves the created xps document to a file. </summary>
        /// <param name="filename"> The name of the file to save the XPS document as. </param>
        public void SaveToFile(string filename)
        {
            var fixedDocument = new FixedDocument();

            foreach (var page in CreatePages())
            {
                fixedDocument.Pages.Add(page);
            }

            using (var memoryStream = new MemoryStream())
                using (Package container = Package.Open(filename, FileMode.Create))
                {
                    using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Maximum))
                    {
                        XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                        rsm.SaveAsXaml(fixedDocument);
                    }
                    memoryStream.Position = 0;
                }
        }
Exemple #18
0
        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            using (var stream = new MemoryStream())
            {
                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)DocViewer.Document).DocumentPaginator;
                        rsm.SaveAsXaml(paginator);
                        rsm.Commit();
                    }
                }
                stream.Position = 0;

                var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(stream);
                PdfSharp.Xps.XpsConverter.Convert(pdfXpsDoc, "doc.pdf", 0);
            }
        }
Exemple #19
0
        private void LoadedHandler(object sender, RoutedEventArgs e)
        {
            // We have to clone the FlowDocument before we use different pagination settings for the export.
            FlowDocument clone = ViewModel.Document.CloneContent();

            clone.ColumnWidth = double.PositiveInfinity;

            var packageStream = new MemoryStream();

            package = Package.Open(packageStream, FileMode.Create, FileAccess.ReadWrite);
            PackageStore.AddPackage(new Uri(PackagePath), package);
            xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, PackagePath);
            using (var serializer = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false))
            {
                DocumentPaginator paginator = ((IDocumentPaginatorSource)clone).DocumentPaginator;
                serializer.SaveAsXaml(paginator);
            }
            documentViewer.Document = xpsDocument.GetFixedDocumentSequence();
            documentViewer.Focus();
        }
        public void Convert(System.Windows.Documents.FlowDocument document, Stream documentStream)
        {
            using (var xpsDocumentStream = new MemoryStream())
            {
                using (var package = Package.Open(xpsDocumentStream, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (var xpsDocument = new XpsDocument(package, CompressionOption.Maximum))
                    {
                        var serializer = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false);
                        var paginator  = ((IDocumentPaginatorSource)document).DocumentPaginator;
                        serializer.SaveAsXaml(paginator);
                        serializer.Commit();
                    }
                }

                xpsDocumentStream.Position = 0;

                XpsConverter.Convert(xpsDocumentStream, documentStream);
            }
        }
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if(!(values.Length > 1 && values[0] is FlowDocument))
            {
                throw new InvalidOperationException("Seule les valeurs de type FlowDocument peuvent êtres converties (FlowDocumentToXpsConverter). Cette erreur est critique.");
            }

            if(!(values.Length > 1 && values[1] is SumUpViewModel) && !(values[1] == null))
            {
                throw new InvalidOperationException("Une valeur (position 2) de type SumUpViewModel doit être fournie (FlowDocumentToXpsConverter. Cette erreur est critique");
            }

            if (values[1] != null)
            {
                FlowDocument flowDoc = ((FlowDocument)values[0]);
                flowDoc.DataContext = values[1];
                string xpsDir = ConfigurationManager.AppSettings["XpsOutDir"];
                if (!Directory.Exists(xpsDir))
                {
                    Directory.CreateDirectory(xpsDir);
                }

                using (FileStream fs = File.Open($"{xpsDir}flowDocument.xps", FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
                {
                    using (Package package = Package.Open(fs, FileMode.Create, FileAccess.ReadWrite))
                    {
                        XpsDocument xpsDoc = new XpsDocument(package, CompressionOption.Maximum);
                        XpsSerializationManager xpsSerializationManager = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                        DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDoc).DocumentPaginator;
                        xpsSerializationManager.SaveAsXaml(paginator);
                        xpsSerializationManager.Commit();

                        return xpsDoc;
                    }
                }
            }
            else
            {
                return null;
            }
        }
Exemple #22
0
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(values.Length > 1 && values[0] is FlowDocument))
            {
                throw new InvalidOperationException("Seule les valeurs de type FlowDocument peuvent êtres converties (FlowDocumentToXpsConverter). Cette erreur est critique.");
            }

            if (!(values.Length > 1 && values[1] is SumUpViewModel) && !(values[1] == null))
            {
                throw new InvalidOperationException("Une valeur (position 2) de type SumUpViewModel doit être fournie (FlowDocumentToXpsConverter. Cette erreur est critique");
            }

            if (values[1] != null)
            {
                FlowDocument flowDoc = ((FlowDocument)values[0]);
                flowDoc.DataContext = values[1];
                string xpsDir = ConfigurationManager.AppSettings["XpsOutDir"];
                if (!Directory.Exists(xpsDir))
                {
                    Directory.CreateDirectory(xpsDir);
                }

                using (FileStream fs = File.Open($"{xpsDir}flowDocument.xps", FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
                {
                    using (Package package = Package.Open(fs, FileMode.Create, FileAccess.ReadWrite))
                    {
                        XpsDocument             xpsDoc = new XpsDocument(package, CompressionOption.Maximum);
                        XpsSerializationManager xpsSerializationManager = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                        DocumentPaginator       paginator = ((IDocumentPaginatorSource)flowDoc).DocumentPaginator;
                        xpsSerializationManager.SaveAsXaml(paginator);
                        xpsSerializationManager.Commit();

                        return(xpsDoc);
                    }
                }
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Helper method to create page header or footer from flow document template
        /// </summary>
        /// <param name="data">report data</param>
        /// <returns></returns>
        public XpsDocument CreateXpsDocument(ReportData data, Action <int, int> PageGeneratedCallBack = null)
        {
            MemoryStream ms   = new MemoryStream();
            Package      pkg  = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
            string       pack = String.Format("pack://report{0}.xps", this.ReportName);

            PackageStore.RemovePackage(new Uri(pack));
            PackageStore.AddPackage(new Uri(pack), pkg);
            XpsDocument             doc = new XpsDocument(pkg, CompressionOption.NotCompressed, pack);
            XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
            //DocumentPaginator paginator = ((IDocumentPaginatorSource)CreateFlowDocument()).DocumentPaginator;

            ReportPaginator rp = new ReportPaginator(this, data, PageGeneratedCallBack);

            rsm.SaveAsXaml(rp);

            rsm.Commit();
            //pkg.Close();

            return(doc);
        }
Exemple #24
0
        public static int SaveAsXps(FlowDocument doc, string fileName, Size printableArea)
        {
            doc.ColumnWidth = printableArea.Width;
            using (Package container = Package.Open(fileName, FileMode.Create))
            {
                using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Maximum))
                {
                    XpsSerializationManager rsm       = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                    DocumentPaginator       paginator = ((IDocumentPaginatorSource)doc).DocumentPaginator;
                    paginator.ComputePageCount();

                    DocumentPaginator newPaginator = new DocumentPaginatorWrapper(
                        paginator,
                        printableArea, new Size(8, 8));

                    rsm.SaveAsXaml(paginator);
                }
            }

            return(0);
        }
Exemple #25
0
 private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
 {
     using (var stream = new MemoryStream())
     {
         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)DocViewer.Document).DocumentPaginator;
                 rsm.SaveAsXaml(paginator);
                 rsm.Commit();
             }
         }
         stream.Position = 0;
     
         var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(stream);
         PdfSharp.Xps.XpsConverter.Convert(pdfXpsDoc, "doc.pdf", 0);
     }
     
 }
Exemple #26
0
        public static void GenPDFFromFlowDocument(FlowDocument flowDocument, string inFileName = null)
        {
            string fileName = inFileName == null?DateTime.Now.Ticks.ToString() + ".pdf" : inFileName;

            using (var stream = new MemoryStream())
            {
                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)flowDocument).DocumentPaginator;
                        rsm.SaveAsXaml(paginator);
                        rsm.Commit();
                    }
                }
                stream.Position = 0;

                var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(stream);
                PdfSharp.Xps.XpsConverter.Convert(pdfXpsDoc, fileName, 0);
            }
        }
        public static FlowDocument CreateFlowDocument(Visual visual, Size pageSize)
        {
            FrameworkElement fe = (visual as FrameworkElement);

            fe.Measure(new Size(Int32.MaxValue, Int32.MaxValue));
            Size visualSize = fe.DesiredSize;

            //Size visualSize = new Size(fe.ActualWidth, fe.ActualHeight);
            fe.Arrange(new Rect(new Point(0, 0), visualSize));
            MemoryStream      stream = new MemoryStream();
            string            pack   = "pack://temp.xps";
            Uri               uri    = new Uri(pack);
            DocumentPaginator paginator;
            XpsDocument       xpsDoc;

            using (Package container = Package.Open(stream, FileMode.Create)){
                PackageStore.AddPackage(uri, container);
                using (xpsDoc = new XpsDocument(container, CompressionOption.Fast, pack)){
                    XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                    rsm.SaveAsXaml(visual);
                    paginator          = ((IDocumentPaginatorSource )xpsDoc.GetFixedDocumentSequence()).DocumentPaginator;
                    paginator.PageSize = visualSize; // new Size(1000, 5000);
                }
                PackageStore.RemovePackage(uri);
            }
            using (Package container = Package.Open(stream, FileMode.Create)){
                using (xpsDoc = new XpsDocument(container, CompressionOption.Fast, pack)){
                    paginator = new VisualDocumentPaginator(paginator, new Size(pageSize.Width, pageSize.Height), new Size(48, 48));
                    XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                    rsm.SaveAsXaml(paginator);
                }
                PackageStore.RemovePackage(uri);
            }

            FlowDocument document = Helper.ConvertXPSDocumentToFlowDocument(stream);

            stream.Close();
            return(document);
        }
Exemple #28
0
        void printButton_Click(object sender, RoutedEventArgs e)
        {
            Frame itemToPrint = GetCurrentFrame();

            // do printing here...
            string path = string.Format(@"c:\temp\{0}.xps", itemToPrint.Source.ToString().Replace("/", "."));;

            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (XpsDocument doc = new XpsDocument(path, System.IO.FileAccess.ReadWrite))
            {
                XpsPackagingPolicy      packagePolicy    = new XpsPackagingPolicy(doc);
                XpsSerializationManager serializationMgr = new XpsSerializationManager(packagePolicy, false);

                serializationMgr.SaveAsXaml(itemToPrint); // this can be any UI element
            }

            System.Diagnostics.Process.Start(path);
        }
Exemple #29
0
        private static void CreateXps(FlowDocument tempFlow, string tempFile, PrintSettings settings)
        {
            //flowDocument, out exceptions, CheckGreyMark(mark, blackAndWhite), showNumber, face, blackAndWhite ? Brushes.Black : brush, useLeading, fontSize, from, till, useOldNumbering, blackAndWhite ? Brushes.Transparent : backBrush
            //
            var stream = new MemoryStream();

            using (Package package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite))
            {
                XpsDocument xpsDoc;
                using (xpsDoc = new XpsDocument(package, CompressionOption.Maximum))
                {
                    var rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                    DocumentPaginator paginator = ((IDocumentPaginatorSource)tempFlow).DocumentPaginator;
                    paginator = new DocumentPaginatorWrapper(paginator)
                    {
                        ContentPageSize = new Size(paginator.PageSize.Width, paginator.PageSize.Height),
                        ContentMargin   = new Size(48, 48),
                        Mark            = settings.UseWatermark ? CheckGreyMark(settings.Watermark, settings.UseBlackAndWhite):null,
                        FooterTypeface  = new Typeface(settings.PageCountElement.FontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal),
                        ForegroundBrush = settings.UseBlackAndWhite ? Brushes.Black : settings.PageCountElement.ForgroundBrush,
                        ShowNumbering   = settings.ShowPageNumber,
                        UseLeadingZero  = settings.PageCountElement.UseLeadingZero,
                        FooterFontSize  = settings.PageCountElement.FontSize,
                        FirstPritedPage = settings.From,
                        LastPrintedPage = settings.Till,
                        UseOldNumbering = settings.UseOldNumbering,
                        BackgroundBrush = settings.UseBlackAndWhite ? Brushes.White : settings.BackgroundBrush
                    };
                    ((DocumentPaginatorWrapper)paginator).ComputeValues();
                    rsm.SaveAsXaml(paginator);
                    rsm.Commit();
                }
            }
            stream.Position = 0;
            using (var fileStream = new FileStream(tempFile, FileMode.CreateNew, FileAccess.ReadWrite))
            {
                stream.CopyTo(fileStream);
            }
        }
Exemple #30
0
        //int minimalOffset = 0;

        /// <summary>
        /// Helper method to create page header o footer from flow document template
        /// </summary>
        /// <param name="fd"></param>
        /// <param name="pageDef"></param>
        /// <returns></returns>
        public static XpsDocument CreateXpsDocument(FlowDocument fd, PageDefinition pageDef)
        {
            MemoryStream ms  = new MemoryStream();
            Package      pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);

            string pack = "pack://" + fd.Name + System.Guid.NewGuid().ToString() + ".xps";

            PackageStore.AddPackage(new Uri(pack), pkg);
            XpsDocument doc = new XpsDocument(pkg, CompressionOption.SuperFast, pack);

            XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);

            DocumentPaginator paginator = ((IDocumentPaginatorSource)fd).DocumentPaginator;
            // Size size = new Size(800, 1024);
            // ReportPaginator rp = new ReportPaginator(paginator, PrintHelper.GetPageSize(), pageDef);
            // ReportPaginator rp = new ReportPaginator(paginator, size, pageDef);
            LabelPaginator rp = new LabelPaginator(paginator, LabelPrintHelper.GetPageSize(), pageDef);

            rsm.SaveAsXaml(rp);

            return(doc);
        }
        public int SaveAsXps(string fileName)

        {
            using (var container = Package.Open(fileName + ".xps",
                                                FileMode.Create))

                using (var xpsDoc = new XpsDocument(container, CompressionOption.Maximum))

                {
                    var rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);

                    var documentClone = CloneXamlControl(IndividualCard);

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

                    // 8 inch x 6 inch, with half inch margin

                    paginator = new DocumentPaginatorWrapper(paginator, new Size(768, 676), new Size(48, 48));

                    rsm.SaveAsXaml(paginator);
                }
            return(0);
        }
Exemple #32
0
        public void FlowDocumentToXps(DocumentPaginator paginator, string filename, string reportName, bool overWrite)
        {
            XpsDocument document;

            if (overWrite)
            {
                document = new XpsDocument(filename, FileAccess.Write);
            }
            else
            {
                document = new XpsDocument(filename, FileAccess.ReadWrite);
            }

            XpsPackagingPolicy packagePolicy = new XpsPackagingPolicy(document);

            XpsSerializationManager serializationMgr = new XpsSerializationManager(packagePolicy, true);

            serializationMgr.Commit();

            serializationMgr.SaveAsXaml(paginator);


            document.Close();
        }
Exemple #33
0
        /// <summary>
        /// Helper method to create page header or footer from flow document template
        /// </summary>
        /// <param name="data">enumerable report data</param>
        /// <param name="fileName">file to save XPS to</param>
        /// <returns></returns>
        public XpsDocument CreateXpsDocument(IEnumerable <ReportData> data, string fileName)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            int count = 0; ReportData firstData = null;

            foreach (ReportData rd in data)
            {
                if (firstData == null)
                {
                    firstData = rd;
                }
                count++;
            }
            if (count == 1)
            {
                return(CreateXpsDocument(firstData));            // we have only one ReportData object -> use the normal ReportPaginator instead
            }
            Package pkg  = Package.Open(fileName, FileMode.Create, FileAccess.ReadWrite);
            string  pack = "pack://report.xps";

            PackageStore.RemovePackage(new Uri(pack));
            PackageStore.AddPackage(new Uri(pack), pkg);
            XpsDocument             doc       = new XpsDocument(pkg, _xpsCompressionOption, pack);
            XpsSerializationManager rsm       = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
            DocumentPaginator       paginator = ((IDocumentPaginatorSource)CreateFlowDocument()).DocumentPaginator;

            MultipleReportPaginator rp = new MultipleReportPaginator(this, data);

            rsm.SaveAsXaml(rp);
            rsm.Commit();
            pkg.Close();
            return(new XpsDocument(fileName, FileAccess.Read));
        }
Exemple #34
0
		/// <summary>
		/// Helper method to create page header or footer from flow document template
		/// </summary>
		/// <param name="data">enumerable report data</param>
		/// <returns></returns>
		/// <exception cref="ArgumentNullException">data</exception>
		public XpsDocument CreateXpsDocument(IEnumerable<ReportData> data)
		{
			using (var counter = new TimeCounter("CreateXpsDocument Total:		{0}", true, true))
			{
				if (data == null)
					throw new ArgumentNullException("data");
				int count = 0;
				ReportData firstData = null;
				foreach (ReportData rd in data) { if (firstData == null) firstData = rd; count++; }
				if (count == 1)
					return CreateXpsDocument(firstData); // we have only one ReportData object -> use the normal ReportPaginator instead

				MemoryStream ms = new MemoryStream();
				Package pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
				string pack = "pack://report.xps";
				PackageStore.RemovePackage(new Uri(pack));
				PackageStore.AddPackage(new Uri(pack), pkg);
				XpsDocument doc = new XpsDocument(pkg, CompressionOption.NotCompressed, pack);
				XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
				//DocumentPaginator paginator = ((IDocumentPaginatorSource)CreateFlowDocument()).DocumentPaginator;
				counter.ShowTick("CreateXpsDocument Prepare:	{0}");

				MultipleReportPaginator rp = new MultipleReportPaginator(this, data);
				counter.ShowTick("CreateXpsDocument Paginator:	{0}");
				rsm.SaveAsXaml(rp);
				counter.ShowTick("CreateXpsDocument SaveAsXaml:	{0}");
				return doc;
			}
		}
Exemple #35
0
        /// <summary>
        /// Helper method to create page header or footer from flow document template
        /// </summary>
        /// <param name="data">report data</param>
        /// <param name="fileName">file to save XPS to</param>
        /// <returns></returns>
        public XpsDocument CreateXpsDocument(ReportData data, string fileName)
        {
            Package pkg = Package.Open(fileName, FileMode.Create, FileAccess.ReadWrite);
            string pack = "pack://report.xps";
            PackageStore.RemovePackage(new Uri(pack));
            PackageStore.AddPackage(new Uri(pack), pkg);
            XpsDocument doc = new XpsDocument(pkg, _xpsCompressionOption, pack);
            XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
            DocumentPaginator paginator = ((IDocumentPaginatorSource)CreateFlowDocument()).DocumentPaginator;

            ReportPaginator rp = new ReportPaginator(this, data);
            rsm.SaveAsXaml(rp);
            rsm.Commit();
            pkg.Close();
            return new XpsDocument(fileName, FileAccess.Read);
        }
Exemple #36
0
        public static int SaveAsXps(IDocumentPaginatorSource docref)
        {
            object doc;

            doc = docref;

            //FileInfo fileInfo = new FileInfo(fileName);



            //using (FileStream file = fileInfo.OpenRead())
            //{

            //    System.Windows.Markup.ParserContext context = new System.Windows.Markup.ParserContext();

            //    context.BaseUri = new Uri(fileInfo.FullName, UriKind.Absolute);

            //    doc = System.Windows.Markup.XamlReader.Load(file, context);

            //}

            string fileName = @"c:\a.xps";



            if (!(doc is IDocumentPaginatorSource))
            {
                Console.WriteLine("DocumentPaginatorSource expected");

                return(-1);
            }



            using (Package container = Package.Open(fileName + ".xps", FileMode.Create))
            {
                using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Maximum))
                {
                    XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);



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



                    // 8 inch x 6 inch, with half inch margin

                    paginator = new DocumentPaginatorWrapper(paginator, new Size(768, 676), new Size(24, 24));



                    rsm.SaveAsXaml(paginator);
                }
            }



            Console.WriteLine("{0} generated.", fileName + ".xps");



            return(0);
        }
Exemple #37
0
        public override int SaveAsXps(string fileName)
        {
            object doc;

            if (Draft == null)
                return -1;

            FileInfo fileInfo = new FileInfo(fileName);

            List<FlowDocument> Docs = new List<FlowDocument>();
            for (int x = 0; x < Chapters.Count; x++)
                Docs.Add(((Chapter)Chapters[x]).getFlow());

            doc = SavableDocument.CombineDocs(Docs);


            if (!(doc is IDocumentPaginatorSource))
            {
                Console.WriteLine("DocumentPaginatorSource expected");
                return -1;
            }

            File.Delete(fileName);
            using (Package container = Package.Open(fileName, FileMode.Create))
            {
                using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Maximum))
                {
                    XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);

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


                    // 8 inch x 6 inch, with half inch margin
                    paginator = new DocumentPaginatorWrapper(paginator, new Size(595 * 1.33, 842 * 1.3), new Size(48, 48));


                    rsm.SaveAsXaml(paginator);

                }
            }


            return 0;
        }
		/// <summary>
		/// Actually print an Xps Document with previously setup params
		/// </summary>
		/// <param name="paginator">Document to print</param>
		/// <param name="description">Description</param>
		public void PrintDocument(DocumentPaginator paginator, string description)
		{
			if (paginator == null)
				throw new ArgumentNullException("paginator", "No DocumentPaginator to print");

			VerifyPrintSettings();

			//Handle XPS ourself, as their document writer hates our thread
			if (mPrintQueue.FullName.Contains("XPS"))
			{
				SaveFileDialog sfd = new SaveFileDialog();
				sfd.Filter = "Xps Document (*.xps) | *.xps";

				if (sfd.ShowDialog() == true)
				{
					XpsDocument document = new XpsDocument(sfd.FileName, System.IO.FileAccess.Write);
					XpsPackagingPolicy packagePolicy = new XpsPackagingPolicy(document);
					XpsSerializationManager serializationMgr = new XpsSerializationManager(packagePolicy, false);
					serializationMgr.SaveAsXaml(paginator);

					document.Close();
				}

				return;
			}

			XpsDocumentWriter writer = null;
			new PrintingPermission(PrintingPermissionLevel.DefaultPrinting).Assert();

			try
			{
				mPrintQueue.CurrentJobSettings.Description = description;
				writer = PrintQueue.CreateXpsDocumentWriter(mPrintQueue);

				TicketEventHandler handler = new TicketEventHandler(mPrintTicket);
				writer.WritingPrintTicketRequired += new WritingPrintTicketRequiredEventHandler(handler.SetPrintTicket);
			}
			finally
			{
				CodeAccessPermission.RevertAssert();
			}

			writer.Write(paginator);

			//Reset
			mPrintableWidth = 0.0;
			mPrintableHeight = 0.0;
			mWidthUpdated = false;
			mHeightUpdated = false;
		}
Exemple #39
0
		private void Save(string outputPath, IDocumentPaginatorSource paginator)
		{
			using (var container = Package.Open(outputPath, FileMode.Create))
			{
				using (var xpsDoc = new XpsDocument(container, CompressionOption.Maximum))
				{
					var sm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
					sm.SaveAsXaml(paginator);
				}
			}
		}
Exemple #40
0
        public void FlowDocumentToPDF(DocumentPaginator paginator, string filename, string reportName, bool overWrite)
        {
            MemoryStream lMemoryStream = new MemoryStream();
            Package package = Package.Open(lMemoryStream, FileMode.Create);
            XpsDocument doc = new XpsDocument(package);

            XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);

            XpsPackagingPolicy packagePolicy = new XpsPackagingPolicy(doc);
            XpsSerializationManager serializationMgr = new XpsSerializationManager(packagePolicy, false);

            writer.Write(paginator);
            doc.Close();
            package.Close();

            var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(lMemoryStream);
            PdfSharp.Xps.XpsConverter.Convert(pdfXpsDoc, filename, 0);
            pdfXpsDoc.Close();
        }
Exemple #41
0
 internal PackageSerializationManager CreateSerializationManager(bool bBatchMode)
 {
     PackageSerializationManager manager = null;
     XpsPackagingPolicy packagingPolicy = new XpsPackagingPolicy(this);
     if (packagingPolicy != null)
     {
         manager = new XpsSerializationManager(packagingPolicy, bBatchMode);
     }
     return manager;
 }
        public FlowDocument CreateFlowDocument(ReportData data, Action<int, int> PageGeneratedCallBack = null)
        {
            MemoryStream ms = new MemoryStream();
            Package pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
            string pack = String.Format("pack://report{0}.xps", this.ReportName);
            PackageStore.RemovePackage(new Uri(pack));
            PackageStore.AddPackage(new Uri(pack), pkg);
            XpsDocument doc = new XpsDocument(pkg, CompressionOption.NotCompressed, pack);
            XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
            var flowDocument = this.CreateFlowDocument();
            ReportPaginator rp = new ReportPaginator(this, data, PageGeneratedCallBack, flowDocument);

            return flowDocument;
        }
        /// <summary>
        /// Helper method to create page header or footer from flow document template
        /// </summary>
        /// <param name="data">report data</param>
        /// <returns></returns>
        public XpsDocument CreateXpsDocument(ReportData data, Action<int,int> PageGeneratedCallBack = null)
        {
            MemoryStream ms = new MemoryStream();
            Package pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
            string pack = String.Format("pack://report{0}.xps", this.ReportName);
            PackageStore.RemovePackage(new Uri(pack));
            PackageStore.AddPackage(new Uri(pack), pkg);
            XpsDocument doc = new XpsDocument(pkg, CompressionOption.NotCompressed, pack);
            XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
            //DocumentPaginator paginator = ((IDocumentPaginatorSource)CreateFlowDocument()).DocumentPaginator;
            
            ReportPaginator rp = new ReportPaginator(this, data, PageGeneratedCallBack);
            rsm.SaveAsXaml(rp);
            
            rsm.Commit();
            //pkg.Close();

            return doc;
        }
        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();
                    }
                }
            }
        }
Exemple #45
0
        public virtual int SaveAsXps(string fileName)
        {
            object doc;

            if (Draft == null)
                return -1;

            FileInfo fileInfo = new FileInfo(fileName);
            SavableDocument sav = new SavableDocument(Draft);
            doc = sav.CloneDoc();

            //using (FileStream file = fileInfo.OpenRead())
            //{
            //    System.Windows.Markup.ParserContext context = new System.Windows.Markup.ParserContext();
            //    context.BaseUri = new Uri(fileInfo.FullName, UriKind.Absolute);
            //    //doc = System.Windows.Markup.XamlReader.Load(file, context);
                
            //}


            if (!(doc is IDocumentPaginatorSource))
            {
                Console.WriteLine("DocumentPaginatorSource expected");
                return -1;
            }

            File.Delete(fileName);
            using (Package container = Package.Open(fileName, FileMode.Create))
            {
                using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Maximum))
                {
                    XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);

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


                    // 8 inch x 6 inch, with half inch margin
                    paginator = new DocumentPaginatorWrapper(paginator, new Size(595*1.33, 842*1.3), new Size(48, 48));


                    rsm.SaveAsXaml(paginator);
                    
                }
            }


            return 0;
        }
Exemple #46
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;
            }
        }
Exemple #47
0
        public void FlowDocumentToXps(DocumentPaginator paginator, string filename, string reportName, bool overWrite)
        {
            XpsDocument document;
            if (overWrite)
                document = new XpsDocument(filename, FileAccess.Write);
            else
                document = new XpsDocument(filename, FileAccess.ReadWrite);

            XpsPackagingPolicy packagePolicy = new XpsPackagingPolicy(document);

            XpsSerializationManager serializationMgr = new XpsSerializationManager(packagePolicy, true);

            serializationMgr.Commit();

            serializationMgr.SaveAsXaml(paginator);

            document.Close();
        }
Exemple #48
0
 public IDocumentPaginatorSource LoadPrint(System.Collections.Generic.List<FixedPage> pages, Size vsize)
 {
     FixedDocument fd = new FixedDocument();
     fd.DocumentPaginator.PageSize = vsize;
     foreach (var item in pages)
     {
         PageContent pc = new PageContent();
         ((IAddChild)pc).AddChild(item);
         pc.Height = vsize.Height;
         pc.Width = vsize.Width;
         fd.Pages.Add(pc);
     }
     MemoryStream ms = new MemoryStream();
     Package pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
     string pack = "pack://report.xps";
     PackageStore.RemovePackage(new Uri(pack));
     PackageStore.AddPackage(new Uri(pack), pkg);
     XpsDocument doc = new XpsDocument(pkg, CompressionOption.NotCompressed, pack);
     XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
     rsm.SaveAsXaml(fd);
     return doc.GetFixedDocumentSequence() as IDocumentPaginatorSource;
 }
Exemple #49
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);
        }
Exemple #50
0
        public int SaveAsXps(string fileName)
        {
            object doc;


            FileInfo fileInfo = new FileInfo(fileName);


            using (FileStream file = fileInfo.OpenRead())
            {
                System.Windows.Markup.ParserContext context = new System.Windows.Markup.ParserContext();
                context.BaseUri = new Uri(fileInfo.FullName, UriKind.Absolute);
                doc             = System.Windows.Markup.XamlReader.Load(file, context);
            }


            if (!(doc is IDocumentPaginatorSource))
            {
                Console.WriteLine("DocumentPaginatorSource expected");
                return(-1);
            }

            using (Package container = Package.Open(fileName + ".xps", FileMode.Create))
            {
                using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Maximum))
                {
                    xpsDoc.AddFixedDocumentSequence();
                    FixedDocumentSequence seq       = xpsDoc.GetFixedDocumentSequence();
                    DocumentReference     reference = new DocumentReference();
                    //reference.SetDocument(doc);
                    seq.References.Add(reference);
                    FixedDocument abc     = new FixedDocument();
                    PageContent   pagecnt = new PageContent();

                    abc.Pages.Add(pagecnt);
                    XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                    xpsDoc.AddFixedDocumentSequence();
                    FixedDocumentSequence aaa = xpsDoc.GetFixedDocumentSequence();

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


                    // 8 inch x 6 inch, with half inch margin
                    //paginator = new DocumentPaginatorWrapper(paginator, new Size(21*96/2.54, 29.7*96/2.54), new Size(0*96/2.54, 0*96/2.54));
                    //PrintDialog ptdlg = new PrintDialog();
                    //ptdlg.ShowDialog();
                    //((IDocumentPaginatorSource)doc).DocumentPaginator.PageSize = new Size(ptdlg.PrintableAreaWidth, ptdlg.PrintableAreaHeight);
                    //paginator = new DocumentPaginatorWrapper(paginator, new Size(ptdlg.PrintableAreaWidth, ptdlg.PrintableAreaHeight), new Size(0 * 96 / 2.54, 0 * 96 / 2.54));

                    rsm.SaveAsXaml(paginator);
                    rsm.Commit();
                    xpsDoc.Close();
                    container.Close();


                    XpsDocument tempdoc = new XpsDocument(fileName + ".xps", FileAccess.Read);
                    //viewer.Document = tempdoc.GetFixedDocumentSequence();
                }
            }


            Console.WriteLine("{0} generated.", fileName + ".xps");


            return(0);
        }
Exemple #51
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);
        }
Exemple #52
0
        /// <summary>
        /// Helper method to create page header or footer from flow document template
        /// </summary>
        /// <param name="data">report data</param>
        /// <returns></returns>
        public XpsDocument CreateXpsDocument(ReportData data)
        {
            MemoryStream ms = new MemoryStream();
            Package pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
            string pack = "pack://report.xps";
            PackageStore.RemovePackage(new Uri(pack));
            PackageStore.AddPackage(new Uri(pack), pkg);
            XpsDocument doc = new XpsDocument(pkg, CompressionOption.NotCompressed, pack);
            XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
            DocumentPaginator paginator = ((IDocumentPaginatorSource)CreateFlowDocument()).DocumentPaginator;

            ReportPaginator rp = new ReportPaginator(this, data);
            rsm.SaveAsXaml(rp);
            return doc;
        }
        /// <summary>
        /// Helper method to create page header or footer from flow document template
        /// </summary>
        /// <param name="data">report data</param>
        /// <returns></returns>
        public static XpsDocument CreateXpsDocument(FlowDocument document) {
            MemoryStream ms = new MemoryStream();
            Package pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
            string pack = "pack://report.xps";
            PackageStore.RemovePackage(new Uri(pack));
            PackageStore.AddPackage(new Uri(pack), pkg);
            XpsDocument xpsdoc = new XpsDocument(pkg, CompressionOption.NotCompressed, pack);
            XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsdoc), false);

            DocumentPaginator dp = 
                ((IDocumentPaginatorSource)document).DocumentPaginator;
            rsm.SaveAsXaml(dp);
            return xpsdoc;
        }
Exemple #54
0
        /// <summary>
        /// Helper method to create page header or footer from flow document template
        /// </summary>
        /// <param name="data">enumerable report data</param>
        /// <param name="fileName">file to save XPS to</param>
        /// <returns></returns>
        public XpsDocument CreateXpsDocument(IEnumerable<ReportData> data, string fileName)
        {
            if (data == null) throw new ArgumentNullException("data");
            int count = 0; ReportData firstData = null;
            foreach (ReportData rd in data) { if (firstData == null) firstData = rd; count++; }
            if (count == 1) return CreateXpsDocument(firstData); // we have only one ReportData object -> use the normal ReportPaginator instead

            Package pkg = Package.Open(fileName, FileMode.Create, FileAccess.ReadWrite);
            string pack = "pack://report.xps";
            PackageStore.RemovePackage(new Uri(pack));
            PackageStore.AddPackage(new Uri(pack), pkg);
            XpsDocument doc = new XpsDocument(pkg, _xpsCompressionOption, pack);
            XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
            DocumentPaginator paginator = ((IDocumentPaginatorSource)CreateFlowDocument()).DocumentPaginator;

            MultipleReportPaginator rp = new MultipleReportPaginator(this, data);
            rsm.SaveAsXaml(rp);
            rsm.Commit();
            pkg.Close();
            return new XpsDocument(fileName, FileAccess.Read);
        }
        public void CreatePdf(string filename)
        {
            var WrapPan = VisualTreeHelper.GetParent(PrintPages[0]);

            using (var stream = new MemoryStream())
            {
                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);
                        int width   = 0;
                        int height  = 0;
                        var flowDoc = new FlowDocument();
                        flowDoc.ColumnWidth = 1189;

                        var paginator = ((IDocumentPaginatorSource)flowDoc).DocumentPaginator;
                        paginator.PageSize = new Size(1189, 841);

                        foreach (var _pagge in PrintPages)
                        {
                            if (_pagge is DefaultPage)
                            {
                                var pp = new DefaultPage();
                                pp     = (DefaultPage)_pagge;
                                width  = 842;
                                height = 595;
                                var wp = VisualTreeHelper.GetParent(pp);
                                if (wp != null)
                                {
                                    (wp as WrapPanel).Children.Remove(pp);
                                }
                            }

                            if (_pagge is PageList)
                            {
                                width  = 842;
                                height = 595;
                                var pp = new PageList();
                                pp = (PageList)_pagge;
                                var wp = VisualTreeHelper.GetParent(pp);
                                if (wp != null)
                                {
                                    (wp as WrapPanel).Children.Remove(pp);
                                }
                            }

                            if (_pagge is PageQuest)
                            {
                                height = 842;
                                width  = 595;
                                var pp = new PageQuest();
                                pp = (PageQuest)_pagge;
                                var wp = VisualTreeHelper.GetParent(pp);
                                if (wp != null)
                                {
                                    (wp as WrapPanel).Children.Remove(pp);
                                }
                            }

                            if (_pagge is PageView)
                            {
                                width  = 842;
                                height = 595;
                                var pp = new PageView();
                                pp = (PageView)_pagge;
                                var wp = VisualTreeHelper.GetParent(pp);
                                if (wp != null)
                                {
                                    (wp as WrapPanel).Children.Remove(pp);
                                }
                            }

                            _pagge.Width  = width;
                            _pagge.Height = height;
                            double scale = Math.Min((1189 - 150) / _pagge.Width, (841 - 150) / _pagge.Height);
                            _pagge.LayoutTransform = new ScaleTransform(scale, scale);

                            var para = new Paragraph();
                            para.Inlines.Add(_pagge);

                            flowDoc.Blocks.Add(para);
                        }

                        rsm.SaveAsXaml(paginator);
                        rsm.Commit();
                    }
                }

                stream.Position = 0;
                var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(stream);
                PdfSharp.Xps.XpsConverter.Convert(pdfXpsDoc, filename, 0);
                (WrapPan as WrapPanel).Children.Clear();
                foreach (var page in PrintPages)
                {
                    var p = page.Parent;
                    (p as InlineUIContainer).Child = null;
                }
            }
        }