Example #1
0
        public static void PrintAppointment(AppointmentModel appointment)
        {
            PrintDialog  pd = new PrintDialog();
            FlowDocument fd = new FlowDocument();

            fd.FontFamily  = new FontFamily("Courier New");
            fd.FontSize    = 14;
            fd.PagePadding = new Thickness(50);
            fd.ColumnGap   = 0;
            fd.ColumnWidth = pd.PrintableAreaWidth;
            fd.Blocks.Add(new Paragraph(new Run(String.Format($"{"Subject:",-15}{appointment.Subject,-50}"))));
            fd.Blocks.Add(new Paragraph(new Run(String.Format($"{"Organizer:",-15}{appointment.AppointmentId,-50}"))));
            fd.Blocks.Add(new Paragraph(new Run(String.Format($"{"Beginning date:",-15}{appointment.BeginningDate.ToString("dd-MM -yyyy HH-mm"),-20}"))));
            fd.Blocks.Add(new Paragraph(new Run(String.Format($"{"Ending date:",-15}{appointment.EndingDate.ToString("dd-MM -yyyy HH-mm"),-20}"))));
            fd.Blocks.Add(new Paragraph(new Run(String.Format($"{"Location:",-15}{appointment.Room,-50}"))));
            fd.Blocks.Add(new Paragraph(new Run("Participants")));
            foreach (var item in appointment.Users)
            {
                fd.Blocks.Add(new Paragraph(new Run(String.Format($"{"Name:", -6}{item.Name, -50}"))));
            }
            IDocumentPaginatorSource dps = fd;
            var result = pd.ShowDialog();

            if ((bool)result)
            {
                pd.PrintDocument(dps.DocumentPaginator, "flowdoc");
            }
        }
        public TheoryViewModel(ExamDbContext db, int TopicId, Action showTopics, Action <object> showTasks) : base()
        {
            this.db = db;

            Topic topic = this.db.Topic.Find(TopicId);

            this.TopicId = TopicId;
            Title        = topic.Title;

            try
            {
                theoryFilePath = Path.GetTempPath() + "tempFile.xps";
                File.WriteAllBytes(theoryFilePath, topic.Theory);
                TheoryFile = new XpsDocument(theoryFilePath, FileAccess.Read);
                Theory     = TheoryFile.GetFixedDocumentSequence();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Не удалосб загрузить файл с теорией. " + ex.Message);
            }


            this.showTopics = showTopics;
            this.showTasks  = showTasks;
        }
Example #3
0
        /// <summary>
        /// This method creates a dynamic FlowDocument. You can add anything to this
        /// FlowDocument that you would like to send to the printer
        /// </summary>
        /// <returns></returns>
        public static void CreateFlowDocument(LIVEX.UserControls.NominaMaestros nom)
        {
            // Create a FlowDocument
            FlowDocument doc = new FlowDocument();

            // Create a Section
            Section sec = new Section();



            BlockUIContainer Contenido = new BlockUIContainer();

            Contenido.Child = nom.stkContent;
            sec.Blocks.Add(Contenido);


            // Add Paragraph to Section
            //sec.Blocks.Add(nom);

            // Add Section to FlowDocument
            doc.Blocks.Add(sec);
            doc.Name = "FlowDoc";
            PrintDialog printDlg = new PrintDialog();
            IDocumentPaginatorSource idpSource = doc;

            printDlg.PrintDocument(idpSource.DocumentPaginator, "Hello WPF Printing.");
        }
Example #4
0
        private void ImprimerPokemon_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog dialogue = new PrintDialog();

            dialogue.PageRangeSelection   = PageRangeSelection.AllPages;
            dialogue.UserPageRangeEnabled = true;

            Nullable <Boolean> print = dialogue.ShowDialog();

            if (print == true)
            {
                FlowDocument doc = new FlowDocument();
                doc.ColumnWidth = 99999;
                doc.FontFamily  = new FontFamily("Arial");
                Paragraph para = new Paragraph(new Bold(new Underline(new Run("Liste des Pokémons"))));
                para.TextAlignment = TextAlignment.Center;
                para.FontSize      = 24;
                doc.Blocks.Add(para);

                foreach (Pokemon p in BManager.getPokemon())
                {
                    Paragraph tmp = new Paragraph();
                    tmp.TextAlignment = TextAlignment.Left;
                    tmp = new Paragraph(new Run(p.ID + "  -  " + p.Nom));
                    doc.Blocks.Add(tmp);
                    tmp = new Paragraph(new Run(p.TypeElement + "  -  " + p.carac.ToString()));
                    doc.Blocks.Add(tmp);
                    doc.Blocks.Add(new Paragraph(new Run("")));
                }
                IDocumentPaginatorSource idpSource = doc;
                dialogue.PrintDocument(idpSource.DocumentPaginator, "Rapport Pokemon");
            }
        }
Example #5
0
        public void TestPrintWithDialogue() //with selecting printer
        {
            // Parts of  Code from https://www.c-sharpcorner.com/uploadfile/mahesh/printing-in-wpf/

            // Create a PrintDialog
            PrintDialog printDlg = new PrintDialog();

            // Create a FlowDocument dynamically.
            FlowDocument doc = new FlowDocument(new Paragraph(new Run("Here is some Text.")));

            doc.Name = "FlowDoc";

            // Create IDocumentPaginatorSource from FlowDocument
            IDocumentPaginatorSource idpSource = doc;

            // Call PrintDocument method to send document to printer
            printDlg.PrintDocument(idpSource.DocumentPaginator, "Hello WPF Printing");

            Nullable <Boolean> print = printDlg.ShowDialog();

            if (print == true)
            {
                // Call PrintDocument method to send document to printer
                printDlg.PrintDocument(idpSource.DocumentPaginator, "Hello WPF Printing.");
            }
        }
Example #6
0
        // Token: 0x06007C3C RID: 31804 RVA: 0x0022EF74 File Offset: 0x0022D174
        internal static ITextView GetDocumentPageTextView(ITextPointer pointer)
        {
            DependencyObject parent = pointer.TextContainer.Parent;

            if (parent != null)
            {
                FlowDocumentScrollViewer flowDocumentScrollViewer = PathNode.GetParent(parent) as FlowDocumentScrollViewer;
                if (flowDocumentScrollViewer != null)
                {
                    IServiceProvider serviceProvider = flowDocumentScrollViewer.ScrollViewer.Content as IServiceProvider;
                    Invariant.Assert(serviceProvider != null, "FlowDocumentScrollViewer should be an IServiceProvider.");
                    return(serviceProvider.GetService(typeof(ITextView)) as ITextView);
                }
            }
            int num;
            IDocumentPaginatorSource pointerPage = TextSelectionHelper.GetPointerPage(pointer, out num);

            if (pointerPage != null && num >= 0)
            {
                DocumentPage     page             = pointerPage.DocumentPaginator.GetPage(num);
                IServiceProvider serviceProvider2 = page as IServiceProvider;
                if (serviceProvider2 != null)
                {
                    return(serviceProvider2.GetService(typeof(ITextView)) as ITextView);
                }
            }
            return(null);
        }
        private void mnuPrint_Click(object sender, RoutedEventArgs e)
        {
            if (PrintData != null)
            {
                Paragraph p = new Paragraph();
                p.Inlines.Add(PrintData);
                FlowDocument fd = new FlowDocument(p);
                fd.FontFamily = new FontFamily("Courier New");
                fd.FontSize   = 14.0;

                PrintDialog pd = new PrintDialog();
                fd.PageHeight  = pd.PrintableAreaHeight;
                fd.PageWidth   = pd.PrintableAreaWidth;
                fd.PagePadding = new Thickness(50);
                fd.ColumnGap   = 0;
                fd.ColumnWidth = pd.PrintableAreaWidth;

                IDocumentPaginatorSource dps = fd;
                if (pd.ShowDialog().Value == true)
                {
                    pd.PrintDocument(dps.DocumentPaginator, "WPFToolboxForSiemensPLCs");
                }
            }
            else
            {
                MessageBox.Show(
                    "Activate the Window with the Block you wish to Print, maybe the current Window doesn't support printing!");
            }
        }
            public static void ExportEnergyLabel(PackagedSolution packaged)
            {
                if (packaged.EnergyLabel.Count <= 0)
                {
                    return;
                }

                var fixedDoc = new FixedDocument();

                var v  = new LabelLayout();
                var vm = new LabelExportViewModel(packaged);

                fixedDoc.Pages.Add(CreatePageContent(v, vm));

                var calculationLayout    = new CalculationLayout();
                var calculationViewModel = new CalculationViewModel(packaged.EnergyLabel);

                calculationViewModel.Setup();

                fixedDoc.Pages.Add(CreatePageContent(calculationLayout, calculationViewModel));

                if (packaged.EnergyLabel.Count > 1)
                {
                    calculationLayout    = new CalculationLayout();
                    calculationViewModel = new CalculationViewModel(packaged.EnergyLabel);
                    calculationViewModel.SetupSpecialPage();
                    fixedDoc.Pages.Add(CreatePageContent(calculationLayout, calculationViewModel));
                }

                IDocumentPaginatorSource dps = fixedDoc;

                RunSaveDialog(fixedDoc.DocumentPaginator, packaged.Name);
            }
Example #9
0
        public void PrintMarkdown()
        {
            PrintDialog printDialog = new PrintDialog();

            if (printDialog.ShowDialog() != true)
            {
                return;
            }
            FlowDocument flowDocument = this.CreateFlowDocument(this.Editor);

            flowDocument.PageHeight  = printDialog.PrintableAreaHeight;
            flowDocument.PageWidth   = printDialog.PrintableAreaWidth;
            flowDocument.PagePadding = new Thickness(72.0);
            flowDocument.ColumnGap   = 0.0;
            flowDocument.ColumnWidth = flowDocument.PageWidth - flowDocument.ColumnGap - flowDocument.PagePadding.Left - flowDocument.PagePadding.Right;
            IDocumentPaginatorSource documentPaginatorSource = flowDocument;

            try
            {
                printDialog.PrintDocument(documentPaginatorSource.DocumentPaginator, "MarkdownPad Document");
            }
            catch (System.Exception exception)
            {
                MarkdownEditor._logger.ErrorException("Exception while attempting to print Markdown plain text", exception);
                MessageBoxHelper.ShowErrorMessageBox(LocalizationProvider.GetLocalizedString("Error_PrintMarkdownMessage", false, "MarkdownPadStrings"), LocalizationProvider.GetLocalizedString("Error_PrintMarkdownTitle", false, "MarkdownPadStrings"), exception, "");
            }
        }
        public static void SaveToPdf(this FlowDocument flowDoc, string filename)
        {
            MemoryStream xamlStream = new MemoryStream();

            XamlWriter.Save(flowDoc, xamlStream);
            File.WriteAllBytes("d:\\file.xaml", xamlStream.ToArray());

            IDocumentPaginatorSource text = flowDoc as IDocumentPaginatorSource;

            xamlStream.Close();

            MemoryStream memoryStream = new MemoryStream();
            Package      pkg          = Package.Open(memoryStream, FileMode.Create, FileAccess.ReadWrite);

            string pack = "pack://temp.xps";

            PackageStore.AddPackage(new Uri(pack), pkg);

            XpsDocument             doc = new XpsDocument(pkg, CompressionOption.SuperFast, pack);
            XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
            DocumentPaginator       pgn = text.DocumentPaginator;

            rsm.SaveAsXaml(pgn);

            MemoryStream xpsStream = new MemoryStream();
            var          writer    = new XpsSerializerFactory().CreateSerializerWriter(xpsStream);

            writer.Write(doc.GetFixedDocumentSequence());

            MemoryStream outStream = new MemoryStream();

            NiXPS.Converter.XpsToPdf(xpsStream, outStream);
            File.WriteAllBytes("file.pdf", outStream.ToArray());
        }
Example #11
0
        public IDocumentPaginatorSource CreateDocumentPaginatorSource()
        {
            var document = new FixedDocument();

            for (var i = 0; i < PageCount; i++)
            {
                var page = GetPage(i);
                var fp   = new FixedPage {
                    ContentBox = FrameRect, BleedBox = FrameRect, Width = page.Size.Width, Height = page.Size.Height
                };

                var vb = new DrawingBrush(DrawingVisuals[i].Drawing)
                {
                    Stretch      = Stretch.Uniform,
                    ViewboxUnits = BrushMappingMode.Absolute,
                    Viewbox      = new Rect(page.Size)
                };
                var totalHorizontalMargin = _originalMargin.Left + _originalMargin.Right;
                var toltalVerticalMargin  = _originalMargin.Top + _originalMargin.Bottom;
                var printablePageWidth    = PageSize.Width - totalHorizontalMargin;
                var printablePageHeight   = PageSize.Height - toltalVerticalMargin - 10;

                var rect = new Rect(_originalMargin.Left, _originalMargin.Top, printablePageWidth, printablePageHeight);
                fp.Children.Add(CreateContentRectangle(vb, rect));
                var pageContent = new PageContent();
                ((IAddChild)pageContent).AddChild(fp);
                document.Pages.Add(pageContent);
            }
            _document = document;
            _document.DocumentPaginator.PageSize = new Size(PageSize.Width, PageSize.Height);
            return(_document);
        }
Example #12
0
        // Print the FlowDocument.
        private void mnuFilePrint_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog pd = new PrintDialog();

            if (pd.ShowDialog() == true)
            {
                // Set a page width and height.
                //double wid = fdContents.PageWidth;
                //double hgt = fdContents.PageHeight;
                //fdContents.PageHeight = 900;
                //fdContents.PageWidth = 700;


                // Make an XPS document writer for the print queue.
                XpsDocumentWriter xps_writer =
                    PrintQueue.CreateXpsDocumentWriter(pd.PrintQueue);

                // Turn the FlowDocument into an IDocumentPaginatorSource.
                IDocumentPaginatorSource paginator_source =
                    (IDocumentPaginatorSource)fdContents;

                // Use the IDocumentPaginatorSource's
                // property to get a paginator.
                xps_writer.Write(paginator_source.DocumentPaginator);


                // Restore the original page width and height.
                //fdContents.PageWidth = wid;
                //fdContents.PageHeight = hgt;
            }
        }
Example #13
0
        /// <summary>
        /// CHOOSING PRINT TO PAPER OR PRINT TO WINDOWS
        /// </summary>
        /// <param name="doc"></param>
        private void PrintToReal(FlowDocument doc)
        {
            // Create IDocumentPaginatorSource from FlowDocument
            IDocumentPaginatorSource idpSource = doc;

            if (!isShowReview)
            {
                // Call PrintDocument method to send document to printer
                printDlg.PrintDocument(idpSource.DocumentPaginator, "bill printing");
            }
            else
            {
                // convert FlowDocument to FixedDocument
                var paginator = idpSource.DocumentPaginator;
                var package   = Package.Open(new MemoryStream(), FileMode.Create, FileAccess.ReadWrite);
                var packUri   = new Uri("pack://temp.xps");
                PackageStore.RemovePackage(packUri);
                PackageStore.AddPackage(packUri, package);
                var xps = new XpsDocument(package, CompressionOption.NotCompressed, packUri.ToString());
                XpsDocument.CreateXpsDocumentWriter(xps).Write(paginator);
                FixedDocument fdoc = xps.GetFixedDocumentSequence().References[0].GetDocument(true);

                DocumentViewer previewWindow = new DocumentViewer
                {
                    Document = fdoc
                };
                Window printpriview = new Window();
                printpriview.Content = previewWindow;
                printpriview.Title   = "Print Preview";
                printpriview.Show();
            }
        }
Example #14
0
        private void Print()
        {
            PrintDialog pd = new PrintDialog();

            //if (pd.ShowDialog() != true) return;

            flowDocument.PageHeight = pd.PrintableAreaHeight;
            flowDocument.PageWidth  = pd.PrintableAreaWidth;

            IDocumentPaginatorSource idocument = flowDocument as IDocumentPaginatorSource;

            pd.PrintDocument(idocument.DocumentPaginator, "Hoá đơn bán lẻ số " + quet.DonHangSo);
            this.Close();
            MessageBox.Show("Hoá đơn đã được xuất ra máy in.\nĐơn hàng số: " + quet.DonHangSo, "In hoá đơn");


            //Export bill to image
            if (!Directory.Exists(@".\HoaDonDaXuat"))
            {
                Directory.CreateDirectory(@".\HoaDonDaXuat");
            }
            string todayFolder = @".\HoaDonDaXuat\Hoa Don Ngay " + quet.NgayBan.Substring(0, 8).Replace("/", ".");

            if (!Directory.Exists(todayFolder))
            {
                Directory.CreateDirectory(todayFolder);
            }

            string filename = todayFolder + @"\HoaDonSo" + quet.DonHangSo + "_" + quet.NgayBan.Replace(" ", "-").Replace("/", ".").Replace(":", ".") + ".jpg";

            SaveDocumentPagesToImages(idocument, filename);
        }
Example #15
0
        private void PrintKitchenReceipt(OrderVM e)
        {
            PrintDialog printDlg = new PrintDialog();

            try
            {
                printDlg.PrintQueue = new PrintQueue(new PrintServer(),
                                                     Properties.Settings.Default.POSKitchenPrinter);
            }
            catch
            {
                MessageBox.Show("Printer not setup");
            }
            // Create a FlowDocument dynamically.
            FlowDocument doc = CreateFlowDocument(e);

            doc.Name = "Receipt";

            // Create IDocumentPaginatorSource from FlowDocument
            IDocumentPaginatorSource idpSource = doc;

            // Call PrintDocument method to send document to printer
            printDlg.PrintDocument(idpSource.DocumentPaginator, "Order Receipt");

            ////Printer to number of printers.
            if (Properties.Settings.Default.POSExtraPrinterCount > 0)
            {
                for (int i = 1; i <= Properties.Settings.Default.POSExtraPrinterCount; i++)
                {
                    if (i == 1)
                    {
                        try
                        {
                            printDlg.PrintQueue = new PrintQueue(new PrintServer(),
                                                                 Properties.Settings.Default.POSExtraPrinter01);
                        }
                        catch
                        {
                            MessageBox.Show("Printer not setup");
                        }
                        // Call PrintDocument method to send document to printer
                        printDlg.PrintDocument(idpSource.DocumentPaginator, "Order Receipt");
                    }
                    if (i == 2)
                    {
                        try
                        {
                            printDlg.PrintQueue = new PrintQueue(new PrintServer(),
                                                                 Properties.Settings.Default.POSExtraPrinter02);
                        }
                        catch
                        {
                            MessageBox.Show("Printer not setup");
                        }
                        // Call PrintDocument method to send document to printer
                        printDlg.PrintDocument(idpSource.DocumentPaginator, "Order Receipt");
                    }
                }
            }
        }
Example #16
0
        /// <summary>
        /// Gets the TextView exposed by the page where this pointer lives
        /// </summary>
        /// <param name="pointer">the pointer</param>
        /// <returns>the TextView</returns>
        internal static ITextView GetDocumentPageTextView(ITextPointer pointer)
        {
            int pageNumber;

            DependencyObject content = pointer.TextContainer.Parent as DependencyObject;

            if (content != null)
            {
                FlowDocumentScrollViewer scrollViewer = PathNode.GetParent(content) as FlowDocumentScrollViewer;
                if (scrollViewer != null)
                {
                    IServiceProvider provider = scrollViewer.ScrollViewer.Content as IServiceProvider;
                    Invariant.Assert(provider != null, "FlowDocumentScrollViewer should be an IServiceProvider.");
                    return(provider.GetService(typeof(ITextView)) as ITextView);
                }
            }

            IDocumentPaginatorSource idp = GetPointerPage(pointer, out pageNumber);

            if (idp != null && pageNumber >= 0)
            {
                DocumentPage     docPage = idp.DocumentPaginator.GetPage(pageNumber);
                IServiceProvider isp     = docPage as IServiceProvider;
                if (isp != null)
                {
                    return(isp.GetService(typeof(ITextView)) as ITextView);
                }
            }

            return(null);
        }
Example #17
0
        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            int count = 0;

            try
            {
                this.IsEnabled = false;

                PrintDialog  pd = new PrintDialog();
                FlowDocument fd = new FlowDocument();
                fd.ColumnWidth = 800;
                foreach (object item in lstReports.Items)
                {
                    ++count;
                    fd.Blocks.Add(new Paragraph(new Run("#" + count)));
                    fd.Blocks.Add(new Paragraph(new Run(item.ToString())));
                    fd.Blocks.Add(new Paragraph(new Run("----------------------------------------------------------------------------------------------------------------------------")));
                }
                IDocumentPaginatorSource idocument = fd as IDocumentPaginatorSource;

                pd.PrintDocument(idocument.DocumentPaginator, "Printing flow document...");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.IsEnabled = true;
            }
        }
Example #18
0
        public void PrintMarkdown()
        {
            PrintDialog printDialog = new PrintDialog();

            if (printDialog.ShowDialog() != true)
            {
                return;
            }
            FlowDocument flowDocument = this.CreateFlowDocument(this.textEditor);

            flowDocument.PageHeight  = printDialog.PrintableAreaHeight;
            flowDocument.PageWidth   = printDialog.PrintableAreaWidth;
            flowDocument.PagePadding = new Thickness(72.0);
            flowDocument.ColumnGap   = 0.0;
            flowDocument.ColumnWidth = flowDocument.PageWidth - flowDocument.ColumnGap - flowDocument.PagePadding.Left - flowDocument.PagePadding.Right;
            IDocumentPaginatorSource documentPaginatorSource = flowDocument;

            try
            {
                printDialog.PrintDocument(documentPaginatorSource.DocumentPaginator, "MarkWord");
            }
            catch (System.Exception exception)
            {
                Common.ShowMessage(exception.Message);
            }
        }
        SerializeDocumentReference(
            object documentReference
            )
        {
            IDocumentPaginatorSource idp = ((DocumentReference)documentReference).GetDocument(false);

            if (idp != null)
            {
                FixedDocument fixedDoc = idp as FixedDocument;

                if (fixedDoc != null)
                {
                    ReachSerializer serializer = NgcSerializationManager.GetSerializer(fixedDoc);
                    if (serializer != null)
                    {
                        serializer.SerializeObject(fixedDoc);
                    }
                }
                else
                {
                    ReachSerializer serializer = NgcSerializationManager.GetSerializer(idp.DocumentPaginator);
                    if (serializer != null)
                    {
                        serializer.SerializeObject(idp);
                    }
                }
            }
        }
        private void PrintBtn_Click(object sender, RoutedEventArgs e)
        {
            if ((sender as Button).DataContext != null)
            {
                string sB = (sender as Button).DataContext as string;

                if (sB != null)
                {
                    PrintDialog printDlg = new PrintDialog();

                    FlowDocument doc = CreateFlowDocument(sB);
                    doc.Name = "Errors";
                    IDocumentPaginatorSource idpSource = doc;
                    printDlg.PrintDocument(idpSource.DocumentPaginator, "Drukowanie błędów.");
                }
                else
                {
                    MessageBox.Show("Wystąpił błąd. Nie można eksportować danych.", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                MessageBox.Show("Wystąpił błąd. Nie można eksportować danych.", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #21
0
        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.IsEnabled = false;

                PrintDialog  pd = new PrintDialog();
                FlowDocument fd = new FlowDocument();
                fd.ColumnWidth = 800;
                fd.Blocks.Add(new Paragraph(new Run("Pet Best LLC")));
                fd.Blocks.Add(new Paragraph(new Run("Customer: " + invoiceUser.Firstname + " " + invoiceUser.Lastname)));
                fd.Blocks.Add(new Paragraph(new Run("Address: " + userAddress.Line1 + " " + userAddress.City + " " + userAddress.State)));
                fd.Blocks.Add(new Paragraph(new Run("ZipCode: " + userAddress.ZipCode)));
                fd.Blocks.Add(new Paragraph(new Run("Phone #: " + userAddress.Phone)));
                fd.Blocks.Add(new Paragraph(new Run("Invoice ID #: " + currentInvoice.InvoiceID)));
                fd.Blocks.Add(new Paragraph(new Run("Order ID #: " + currentInvoice.OrderID)));
                fd.Blocks.Add(new Paragraph(new Run("Invoice Date: " + currentInvoice.InvoiceDate + "\t\t\t" + "Due Date: " + currentInvoice.InvoiceDueDate)));
                fd.Blocks.Add(new Paragraph(new Run("Invoice Total: " + currentInvoice.InvoiceTotal + "\t\t\t" + "Payment Total: " + currentInvoice.PaymentTotal)));
                fd.Blocks.Add(new Paragraph(new Run("Notes: \n" + currentInvoice.Notes)));

                IDocumentPaginatorSource idocument = fd as IDocumentPaginatorSource;

                pd.PrintDocument(idocument.DocumentPaginator, "Printing flow document...");
            }
            finally
            {
                this.IsEnabled = true;
            }
        }
Example #22
0
        //--------------------------------------------------------------------
        //
        // Internal Methods
        //
        //---------------------------------------------------------------------

        #region Internal Method

        internal DynamicDocumentPaginator GetPaginator(DocumentReference docRef)
        {
            // #966803: Source change won't be a support scenario.
            Debug.Assert(docRef != null);
            DynamicDocumentPaginator paginator = null;
            IDocumentPaginatorSource document  = docRef.CurrentlyLoadedDoc;

            if (document != null)
            {
                paginator = document.DocumentPaginator as DynamicDocumentPaginator;
                Debug.Assert(paginator != null);
            }
            else
            {
                document = docRef.GetDocument(false /*forceReload*/);
                if (document != null)
                {
                    paginator = document.DocumentPaginator as DynamicDocumentPaginator;
                    Debug.Assert(paginator != null);
                    // hook up event handlers
                    paginator.PaginationCompleted += new EventHandler(_OnChildPaginationCompleted);
                    paginator.PaginationProgress  += new PaginationProgressEventHandler(_OnChildPaginationProgress);
                    paginator.PagesChanged        += new PagesChangedEventHandler(_OnChildPagesChanged);
                }
            }

            return(paginator);
        }
Example #23
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            paymentId = db.AddNewPayment(orderId);
            for (int i = 0; i < lstPayment.Items.Count; i++)
            {
                OrderDetail od   = (OrderDetail)lstPayment.Items[i];
                int         odId = od.OrderDetailId;
                db.UpdateOrderDetailsPaymentId(odId, paymentId);
            }


            // Create a PrintDialog
            PrintDialog printDlg = new PrintDialog();

            // Create a FlowDocument dynamically.
            List <OrderDetail> list = db.GetAllOrderDetailByPaymentId(orderId, paymentId);
            FlowDocument       doc  = CreateFlowDocument(paymentId, list);

            doc.Name = "FlowDoc";

            // Create IDocumentPaginatorSource from FlowDocument
            IDocumentPaginatorSource idpSource = doc;

            // Call PrintDocument method to send document to printer
            printDlg.PrintDocument(idpSource.DocumentPaginator, "RestranPOS Printing.");
            lstPayment.Items.Clear();
            ClearTotal();
            txtId.Text = "";
            this.Close();
        }
        //--------------------------------------------------------------------
        //
        // Private Methods
        //
        //---------------------------------------------------------------------

        #region Private Methods
        private void _EnsureBlockLoaded()
        {
            if (_HasStatus(BlockStatus.UnloadedBlock))
            {
                _ClearStatus(BlockStatus.UnloadedBlock);

                DocumentsTrace.FixedDocumentSequence.TextOM.Trace("Loading TextContainer " + _docRef.ToString());
                // Load the TextContainer
                IDocumentPaginatorSource idp = _docRef.GetDocument(false /*forceReload*/);
                IServiceProvider         isp = idp as IServiceProvider;
                if (isp != null)
                {
                    ITextContainer tc = isp.GetService(typeof(ITextContainer)) as ITextContainer;
                    if (tc != null)
                    {
                        _container = tc;
                        DocumentsTrace.FixedDocumentSequence.TextOM.Trace("Got ITextContainer");
                    }
                }

                if (_container == null)
                {
                    _container = new NullTextContainer();
                }
            }
        }
        //----< prints FlowDocument deserialized from MemoryStream >-------
        void printFromStream(MemoryStream stream)
        {
            FlowDocument             fd   = (FlowDocument)System.Windows.Markup.XamlReader.Load(stream);
            IDocumentPaginatorSource idoc = fd as IDocumentPaginatorSource;

            printDialog.PrintDocument(idoc.DocumentPaginator, "printing analysis");
        }
        private void print_stade_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog pDialog = new PrintDialog();

            pDialog.PageRangeSelection   = PageRangeSelection.AllPages;
            pDialog.UserPageRangeEnabled = true;

            Nullable <Boolean> print = pDialog.ShowDialog();

            if (print == true)
            {
                FlowDocument doc = new FlowDocument();
                doc.ColumnWidth = 99999; //triche :x
                doc.FontFamily  = new FontFamily("Arial");
                //Titre
                Paragraph par = new Paragraph(new Bold(new Underline(new Run("Rapport : liste des Stades"))));
                par.TextAlignment = TextAlignment.Center;
                par.FontSize      = 24;
                doc.Blocks.Add(par);
                //Données
                //doc.LineHeight = 1; //Pourquoi ça colle le texte à gauche...
                foreach (Stade s in BManager.getStades())
                {
                    Paragraph tmp = new Paragraph();
                    tmp.TextAlignment = TextAlignment.Left;
                    tmp = new Paragraph(new Run(s.ID + "  -  " + s.Nom + " : " + s.NbPlace + " places."));
                    doc.Blocks.Add(tmp);
                    tmp = new Paragraph(new Run(s.Element + "  -  " + s.Caract));
                    doc.Blocks.Add(tmp);
                    doc.Blocks.Add(new Paragraph(new Run("")));
                }
                IDocumentPaginatorSource idpSource = doc;
                pDialog.PrintDocument(idpSource.DocumentPaginator, "Rapport Stade");
            }
        }
Example #27
0
        //public void Print()
        //{
        //    PrintDialog printDialog = new PrintDialog();
        //    LocalPrintServer printServer = new LocalPrintServer();
        //    PrintQueue pq = printServer.GetPrintQueue(PrinterVariables.PRINTERNAME);
        //    printDialog.PrintQueue = pq;
        //    FlowDocument flowDoc = new FlowDocument(new Paragraph(new Run(receipt)));
        //    flowDoc.Name = "Receipt";
        //    flowDoc.FontFamily =  new System.Windows.Media.FontFamily(PrinterVariables.FONTNAME);
        //    flowDoc.FontSize = PrinterVariables.FONTSIZE;

        //    IDocumentPaginatorSource idpSource = flowDoc;
        //    printDialog.PrintDocument(idpSource.DocumentPaginator, "Printing Receipt");

        //}

        public void PrintSilently()
        {
            PrintDialog printDialog = new PrintDialog();
            PrintQueue  pq;
            IDocumentPaginatorSource idpSource = flowDoc;

            try
            {
                if (Settings.Default.useNetworkPrinter)
                {
                    string printServerName = @"\\Coregaming";
                    string printQueueName  = "POS";

                    PrintServer ps = new PrintServer(printServerName);
                    pq = ps.GetPrintQueue(printQueueName);
                    flowDoc.PageWidth = printDialog.PrintableAreaWidth;
                }
                else
                {
                    LocalPrintServer printServer = new LocalPrintServer();
                    pq = printServer.GetPrintQueue(PrinterVariables.PRINTERNAME);
                }
                idpSource = flowDoc;
                printDialog.PrintQueue = pq;
                printDialog.PrintDocument(idpSource.DocumentPaginator, "Printing Receipt");
            }
            catch (Exception e)
            {
                MessageBox.Show("Error in PrintSilently():\n" + e.Message + "\n" + e.Data.ToString());
            }
        }
        /// <summary>
        /// Create FlowDocument and open PrintDialog() on ConnectionPrintButton OnClick event
        /// </summary>
        /// <param name="sender">Sender parametser</param>
        /// <param name="e">Event parameter</param>
        private void ConnectionPrintButtonOnClick(object sender, RoutedEventArgs e)
        {
            var connection = (sender as Button).DataContext as Connection;

            PrintDialog printDialog = new PrintDialog();

            // Convert Time format of connection
            var departureTime = DateTime.Parse(connection.From.Departure.ToString()).ToString("HH:mm");
            var arrivalTime   = DateTime.Parse(connection.To.Arrival.ToString()).ToString("HH:mm");

            // Create dynamic FlowDocument
            FlowDocument doc = new FlowDocument(
                new Paragraph(
                    new Run(
                        $"From {connection.From.Station.Name} " +
                        $"To: {connection.To.Station.Name} " +
                        $"From: {departureTime} " +
                        $"Until: {arrivalTime} " +
                        $"Duration: {connection.Duration} " +
                        $"Departure Platform: {connection.From.Platform}")));

            doc.Name = "Connection";

            // Create IDocumentPaginatorSource from FlowDocument
            IDocumentPaginatorSource idpSource = doc;

            // Open PrintDialog and print document on OK result
            Nullable <Boolean> print = printDialog.ShowDialog();

            if (print == true)
            {
                printDialog.PrintDocument(idpSource.DocumentPaginator, "My Connection");
            }
        }
        private void _UpdateDocumentPreview()
        {
            m_SupplementLayout.LoadFile(CurrentLayout);

            var sp = new SupplementPainter(MainWindow.DpiY, mainWindow.DisciplineLabels);

            //sp.LayoutProperties = m_LayoutLoader.LoadLayout(CurrentLayout, LayoutProperties.GetConfigFilename(CurrentSide));
            sp.LayoutProperties        = m_SupplementLayout.GetProperties(CurrentSide);
            sp.IsSkipEmplyLines        = mainWindow.IsSkipEmplyLines.IsChecked == true;
            sp.IsAssessmentsOnLastLine = mainWindow.IsAssessmentsOnLastLine.IsChecked == true;
            sp.IsHorizontalInnings     = mainWindow.IsHorizontalInnings.IsChecked == true;

            m_DrawingVisual = sp.DrawSupplement(CurrentStudent, (LayoutSide)CurrentSide);

            var horizontalBorderHeight = SystemParameters.ResizeFrameHorizontalBorderHeight;
            var verticalBorderWidth    = SystemParameters.ResizeFrameVerticalBorderWidth;
            var captionHeight          = SystemParameters.CaptionHeight;

            var px = mainWindow.IsHorizontalInnings.IsChecked.Value ?
                     MainWindow.CentimeterToPixel(sp.DocumentSize.X, sp.DocumentSize.Y) :
                     MainWindow.CentimeterToPixel(sp.DocumentSize.Y, sp.DocumentSize.X);

            documentViewer.Width  = px.X + verticalBorderWidth;
            documentViewer.Height = px.Y + captionHeight + horizontalBorderHeight;

            Document = XpsDocumentPainter.PaintDrawingVisual(m_DrawingVisual, new PageMediaSize(px.X, px.Y));
        }
        private void printButton_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog  printDlg = new PrintDialog();
            FlowDocument doc      = CreateFlowDocument();

            doc.Name = "FlowDoc";
            IDocumentPaginatorSource idpSource = doc;

            printDlg.PrintDocument(idpSource.DocumentPaginator, "Booking");
            BillingOperation Bo = new BillingOperation(bookingIdBlock.Text, customerNameBlock.Text, Convert.ToDateTime(bookingDateBlock.Text), tableNoBlock.Text, contactBlock.Text,
                                                       Convert.ToDouble(subTotal.Text), Convert.ToDouble(serviceTax.Text), Convert.ToDouble(vat.Text), Convert.ToDouble(discount.Text), Total);
            BillingService bs = new BillingService();

            bs.AddBilling(Bo);
            String Query = "truncate Table Orders";

            DataAccess.ExecuteQuery(Query);
            BookingService bookingService = new BookingService();

            bookingService.DeleteBooking(bookingIdBlock.Text);
            using (BookingReport BR = new BookingReport())
            {
                this.Close();
                BR.ShowDialog();
            }
        }
        private static void PrintDocument(IDocumentPaginatorSource flowDocument)
        {
            PrintDialog flowPrintDialog = XamlTemplatePrinter.GetPrintDialog();
            if (flowPrintDialog == null)
                return;

            PrintQueue flowPrintQueue = flowPrintDialog.PrintQueue;
            flowPrintQueue.CurrentJobSettings.Description = "ANRTournament Document";
            XamlTemplatePrinter.PrintFlowDocument(flowPrintQueue, flowDocument.DocumentPaginator);
        }
 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);
         }
     }
 }
Example #33
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;
        }
Example #34
0
 /// <summary>
 /// Loads the specified IDocumentPaginatorSource document for print preview.
 /// </summary>
 public void LoadDocument(IDocumentPaginatorSource document)
 {
     m_Document = document;
     documentViewer.Document = (IDocumentPaginatorSource)document;
 }
Example #35
0
 private static void WriteXps(IDocumentPaginatorSource fixedDocument, string tempFileName)
 {
     var paginator = fixedDocument.DocumentPaginator;
     using (var xps = new XpsDocument(tempFileName, FileAccess.Write))
     {
         var documentWriter = XpsDocument.CreateXpsDocumentWriter(xps);
         documentWriter.Write(paginator);
     }
 }
        /// <summary>
        /// Handle the case when the position is no longer valid for the current document, conservatively returns true if
        /// is uknown.
        /// </summary>
        private bool IsValidContentPositionForDocument(IDocumentPaginatorSource document, ContentPosition contentPosition)
        {
            FlowDocument flowDocument = document as FlowDocument;
            TextPointer textPointer = contentPosition as TextPointer;

            if(flowDocument != null && textPointer != null)
            {
                return flowDocument.ContentStart.TextContainer == textPointer.TextContainer;
            }

            return true;
        }
        public IDocumentPaginatorSource CreateDocumentPaginatorSource()
        {
            var document = new FixedDocument();
            for (var i = 0; i < PageCount; i++)
            {
                var page = GetPage(i);
                var fp = new FixedPage { ContentBox = FrameRect, BleedBox = FrameRect, Width = page.Size.Width, Height = page.Size.Height };

                var vb = new DrawingBrush(DrawingVisuals[i].Drawing)
                {
                    Stretch = Stretch.Uniform,
                    ViewboxUnits = BrushMappingMode.Absolute,
                    Viewbox = new Rect(page.Size)
                };
                var totalHorizontalMargin = _originalMargin.Left + _originalMargin.Right;
                var toltalVerticalMargin = _originalMargin.Top + _originalMargin.Bottom;
                var printablePageWidth = PageSize.Width - totalHorizontalMargin;
                var printablePageHeight = PageSize.Height - toltalVerticalMargin - 10;

                var rect = new Rect(_originalMargin.Left, _originalMargin.Top, printablePageWidth, printablePageHeight);
                fp.Children.Add(CreateContentRectangle(vb, rect));
                var pageContent = new PageContent();
                ((IAddChild)pageContent).AddChild(fp);
                document.Pages.Add(pageContent);
            }
            _document = document;
            _document.DocumentPaginator.PageSize = new Size(PageSize.Width, PageSize.Height);
            return _document;
        }
 /// <summary>
 /// Loads the source Xaml in the form of a complete FlowDocument. 
 /// At this stage there is no automatic string replacement.
 /// </summary>
 /// <param name="flowDocument">The flow document.</param>
 public void LoadXaml(IDocumentPaginatorSource flowDocument) {
     _flowDocument = flowDocument;
     FlushDispatcher();
 }
Example #39
0
        public void AddDataBubbles(IDocumentPaginatorSource dp,MemoryStream ms)
        {
            CustomControls.Bubbles bb = new CustomControls.Bubbles(1);//
            bb.MouseDoubleClick += new MouseButtonEventHandler(bb_MouseDoubleClick);
            bb.Tag = "Data";
            bb.Width = 325;
            bb.Height = 325;
            bb.RenderTransformOrigin = new Point(0.5, 0.5);
            TransformGroup tg = new TransformGroup();
            double dSc = 0.5;
            ScaleTransform st = new ScaleTransform(dSc, dSc);
            bb.Margin = new Thickness(TestGrid.ActualWidth - bb.Width, TestGrid.Height - bb.Height, 0, 0);

            //string ss = @"mms://202.103.25.141/encoder_ad.wmv";
            bb.SetDocSource(dp,ms);

            tg.Children.Add(st);
            bb.RenderTransform = tg;
            TestGrid.Children.Add(bb);
        }
Example #40
0
        //private DateTime dtStart = new DateTime();
        //private DateTime dtEnd = new DateTime();
        private bool ApplyValue(DataRow dr)
        {
            if (ApplyFtp())
            {
                sConname = dr[1].ToString();
                string ss = dr[2].ToString();
                if (ss.Length > 0)
                {
                    try
                    {
                        xpscontent = CreateXpsDocument(ss,sConName);
                        return GetAgendo(sId);
                    }
                    catch (Exception ex) { sfailedopen = ex.Message; }
                }
                else
                {
                    if (dr[3].ToString() == ".xps")
                    {
                        xpscontent = CreateXpsDocument(fw.DownloadStream(dr[4].ToString()),sMemoryType+dr[0].ToString());
                        return GetAgendo(sId);
                    }
                    else
                    {
                        sfailedopen = "会议内容文件格式未转换!";
                    }
                }

            }
            return false;
        }
Example #41
0
 public void SetDocSource(IDocumentPaginatorSource dp,MemoryStream ms)
 {
     HideTypes();
     sdoc = ms;
     docType.Document = dp;
     docType.Visibility = Visibility.Visible;
 }
Example #42
0
 private void DocShow(IDocumentPaginatorSource dp)
 {
     HideAll();
     DocType.Visibility = Visibility.Visible;
     DocType.Document = dp;
 }
 private void Print(IDocumentPaginatorSource document, PrintDialog dialog)
 {
     document.DocumentPaginator.PageSize = new Size(MaxColumns * 7, LineCount * 15);
     dialog.PrintTicket.PageMediaSize = new PageMediaSize(MaxColumns*7, LineCount*15+2);
     dialog.PrintDocument(document.DocumentPaginator, "");
 }
Example #44
0
        /// <summary>
        /// Finds the DocumentViewerBase object if root is DocumentViewerBase or FlowDocumentReader
        /// in paginated mode. If the root is FDSV or FDR in scroll mode - sets only the document;
        /// </summary>
        /// <param name="root">root the service is enabled on</param>
        /// <param name="documentViewerBase">DocumentViewerBase used by the viewer</param>
        /// <param name="document">document for the viewer</param>
        static private void GetViewerAndDocument(DependencyObject root, out DocumentViewerBase documentViewerBase, out IDocumentPaginatorSource document)
        {
            documentViewerBase = root as DocumentViewerBase;

            // Initialize out parameters
            document = null;

            if (documentViewerBase != null)
            {
                document = documentViewerBase.Document;
            }
            else
            {
                FlowDocumentReader reader = root as FlowDocumentReader;
                if (reader != null)
                {
                    documentViewerBase = AnnotationHelper.GetFdrHost(reader) as DocumentViewerBase;
                    document = reader.Document;
                }
                else
                {
                    FlowDocumentScrollViewer docScrollViewer = root as FlowDocumentScrollViewer;
                    // For backwards compatibility with internal APIs - you can enable
                    // a service on any element with internal APIs - so the root might
                    // not be neither an FDR or a FDSV
                    if (docScrollViewer != null)
                    {
                        document = docScrollViewer.Document;
                    }
                }
            }
        }
Example #45
0
        /// <summary>
        /// Gets the ITextView  of an IDocumentPaginator if any
        /// </summary>
        /// <param name="document">the document</param>
        /// <returns>the ITextView</returns>
        static private ITextView GetTextView(IDocumentPaginatorSource document)
        {
            ITextView textView = null;
            IServiceProvider provider = document as IServiceProvider;
            if (provider != null)
            {
                ITextContainer textContainer = provider.GetService(typeof(ITextContainer)) as ITextContainer;
                if (textContainer != null)
                    textView = textContainer.TextView;

            }
            return textView;

        }
Example #46
0
 public Agendo(string sid, string sname, FtpWeb fw, IDocumentPaginatorSource Content)
 {
     Init(sid, sname, fw);
     xpscontent = Content;
 }
Example #47
0
 public Agendo(string sid, string sname, FtpWeb fw, IDocumentPaginatorSource ids, DateTime dtstart, DateTime dtend)
 {
     Init(sid, sname, fw);
     xpscontent = ids;
     initDatetime(dtstart, dtend);
 }
		public static void ShowDocument(IDocumentPaginatorSource document, string description)
		{
			PrintPreviewViewContent vc = WorkbenchSingleton.Workbench.ViewContentCollection.OfType<PrintPreviewViewContent>().FirstOrDefault();
			if (vc != null) {
				vc.WorkbenchWindow.SelectWindow();
			} else {
				vc = new PrintPreviewViewContent();
				WorkbenchSingleton.Workbench.ShowView(vc);
			}
			vc.Document = document;
			vc.Description = description;
		}
Example #49
0
        /// <summary>
        /// Gets existing views for pages from start to end. Scans only existing view to
        /// avoid loading of unloaded pages.
        /// </summary> 
        /// <param name="idp">IDocumentPaginatorSource</param>
        /// <param name="startPageNumber">start page number</param> 
        /// <param name="endPageNumber">end page number</param> 
        /// <returns>returns a list of text views</returns>
        private static List<ITextView> ProcessMultiplePages(IDocumentPaginatorSource idp, int startPageNumber, int endPageNumber) 
        {
            Invariant.Assert(idp != null, "IDocumentPaginatorSource is null");

            //now get available views 
            DocumentViewerBase viewer = PathNode.GetParent(idp as DependencyObject) as DocumentViewerBase;
            Invariant.Assert(viewer != null, "DocumentViewer not found"); 
 
            // If the pages for the text segment are reversed (possibly a floater where the floater
            // reflow on to a page that comes after its anchor) we just swap them 
            if (endPageNumber < startPageNumber)
            {
                int temp = endPageNumber;
                endPageNumber = startPageNumber; 
                startPageNumber = temp;
            } 
 
            List<ITextView> res = null;
            if (idp != null && startPageNumber >= 0 && endPageNumber >= startPageNumber) 
            {
                res = new List<ITextView>(endPageNumber - startPageNumber + 1);
                for (int pageNb = startPageNumber; pageNb <= endPageNumber; pageNb++)
                { 
                    DocumentPageView view = AnnotationHelper.FindView(viewer, pageNb);
                    if (view != null) 
                    { 
                        IServiceProvider serviceProvider = view.DocumentPage as IServiceProvider;
                        if (serviceProvider != null) 
                        {
                            ITextView textView = serviceProvider.GetService(typeof(ITextView)) as ITextView;
                            if (textView != null)
                                res.Add(textView); 
                        }
                    } 
                } 
            }
 
            return res;
        }
Example #50
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);
				}
			}
		}
Example #51
0
        //-----------------------------------------------------
        // 
        //  Private Methods 
        //
        //------------------------------------------------------ 
        #region Private Methods

        /// <summary>
        /// Gets a single page TextView throug the idp.GetPage. cALL this API only when 
        /// it is sure that the page is loaded
        /// </summary> 
        /// <param name="idp">IDocumentPaginatorSource</param> 
        /// <param name="pageNumber">page number</param>
        /// <returns>returns a list of one view</returns> 
        private static List<ITextView> ProcessSinglePage(IDocumentPaginatorSource idp, int pageNumber)
        {
            Invariant.Assert(idp != null, "IDocumentPaginatorSource is null");
 
            DocumentPage docPage = idp.DocumentPaginator.GetPage(pageNumber);
            IServiceProvider isp = docPage as IServiceProvider; 
            List<ITextView> res = null; 
            if (isp != null)
            { 
                res = new List<ITextView>(1);
                ITextView view = isp.GetService(typeof(ITextView)) as ITextView;
                if (view != null)
                    res.Add(view); 
            }
 
            return res; 
        }
        /// <summary>
        /// The Document has changed and needs to be updated.
        /// </summary>
        private void DocumentChanged(IDocumentPaginatorSource oldDocument, IDocumentPaginatorSource newDocument)
        {
            DependencyObject doDocument;
            DynamicDocumentPaginator dynamicDocumentPaginator;
            _document = newDocument;

            // Cleanup state associated with the old document.
            if (oldDocument != null)
            {
                // If Document was added to logical tree of DocumentViewer before, remove it.
                if (CheckFlags(Flags.DocumentAsLogicalChild))
                {
                    RemoveLogicalChild(oldDocument);
                }
                // Unregister from PaginationProgress and PaginationCompleted events.
                dynamicDocumentPaginator = oldDocument.DocumentPaginator as DynamicDocumentPaginator;
                if (dynamicDocumentPaginator != null)
                {
                    dynamicDocumentPaginator.PaginationProgress -= new PaginationProgressEventHandler(HandlePaginationProgress);
                    dynamicDocumentPaginator.PaginationCompleted -= new EventHandler(HandlePaginationCompleted);
                    dynamicDocumentPaginator.GetPageNumberCompleted -= new GetPageNumberCompletedEventHandler(HandleGetPageNumberCompleted);
                }

                DependencyObject depObj = oldDocument as DependencyObject;
                if (depObj != null)
                {
                    depObj.ClearValue(PathNode.HiddenParentProperty);
                }
            }

            // If DocumentViewer was created through style, then do not modify
            // the logical tree. Instead, set "core parent" for the Document.
            doDocument = _document as DependencyObject;
	        if (doDocument != null && LogicalTreeHelper.GetParent(doDocument) != null && doDocument is ContentElement)
            {
                // Set the "core parent" back to us.
                ContentOperations.SetParent((ContentElement)doDocument, this);
                SetFlags(false, Flags.DocumentAsLogicalChild);
            }
            else
            {
                SetFlags(true, Flags.DocumentAsLogicalChild);
            }

            // Initialize state associated with the new document.
            if (_document != null)
            {
                // If Document should be part of DocumentViewer's logical tree, add it.
                if (CheckFlags(Flags.DocumentAsLogicalChild))
                {
                    AddLogicalChild(_document);
                }
                // Register for PaginationProgress and PaginationCompleted events.
                dynamicDocumentPaginator = _document.DocumentPaginator as DynamicDocumentPaginator;
                if (dynamicDocumentPaginator != null)
                {
                    dynamicDocumentPaginator.PaginationProgress += new PaginationProgressEventHandler(HandlePaginationProgress);
                    dynamicDocumentPaginator.PaginationCompleted += new EventHandler(HandlePaginationCompleted);
                    dynamicDocumentPaginator.GetPageNumberCompleted += new GetPageNumberCompletedEventHandler(HandleGetPageNumberCompleted);
                }

                // Setup DPs and processors for annotation handling.  If the service isn't already
                // enabled the processors will be registered by the service when it is enabled.
                FlowDocument flowDocument;
                DependencyObject doc = _document as DependencyObject;
                if (_document is FixedDocument || _document is FixedDocumentSequence)
                {
                    // Clear properties that aren't needed for FixedDocument
                    this.ClearValue(AnnotationService.DataIdProperty);
                    // Setup service to look for FixedPages in the content
                    AnnotationService.SetSubTreeProcessorId(this, FixedPageProcessor.Id);
                    // Tell the content how to get to its parent DocumentViewer
                    doc.SetValue(PathNode.HiddenParentProperty, this);
                    // If the service is already registered, set it up for fixed content
                    AnnotationService service = AnnotationService.GetService(this);
                    if (service != null)
                    {
                        service.LocatorManager.RegisterSelectionProcessor(new FixedTextSelectionProcessor(), typeof(TextRange));
                        service.LocatorManager.RegisterSelectionProcessor(new FixedTextSelectionProcessor(), typeof(TextAnchor));
                    }
                }
                else if ((flowDocument = _document as FlowDocument) != null)
                {
                    // Tell the content how to get to its parent DocumentViewer
                    flowDocument.SetValue(PathNode.HiddenParentProperty, this);
                    // If the service is already registered, set it up for fixed content
                    AnnotationService service = AnnotationService.GetService(this);
                    if (service != null)
                    {
                        service.LocatorManager.RegisterSelectionProcessor(new TextSelectionProcessor(), typeof(TextRange));
                        service.LocatorManager.RegisterSelectionProcessor(new TextSelectionProcessor(), typeof(TextAnchor));
                        service.LocatorManager.RegisterSelectionProcessor(new TextViewSelectionProcessor(), typeof(DocumentViewerBase));
                    }
                    // Setup service to use DataID processor
                    AnnotationService.SetDataId(this, "FlowDocument");
                }
                else
                {
                    // Clear values that were set directly on the tree - only valid for Fixed or Flow Documents
                    this.ClearValue(AnnotationService.SubTreeProcessorIdProperty);
                    this.ClearValue(AnnotationService.DataIdProperty);
                }
            }

            // Document is also represented as Automation child. Need to invalidate peer to force update.
            DocumentViewerBaseAutomationPeer peer = UIElementAutomationPeer.FromElement(this) as DocumentViewerBaseAutomationPeer;
            if (peer != null)
            {
                peer.InvalidatePeer();
            }

            // Respond to Document change - update state that is affected by this change.
            OnDocumentChanged();
        }
 /// <summary>
 /// Loads the specified IDocumentPaginatorSource document for print preview.
 /// </summary>
 public void LoadDocument(IDocumentPaginatorSource document)
 {
     this.mDocument = document;
       this.documentViewer.Document = (IDocumentPaginatorSource)document;
 }