Exemple #1
0
        private static void OnPrint(object sender, ExecutedRoutedEventArgs e)
        {
            RichTextEditor control     = (RichTextEditor)sender;
            RichTextBox    richTextBox = control.RichTextBox;

            // Serialize RichTextBox content into a stream in Xaml format. Note: XamlPackage format isn't supported in partial trust.
            TextRange    sourceDocument = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
            MemoryStream stream         = new MemoryStream();

            sourceDocument.Save(stream, DataFormats.Xaml);

            // Clone the source document's content into a new FlowDocument.
            FlowDocument flowDocumentCopy  = new FlowDocument();
            TextRange    copyDocumentRange = new TextRange(flowDocumentCopy.ContentStart, flowDocumentCopy.ContentEnd);

            copyDocumentRange.Load(stream, DataFormats.Xaml);

            // Creates a XpsDocumentWriter object, opens a Windows common print dialog and
            // returns a ref parameter that represents information about the dimensions of the media.
            PrintDocumentImageableArea ia        = null;
            XpsDocumentWriter          docWriter = PrintQueue.CreateXpsDocumentWriter(ref ia);

            if (docWriter != null && ia != null)
            {
                DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocumentCopy).DocumentPaginator;

                // Change the PageSize and PagePadding for the document to match the CanvasSize for the printer device.
                paginator.PageSize = new Size(ia.MediaSizeWidth, ia.MediaSizeHeight);
                Thickness pagePadding = flowDocumentCopy.PagePadding;
                flowDocumentCopy.PagePadding = new Thickness(
                    Math.Max(ia.OriginWidth, pagePadding.Left),
                    Math.Max(ia.OriginHeight, pagePadding.Top),
                    Math.Max(ia.MediaSizeWidth - (ia.OriginWidth + ia.ExtentWidth), pagePadding.Right),
                    Math.Max(ia.MediaSizeHeight - (ia.OriginHeight + ia.ExtentHeight), pagePadding.Bottom));
                flowDocumentCopy.ColumnWidth = double.PositiveInfinity;

                // Send DocumentPaginator to the printer.
                docWriter.Write(paginator);
            }
        }
        private void ExecutePrintCommand(object parameter)
        {
            PrintDialog printDialog = new PrintDialog();
            bool?       dlgResult   = printDialog.ShowDialog();

            if (dlgResult == true)
            {
                DataGrid printGrid = Application.Current.Resources["PrintDataGrid"] as DataGrid;

                if (printGrid.Parent != null)
                {
                    FixedPage parentPage = printGrid.Parent as FixedPage;
                    parentPage.Children.Remove(printGrid);
                }

                printGrid.DataContext = Data;

                ICollectionView dataView       = CollectionViewSource.GetDefaultView(printGrid.Items);
                ICollectionView sourceDataView = CollectionViewSource.GetDefaultView((parameter as DataGrid).ItemsSource);

                dataView.SortDescriptions.Clear();
                foreach (SortDescription sortDescription in sourceDataView.SortDescriptions)
                {
                    dataView.SortDescriptions.Add(sortDescription);
                }
                dataView.Refresh();

                FixedDocument fixedDocument = new FixedDocument();
                PageContent   pageContent   = new PageContent();
                FixedPage     fixedPage     = new FixedPage();

                fixedPage.Children.Add(printGrid);
                (pageContent as System.Windows.Markup.IAddChild).AddChild(fixedPage);
                fixedDocument.Pages.Add(pageContent);

                XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(printDialog.PrintQueue);

                writer.Write(fixedDocument, printDialog.PrintTicket);
            }
        }
Exemple #3
0
        public void PrintDocumentAsync(FixedDocument fixedDocument)
        {
            //Get a hold of a PrintQueue.
            PrintQueue printQueue = GetPrintQueue();

            //Create a document writer to print to.
            xpsDocumentWriter = PrintQueue.CreateXpsDocumentWriter(printQueue);

            //We want to know when the printing progress has changed so
            //we can update the UI.
            xpsDocumentWriter.WritingProgressChanged +=
                PrintAsync_WritingProgressChanged;

            //We also want to know when the print job has finished, allowing
            //us to check for any problems.
            xpsDocumentWriter.WritingCompleted += PrintAsync_Completed;

            StartLongPrintingOperation(fixedDocument.Pages.Count);

            //Print the FixedDocument asynchronously.
            xpsDocumentWriter.WriteAsync(fixedDocument);
        }
Exemple #4
0
        private void PrintPlaintext(string text, string docName, int copies)
        {
            // Clone the source document's content into a new FlowDocument.
            FlowDocument flowDocumentCopy = new FlowDocument();

            flowDocumentCopy.Blocks.Add(new Paragraph(new Run(docName)));
            flowDocumentCopy.Blocks.Add(new Paragraph(new Run(text)));

            // Create a XpsDocumentWriter object, open a Windows common print dialog.
            // This methods returns a ref parameter that represents information about the dimensions of the printer media.
            PrintDocumentImageableArea ia        = null;
            XpsDocumentWriter          docWriter = PrintQueue.CreateXpsDocumentWriter(ref ia);

            if (docWriter == null || ia == null)
            {
                throw new NullReferenceException();
            }

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

            // Change the PageSize and PagePadding for the document to match the CanvasSize for the printer device.
            paginator.PageSize = new Size(ia.MediaSizeWidth, ia.MediaSizeHeight);
            Thickness pagePadding = flowDocumentCopy.PagePadding;

            flowDocumentCopy.PagePadding = new Thickness(
                Math.Max(ia.OriginWidth, pagePadding.Left),
                Math.Max(ia.OriginHeight, pagePadding.Top),
                Math.Max(ia.MediaSizeWidth - (ia.OriginWidth + ia.ExtentWidth), pagePadding.Right),
                Math.Max(ia.MediaSizeHeight - (ia.OriginHeight + ia.ExtentHeight), pagePadding.Bottom));
            flowDocumentCopy.ColumnWidth = double.PositiveInfinity;

            PrintDialog dialog = new PrintDialog();

            for (int i = 0; i < copies; i++)
            {
                dialog.PrintDocument(paginator, "asfd");
            }
        }
Exemple #5
0
        protected override void OnPrintCommand()
        {
            // get a print dialog, defaulted to default printer and default printer's preferences.
            PrintDialog printDialog = new PrintDialog();

            printDialog.PrintQueue  = LocalPrintServer.GetDefaultPrintQueue();
            printDialog.PrintTicket = printDialog.PrintQueue.DefaultPrintTicket;

            // get a reference to the FixedDocumentSequence for the viewer.
            FixedDocumentSequence docSeq = this.Document as FixedDocumentSequence;

            // set the default page orientation based on the desired output.
            printDialog.PrintTicket.PageOrientation = GetPageOrientationOfFirstPageOfFixedDocSeq(docSeq);

            if (printDialog.ShowDialog() == true)
            {
                // set the print ticket for the document sequence and write it to the printer.
                docSeq.PrintTicket = printDialog.PrintTicket;

                XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(printDialog.PrintQueue);
                writer.WriteAsync(docSeq, printDialog.PrintTicket);
            }
        }
        PrintAsync(
            IEnumerable pages,
            Size pageSize,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            var isLandscape = pageSize.Width > pageSize.Height;
            var mediaSize   = isLandscape ? new Size(pageSize.Height, pageSize.Width) : pageSize;

            // Set up print ticket.
            var ticket = printQueue.DefaultPrintTicket;

            ticket.PageMediaSize   = new PageMediaSize(mediaSize.Width, mediaSize.Height);
            ticket.PageOrientation = PageOrientation.Portrait;

            // Generate FixedDocument to be printed.
            var document = new FixedDocumentCreator().FromDataContexts(pages, pageSize);

            // Print asynchronously.
            var writer = PrintQueue.CreateXpsDocumentWriter(printQueue);

            return(writer.WriteAsyncAsTask(document, cancellationToken));
        }
Exemple #7
0
        /// <summary>
        /// Manda a imprimir a la impresora seleccionada en los ajustes
        /// </summary>
        private void Print(FixedDocument pFDPage, string pStrPrintName)
        {
            LocalPrintServer lObjPrintServer     = new LocalPrintServer();
            PrinterSettings  lObjPrinterSettings = new PrinterSettings();
            PrintQueue       lObjPrintQueue      = new PrintQueue(lObjPrintServer, Auctions.Properties.Settings.Default.gStrBatchPrinter);

            // var x = lObjPrinterSettings.DefaultPageSettings.PaperSize;
            // x.PaperSize;
            if (lObjPrintQueue == null)
            {
                return;
            }
            XpsDocumentWriter lObjXpswriter = PrintQueue.CreateXpsDocumentWriter(lObjPrintQueue);

            try
            {
                lObjXpswriter.Write(pFDPage);
            }
            catch (Exception lObjException)
            {
                CustomMessageBox.Show("Error", lObjException.Message, this.GetParent());
            }
        }
Exemple #8
0
        private void PrintButton_Click(object sender, RoutedEventArgs e)
        {
            var vm = DataContext as IdViewModel;

            if (vm.SelectedLayout.PrintBackground == false)
            {
                BackgroundImage.Visibility = Visibility.Hidden;
            }
            var queue = vm.SelectedPrinter;

            queue.CurrentJobSettings.Description = "idservice";
            var writer = PrintQueue.CreateXpsDocumentWriter(queue);
            //writer.Write(Area);
            var left = queue.UserPrintTicket.PageMediaSize.Width / 2 - Area.ActualWidth / 2;
            //Area.Margin = new Thickness((double)left, 0, 0, 0);
            var collator = writer.CreateVisualsCollator();

            collator.BeginBatchWrite();
            collator.Write(Area);
            collator.Write(Area);
            collator.EndBatchWrite();
            //writer.WriteAsync(Area);
        }
        /// <summary>
        /// Prints the specified plot model.
        /// </summary>
        /// <param name="model">The model.</param>
        public void Print(IPlotModel model)
        {
            PrintDocumentImageableArea area = null;
            var xpsDocumentWriter           = PrintQueue.CreateXpsDocumentWriter(ref area);

            if (xpsDocumentWriter != null)
            {
                var width  = this.Width;
                var height = this.Height;
                if (double.IsNaN(width))
                {
                    width = area.MediaSizeWidth;
                }

                if (double.IsNaN(height))
                {
                    height = area.MediaSizeHeight;
                }

                var canvas = new Canvas {
                    Width = width, Height = height, Background = this.Background.ToBrush()
                };
                canvas.Measure(new Size(width, height));
                canvas.Arrange(new Rect(0, 0, width, height));

                var rc = new ShapesRenderContext(canvas)
                {
                    TextFormattingMode = this.TextFormattingMode
                };
                model.Update(true);
                model.Render(rc, width, height);

                canvas.UpdateLayout();

                xpsDocumentWriter.Write(canvas);
            }
        }
Exemple #10
0
        private void btnPrintVisuals_Click(object sender, RoutedEventArgs e)
        {
            //Get hold of the visual you want to print.
            List <Visual> visuals = GetVisuals();

            // Create a Print dialog.
            PrintDialog printDialog = new PrintDialog();

            if (printDialog.ShowDialog() != true)
            {
                return;
            }

            // Get the default print queue
            PrintQueue printQueue = printDialog.PrintQueue;

            // Get an XpsDocumentWriter for the default print queue
            XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(printQueue);

            VisualsToXpsDocument vtxd =
                (VisualsToXpsDocument)xpsdw.CreateVisualsCollator();

            //Indicate we want any writes to be performed in a batch operation.
            vtxd.BeginBatchWrite();

            //Write out each visual.
            visuals.ForEach(delegate(Visual visual)
            {
                //Scale the visual
                Visual scaledVisual = ScaleVisual(visual, printQueue);

                vtxd.Write(scaledVisual);
            });

            //Mark the end of the batch operation.
            vtxd.EndBatchWrite();
        }
Exemple #11
0
        public void Print(FlowDocument doc)
        {
            // Clone the source doc's content into a new FlowDocument.
            // This is because the pagination for the printer needs to be
            // done differently than the pagination for the displayed page.
            // We print the copy, rather that the original FlowDocument.
            FlowDocument copy = DuplicateDocument(doc);

            // Create a XpsDocumentWriter object, implicitly opening a Windows common print dialog,
            // and allowing the user to select a printer.

            // get information about the dimensions of the seleted printer+media.
            PrintDocumentImageableArea ia        = null;
            XpsDocumentWriter          docWriter = PrintQueue.CreateXpsDocumentWriter(ref ia);

            if (docWriter == null || ia == null)
            {
                return;
            }
            DocumentPaginator paginator = ((IDocumentPaginatorSource)copy).DocumentPaginator;

            // Change the PageSize and PagePadding for the doc to match the CanvasSize for the printer device.
            paginator.PageSize = new Size(ia.MediaSizeWidth, ia.MediaSizeHeight);
            var t = new Thickness(72);  // copy.PagePadding;

            copy.PagePadding = new Thickness(
                Math.Max(ia.OriginWidth, t.Left),
                Math.Max(ia.OriginHeight, t.Top),
                Math.Max(ia.MediaSizeWidth - (ia.OriginWidth + ia.ExtentWidth), t.Right),
                Math.Max(ia.MediaSizeHeight - (ia.OriginHeight + ia.ExtentHeight), t.Bottom));

            copy.ColumnWidth = double.PositiveInfinity;
            //copy.PageWidth = 528; // allow the page to be the natural with of the output device

            // Send content to the printer.
            docWriter.Write(paginator);
        }
Exemple #12
0
        //Handles the click of the print button in the document
        //viewer, overriding the default behavior.
        private void DocumentViewer_PrintDocument(object sender, RoutedEventArgs e)
        {
            //Get a print queue
            PrintQueue printQueue = ShowPrintDialog();

            if (printQueue == null)
            {
                return;
            }

            try
            {
                //Create a new XPS writer using the chosen print queue.
                XpsDocumentWriter writer
                    = PrintQueue.CreateXpsDocumentWriter(printQueue);

                //We need to use a copy of the document's fixed document
                //sequence when creating the AnnotationDocumentPaginator.
                FixedDocumentSequence fds
                    = xpsDocument.GetFixedDocumentSequence();

                //You now need to create a document paginator for any
                //annotations in the document.
                AnnotationDocumentPaginator adp =
                    new AnnotationDocumentPaginator(fds.DocumentPaginator,
                                                    fixedAnnotationService.Store);

                //Write out the document, with annotations using the annotation
                //document paginator.
                writer.Write(adp);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #13
0
        public void PrintCmdExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            //Printstuff
            FlowDocument printDoc = new FlowDocument();

            printDoc.Blocks.Add(new Paragraph(new Run(stickyWindow.sTextArea.Text)));
            printDoc.PagePadding = new Thickness(25);

            TextRange    source = new TextRange(printDoc.ContentStart, printDoc.ContentEnd);
            MemoryStream stream = new MemoryStream();

            source.Save(stream, DataFormats.Xaml);

            // Create a XpsDocumentWriter object, open a Windows common print dialog.
            // This methods returns a ref parameter that represents information about the dimensions of the printer media.
            PrintDocumentImageableArea ia        = null;
            XpsDocumentWriter          docWriter = PrintQueue.CreateXpsDocumentWriter(ref ia);

            if (docWriter != null && ia != null)
            {
                DocumentPaginator paginator = ((IDocumentPaginatorSource)printDoc).DocumentPaginator;

                // Change the PageSize and PagePadding for the document to match the CanvasSize for the printer device.
                paginator.PageSize = new Size(ia.MediaSizeWidth, ia.MediaSizeHeight);
                Thickness pagePadding = printDoc.PagePadding;
                printDoc.PagePadding = new Thickness(
                    Math.Max(ia.OriginWidth, pagePadding.Left),
                    Math.Max(ia.OriginHeight, pagePadding.Top),
                    Math.Max(ia.MediaSizeWidth - (ia.OriginWidth + ia.ExtentWidth), pagePadding.Right),
                    Math.Max(ia.MediaSizeHeight - (ia.OriginHeight + ia.ExtentHeight), pagePadding.Bottom));
                printDoc.ColumnWidth = double.PositiveInfinity;

                // Send DocumentPaginator to the printer.
                docWriter.Write(paginator);
            }
        }
Exemple #14
0
        private XpsDocumentWriter CreateWriter(string description)
        {
            PrintQueue        printQueue        = null;
            PrintTicket       printTicket       = null;
            XpsDocumentWriter xpsDocumentWriter = null;

            this.PickCorrectPrintingEnvironment(ref printQueue, ref printTicket);
            SystemDrawingHelper.NewDefaultPrintingPermission().Assert();
            try
            {
                if (printQueue != null)
                {
                    printQueue.CurrentJobSettings.Description = description;
                }
                xpsDocumentWriter = PrintQueue.CreateXpsDocumentWriter(printQueue);
                PrintDialog.PrintDlgPrintTicketEventHandler @object = new PrintDialog.PrintDlgPrintTicketEventHandler(printTicket);
                xpsDocumentWriter.WritingPrintTicketRequired += @object.SetPrintTicket;
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
            return(xpsDocumentWriter);
        }
Exemple #15
0
        CreateWriter(
            String description
            )
        {
            PrintQueue        printQueue  = null;
            PrintTicket       printTicket = null;
            XpsDocumentWriter writer      = null;

            PickCorrectPrintingEnvironment(ref printQueue, ref printTicket);

            if (printQueue != null)
            {
                printQueue.CurrentJobSettings.Description = description;
            }

            writer = PrintQueue.CreateXpsDocumentWriter(printQueue);

            PrintDlgPrintTicketEventHandler eventHandler = new PrintDlgPrintTicketEventHandler(printTicket);

            writer.WritingPrintTicketRequired +=
                new WritingPrintTicketRequiredEventHandler(eventHandler.SetPrintTicket);

            return(writer);
        }
Exemple #16
0
        private void btnPrintVisual_Click(object sender, RoutedEventArgs e)
        {
            //Get hold of the visual you want to print.
            Visual visual = GetVisual();

            // Create a Print dialog.
            PrintDialog printDialog = new PrintDialog();

            if (printDialog.ShowDialog() != true)
            {
                return;
            }

            // Get the default print queue
            PrintQueue pq = printDialog.PrintQueue;

            //Scale the visual
            Visual scaledVisual = ScaleVisual(visual, pq);

            // Get an XpsDocumentWriter for the default print queue
            XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(pq);

            xpsdw.Write(scaledVisual);
        }
        internal static void PrintFlowDocument(PrintQueue pq, FlowDocument flowDocument)
        {
            // Create a XpsDocumentWriter object, open a Windows common print dialog.
            // This methods returns a ref parameter that represents information about the dimensions of the printer media.
            XpsDocumentWriter docWriter = PrintQueue.CreateXpsDocumentWriter(pq);
            PageImageableArea ia        = pq.GetPrintCapabilities().PageImageableArea;
            PrintTicket       pt        = pq.UserPrintTicket;

            if (ia != null)
            {
                DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
                // Change the PageSize and PagePadding for the document to match the CanvasSize for the printer device.
                paginator.PageSize = new Size((double)pt.PageMediaSize.Width, (double)pt.PageMediaSize.Height);
                Thickness pagePadding = flowDocument.PagePadding;
                flowDocument.PagePadding = new Thickness(
                    Math.Max(ia.OriginWidth, pagePadding.Left),
                    Math.Max(ia.OriginHeight, pagePadding.Top),
                    Math.Max((double)pt.PageMediaSize.Width - (ia.OriginWidth + ia.ExtentWidth), pagePadding.Right),
                    Math.Max((double)pt.PageMediaSize.Height - (ia.OriginHeight + ia.ExtentHeight), pagePadding.Bottom));
                flowDocument.ColumnWidth = double.PositiveInfinity;
                // Send DocumentPaginator to the printer.
                docWriter.Write(paginator);
            }
        }
        public void PrintReport()
        {
            try
            {
                FlowDocument fd = this.CloneCurrentReportDocument(false);


                PrintDocumentImageableArea pd_ia     = null;
                XpsDocumentWriter          docWriter = PrintQueue.CreateXpsDocumentWriter(ref pd_ia);
                if (docWriter != null && pd_ia != null)
                {
                    DocumentPaginator d_paginator = ((IDocumentPaginatorSource)fd).DocumentPaginator;
                    d_paginator.PageSize = new Size(pd_ia.MediaSizeWidth, pd_ia.MediaSizeHeight);
                    Thickness pagePadding = fd.PagePadding;
                    fd.PagePadding = new Thickness(
                        Math.Max(pd_ia.OriginWidth, pagePadding.Left),
                        Math.Max(pd_ia.OriginHeight, pagePadding.Top),
                        Math.Max(pd_ia.MediaSizeWidth - (pd_ia.OriginWidth + pd_ia.ExtentWidth), pagePadding.Right),
                        Math.Max(pd_ia.MediaSizeHeight - (pd_ia.OriginHeight + pd_ia.ExtentHeight), pagePadding.Bottom));
                    fd.ColumnWidth = double.PositiveInfinity;
                    docWriter.Write(d_paginator);
                }
            }
            catch (Exception ex)
            {
                SiliconStudio.DebugManagers.DebugReporter.Report(
                    SiliconStudio.DebugManagers.MessageType.Error,
                    "EjpControls - Report Editor",
                    "Failed to print Report" +
                    "\nParent Study ID: " + this.ParentStudyId.ToString() +
                    "\nReport ID: " + this._reportObject.Id.ToString() +
                    "\nError: " + ex.Message);

                MessageBox.Show("印刷する際に失敗しました。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #19
0
        private void print(int copies, params int[] pages)
        {
            FixedDocument doc = new FixedDocument();

            doc.DocumentPaginator.PageSize = Document.DocumentPaginator.PageSize;
            doc.Resources   = Document.Resources;
            doc.PrintTicket = Document.PrintTicket;

            PrintTicket ticket = (PrintTicket)doc.PrintTicket;

            ticket.CopyCount = copies;
            //ticket.Collation = Collated ? Collation.Collated : Collation.Uncollated;

            foreach (int p in pages)
            {
                Border border = (Border)Document.Pages[p].Child.Children[0];

                FixedPage fp = new FixedPage();
                fp.Children.Add(new Border()
                {
                    Width      = border.Width,
                    Height     = border.Height,
                    Margin     = border.Margin,
                    Background = border.Background
                });
                doc.Pages.Add(new PageContent()
                {
                    Child = fp
                });
            }

            XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(Printer);

            HandleMessages(writer);
            writer.Write(doc);
        }
Exemple #20
0
        public void PrintFixedDocument(FixedDocument fixedDoc, PrintDialog printDialog)
        {
            XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(printDialog.PrintQueue);

            writer.Write(fixedDoc, printDialog.PrintTicket);
        }
Exemple #21
0
        }// end:GetPrintXpsDocumentWriter()

        //</SnippetPrintQueueSnip>

        // --------------- GetPrintXpsDocumentWriter(PrintQueue) --------------
        /// <summary>
        ///   Returns an XpsDocumentWriter for a given print queue.</summary>
        /// <param name="pq">
        ///   The print queue to return the XpsDocumentWriter for.</param>
        /// <returns>
        ///   An XpsDocumentWriter for the given print queue.</returns>
        private XpsDocumentWriter GetPrintXpsDocumentWriter(PrintQueue pq)
        {
            XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(pq);

            return(xpsdw);
        }// end:GetPrintXpsDocumentWriter(PrintQueue)
Exemple #22
0
        void PrintContent(Object sender, RoutedEventArgs args)
        {
            //Printing with Paginator

            //set pagination with printer's margins and size
            PrintDocumentImageableArea area     = null;
            XpsDocumentWriter          xdwriter = PrintQueue.CreateXpsDocumentWriter(ref area);

            //make a copy to print with pagginator w/o crashing
            TextPointer position1           = mainRichTextBox.Document.ContentStart;
            TextPointer position2           = mainRichTextBox.Document.ContentEnd;
            TextRange   sourceDocumentRange = new TextRange(position1, position2);

            MemoryStream tempstream = new MemoryStream();

            sourceDocumentRange.Save(tempstream, System.Windows.DataFormats.Xaml);

            FlowDocument sourceDocumentCopy = new FlowDocument();
            TextPointer  position3          = sourceDocumentCopy.ContentStart;
            TextPointer  position4          = sourceDocumentCopy.ContentEnd;
            TextRange    copyDocumentRange  = new TextRange(position3, position4);

            copyDocumentRange.Load(tempstream, System.Windows.DataFormats.Xaml);

            if ((xdwriter != null) && (area != null))
            {
                DocumentPaginator paginator = ((IDocumentPaginatorSource)sourceDocumentCopy).DocumentPaginator;
                paginator.PageSize = new Size(area.MediaSizeWidth, area.MediaSizeHeight);

                Thickness pageBounds = sourceDocumentCopy.PagePadding;

                double leftmargin, topmargin, rightmargin, bottommargin;
                if (area.OriginWidth > pageBounds.Left)
                {
                    leftmargin = area.OriginWidth;
                }
                else
                {
                    leftmargin = pageBounds.Left;
                }

                if (area.OriginHeight > pageBounds.Top)
                {
                    topmargin = area.OriginHeight;
                }
                else
                {
                    topmargin = pageBounds.Top;
                }

                double printerRightMargin = area.MediaSizeWidth - (area.OriginWidth + area.ExtentWidth);
                if (printerRightMargin > pageBounds.Right)
                {
                    rightmargin = printerRightMargin;
                }
                else
                {
                    rightmargin = pageBounds.Right;
                }

                double printerBottomMargin = area.MediaSizeHeight - (area.OriginHeight + area.ExtentHeight);
                if (printerBottomMargin > pageBounds.Bottom)
                {
                    bottommargin = printerBottomMargin;
                }
                else
                {
                    bottommargin = pageBounds.Bottom;
                }

                sourceDocumentCopy.PagePadding = new Thickness(leftmargin, topmargin, rightmargin, bottommargin);

                //can be used to set columns
                sourceDocumentCopy.ColumnWidth = double.PositiveInfinity;

                xdwriter.Write(paginator);
            }
        }
        private void printButton_Click(object sender, RoutedEventArgs e)
        {
            int copies;

            if (!int.TryParse(copiesTextBox.Text, out copies) || copies <= 0)
            {
                TaskDialog td = new TaskDialog(Window.GetWindow(this), "Invalid Input",
                                               "The value entered in the Copies field is not a valid. The value must be between 1 and " + int.MaxValue.ToString() + " inclusive.",
                                               MessageType.Error);
                td.ShowDialog();

                copiesTextBox.SelectAll();
                copiesTextBox.Focus();

                return;
            }

            printButton.IsEnabled = false;
            SavePrintSettings();

            PrintQueue printer = selectedPrinter;

            FixedDocument document = (FixedDocument)documentViewer.Document;
            PrintTicket   ticket   = printer.DefaultPrintTicket;

            if (duplexCombo.SelectedItem == oneSide)
            {
                ticket.Duplexing = Duplexing.OneSided;
            }
            else if (duplexCombo.SelectedItem == longDuplex)
            {
                ticket.Duplexing = Duplexing.TwoSidedLongEdge;
            }
            else if (duplexCombo.SelectedItem == shortDuplex)
            {
                ticket.Duplexing = Duplexing.TwoSidedShortEdge;
            }

            ticket.PagesPerSheet = int.Parse(((FrameworkElement)pagesPerSheetCombo.SelectedItem).Tag.ToString());

            document.PrintTicket = ticket;

            bool manDuplex = duplexCombo.SelectedItem == manualDuplex;
            bool collated  = collationCombo.SelectedIndex == 0;

            BackstageEvents.StaticUpdater.InvokeForceBackstageClose(this, EventArgs.Empty);

            if (!manDuplex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    XpsDocumentWriter xps = PrintQueue.CreateXpsDocumentWriter(printer);
                    BackstageEvents.StaticUpdater.InvokePrintStarted(this, new PrintEventArgs(xps));

                    ticket.Collation = collated ? Collation.Collated : Collation.Uncollated;
                    ticket.CopyCount = copies;
                    xps.WriteAsync(document, XpsDocumentNotificationLevel.ReceiveNotificationEnabled);
                });
            }
            else
            {
                Dispatcher.BeginInvoke(() =>
                {
                    new ManualDuplex(document, printer, collated, copies);
                });
            }
        }
Exemple #24
0
        static void Main(string[] args)
        {
            string siteURL = args[0];
            string docLib  = args[1];

            using (SPSite spSite = new SPSite(siteURL))
            {
                SPDocumentLibrary library     = spSite.RootWeb.Lists[docLib] as SPDocumentLibrary;
                string            docPath     = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Automation.xml";
                SPFile            file        = spSite.RootWeb.GetFile(docPath);
                XDocument         automation  = XDocument.Load(new StreamReader(file.OpenBinaryStream()));
                XElement          autoElement = automation.Element("Automation");
                string            masterName  = autoElement.Attribute("Master").Value;
                string            printerName = autoElement.Attribute("Printer").Value;

                // Open the master document
                docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/" + masterName + ".docx";
                SPFile       masterFile      = spSite.RootWeb.GetFile(docPath);
                Stream       docStream       = new MemoryStream();
                Stream       docMasterStream = masterFile.OpenBinaryStream();
                BinaryReader docMasterReader = new BinaryReader(docMasterStream);
                BinaryWriter docWriter       = new BinaryWriter(docStream);
                docWriter.Write(docMasterReader.ReadBytes((int)docMasterStream.Length));
                docWriter.Flush();
                docMasterReader.Close();
                docMasterStream.Dispose();
                Package package = Package.Open(docStream, FileMode.Open, FileAccess.ReadWrite);
                WordprocessingDocument master = WordprocessingDocument.Open(package);
                string guid;
                Uri    XMLUri = CreateCustomXML(master, automation.Descendants("Record").First(), out guid);
                BindControls(master, guid);
                master.Close();
                docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Output 00001.docx";
                spSite.RootWeb.Files.Add(docPath, docStream, true);

                // Loop through all the records from the XML file
                int count = 1;
                foreach (XElement element in automation.Descendants("Record"))
                {
                    if (count != 1)
                    {
                        package = Package.Open(docStream, FileMode.Open, FileAccess.ReadWrite);
                        master  = WordprocessingDocument.Open(package);
                        foreach (CustomXmlPart part in master.MainDocumentPart.CustomXmlParts)
                        {
                            if (part.Uri == XMLUri)
                            {
                                Stream       stream = part.GetStream(FileMode.Create, FileAccess.ReadWrite);
                                StreamWriter sw     = new StreamWriter(stream);
                                sw.Write(element.ToString());
                                sw.Flush();
                                sw.Close();
                                break;
                            }
                        }
                        master.Close();
                        docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Output " + count.ToString("D5") + ".docx";
                        spSite.RootWeb.Files.Add(docPath, docStream, true);
                    }
                    count++;
                }

                // Use Word Automation Services to convert to XPS files
                ConversionJob job = new ConversionJob(WordAutomationServicesName);
                job.UserToken                   = spSite.UserToken;
                job.Settings.UpdateFields       = true;
                job.Settings.OutputFormat       = SaveFormat.XPS;
                job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
                SPList listToConvert = spSite.RootWeb.Lists[docLib];
                job.AddLibrary(listToConvert, listToConvert);
                job.Start();
                for (; ;)
                {
                    Thread.Sleep(5000);
                    ConversionJobStatus status = new ConversionJobStatus(WordAutomationServicesName, job.JobId, null);
                    if (status.Count == status.Succeeded + status.Failed)
                    {
                        break;
                    }
                }

                // Print output XPS files
                LocalPrintServer srv = new LocalPrintServer();
                PrintQueue       pq  = srv.GetPrintQueue(printerName);
                for (int num = 1; num < count; num++)
                {
                    XpsDocumentWriter xdw = PrintQueue.CreateXpsDocumentWriter(pq);
                    docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Output " + num.ToString("D5") + ".xps";
                    SPFile docFile = spSite.RootWeb.GetFile(docPath);
                    package = Package.Open(docFile.OpenBinaryStream(), FileMode.Open, FileAccess.Read);
                    XpsDocument xdoc = new XpsDocument(package);
                    xdoc.Uri = new Uri(docPath);
                    xdw.Write(xdoc.GetFixedDocumentSequence());
                    xdoc.Close();
                }
            }
        }
Exemple #25
0
        private void butPrint_Click(object sender, RoutedEventArgs e)
        {
            //move this first section, including the dlg into PrintHelper, analogous to OpenDental.PrinterL.  Or maybe into OpenDentalWpf.PrinterL?
            PrintDialog dlg  = new PrintDialog();
            PrintQueue  pq   = LocalPrintServer.GetDefaultPrintQueue();
            PrintTicket tick = pq.DefaultPrintTicket;

            tick.PageOrientation = PageOrientation.Landscape;
            dlg.PrintTicket      = tick;
            dlg.PrintQueue       = pq;
            if (dlg.ShowDialog() != true)
            {
                return;
            }
            FixedDocument document = new FixedDocument();

            document.PrintTicket = dlg.PrintTicket;
            document.DocumentPaginator.PageSize = new Size(dlg.PrintableAreaWidth, dlg.PrintableAreaHeight);
            Canvas canvas1 = PrintHelper.GetCanvas(document);
            //set up a grid for printing that's the same as the main grid except for the bottom section with the buttons
            Grid gridPrint = new Grid();

            gridPrint.Width  = 906;
            gridPrint.Height = 603;
            //5 columns
            gridPrint.ColumnDefinitions.Add(new ColumnDefinition());
            ColumnDefinition colDef = new ColumnDefinition();

            colDef.Width = new GridLength(3);
            gridPrint.ColumnDefinitions.Add(colDef);
            gridPrint.ColumnDefinitions.Add(new ColumnDefinition());
            colDef       = new ColumnDefinition();
            colDef.Width = new GridLength(3);
            gridPrint.ColumnDefinitions.Add(colDef);
            gridPrint.ColumnDefinitions.Add(new ColumnDefinition());
            //3 rows
            gridPrint.RowDefinitions.Add(new RowDefinition());
            RowDefinition rowDef = new RowDefinition();

            rowDef.Height = new GridLength(3);
            gridPrint.RowDefinitions.Add(rowDef);
            gridPrint.RowDefinitions.Add(new RowDefinition());
            //draw rectangles to separate sections
            //3 vert:
            Rectangle rect;

            rect        = new Rectangle();
            rect.Fill   = Brushes.LightGray;
            rect.Width  = 3;
            rect.Height = 300;
            Grid.SetRow(rect, 0);
            Grid.SetColumn(rect, 1);
            gridPrint.Children.Add(rect);
            rect        = new Rectangle();
            rect.Fill   = Brushes.LightGray;
            rect.Width  = 3;
            rect.Height = 3;
            Grid.SetRow(rect, 1);
            Grid.SetColumn(rect, 1);
            gridPrint.Children.Add(rect);
            rect        = new Rectangle();
            rect.Fill   = Brushes.LightGray;
            rect.Width  = 3;
            rect.Height = 300;
            Grid.SetRow(rect, 2);
            Grid.SetColumn(rect, 1);
            gridPrint.Children.Add(rect);
            //1 horiz
            rect        = new Rectangle();
            rect.Fill   = Brushes.LightGray;
            rect.Width  = 300;
            rect.Height = 3;
            Grid.SetRow(rect, 1);
            Grid.SetColumn(rect, 2);
            gridPrint.Children.Add(rect);
            //3 more vert:
            rect        = new Rectangle();
            rect.Fill   = Brushes.LightGray;
            rect.Width  = 3;
            rect.Height = 300;
            Grid.SetRow(rect, 0);
            Grid.SetColumn(rect, 3);
            gridPrint.Children.Add(rect);
            rect        = new Rectangle();
            rect.Fill   = Brushes.LightGray;
            rect.Width  = 3;
            rect.Height = 3;
            Grid.SetRow(rect, 1);
            Grid.SetColumn(rect, 3);
            gridPrint.Children.Add(rect);
            rect        = new Rectangle();
            rect.Fill   = Brushes.LightGray;
            rect.Width  = 3;
            rect.Height = 300;
            Grid.SetRow(rect, 2);
            Grid.SetColumn(rect, 3);
            gridPrint.Children.Add(rect);
            //1 more horiz
            rect        = new Rectangle();
            rect.Fill   = Brushes.LightGray;
            rect.Width  = 300;
            rect.Height = 3;
            Grid.SetRow(rect, 1);
            Grid.SetColumn(rect, 4);
            gridPrint.Children.Add(rect);
            //add the grid to the canvas
            canvas1.Children.Add(gridPrint);
            double center = canvas1.Width / 2d;

            Canvas.SetLeft(gridPrint, (canvas1.Width / 2d) - (gridPrint.Width / 2));
            //draw a rectangle around the entire grid
            rect                 = new Rectangle();
            rect.Stroke          = Brushes.DarkGray;
            rect.StrokeThickness = 1;
            rect.Width           = 906;
            rect.Height          = 603;
            Canvas.SetLeft(rect, (canvas1.Width / 2d) - (rect.Width / 2));
            canvas1.Children.Add(rect);
            //add the five dashboard controls
            gridMain.Children.Remove(contrDashProvList);
            gridPrint.Children.Add(contrDashProvList);
            gridMain.Children.Remove(contrDashProdProvs);
            gridPrint.Children.Add(contrDashProdProvs);
            gridMain.Children.Remove(contrDashAR);
            gridPrint.Children.Add(contrDashAR);
            gridMain.Children.Remove(contrDashProdInc);
            gridPrint.Children.Add(contrDashProdInc);
            gridMain.Children.Remove(contrDashNewPat);
            gridPrint.Children.Add(contrDashNewPat);
            //Canvas.SetTop(contrDashProdInc,
                        #if DEBUG
            WinPrintPreview pp = new WinPrintPreview();
            pp.Owner    = this;
            pp.Document = document;
            //warning! Only use the print preview in debug.  It will crash if your mouse moves into the top toolbar.
            pp.ShowDialog();
                        #else
            //dlg.PrintDocument(document.DocumentPaginator,"Dashboard");//old
            XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(dlg.PrintQueue);
            Cursor = Cursors.Wait;
            writer.Write(document, dlg.PrintTicket);                    //use WriteAsynch usually, but we can't here because we "borrowed" the controls from the screen.
            Cursor = Cursors.Arrow;
                        #endif
            //myPanel.Measure(new Size(dialog.PrintableAreaWidth,dialog.PrintableAreaHeight));
            //myPanel.Arrange(new Rect(new Point(0, 0),myPanel.DesiredSize));
            //dlg.PrintVisual(gridMain,"Dashboard");
            gridPrint.Children.Remove(contrDashProvList);
            gridMain.Children.Add(contrDashProvList);
            gridPrint.Children.Remove(contrDashProdProvs);
            gridMain.Children.Add(contrDashProdProvs);
            gridPrint.Children.Remove(contrDashAR);
            gridMain.Children.Add(contrDashAR);
            gridPrint.Children.Remove(contrDashProdInc);
            gridMain.Children.Add(contrDashProdInc);
            gridPrint.Children.Remove(contrDashNewPat);
            gridMain.Children.Add(contrDashNewPat);
        }
        public override void Print(PrintQueue printQueue, Visual visual)
        {
            var xpsDocumentWriter = PrintQueue.CreateXpsDocumentWriter(printQueue);

            xpsDocumentWriter.Write(visual);
        }
        /// <summary>
        /// 打印范围
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="endIndex"></param>
        private void PrintRange(int startIndex, int endIndex)
        {
            if (startIndex >= 0 && endIndex < PageCount && startIndex <= endIndex)
            {
                var queueName = CurrentPrintQueue.FullName;

                //BitmapImage暂时没有办法异步打印
                if (this._paginator is DataTableDocumentPaginator)
                {
                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            ProgressValue = 0;

                            if (endIndex != 0)
                            {
                                ShowProgress = true;
                            }

                            ControlStatus   = false;
                            IsIndeterminate = false;

                            var p = PaginatorFactory.GetDocumentPaginator(_config);

                            p.PageSize = new Size(_paginator.PageSize.Width, _paginator.PageSize.Height);

                            var server = new LocalPrintServer();

                            var queue = server.GetPrintQueue(queueName);

                            queue.UserPrintTicket.PageMediaSize = PageSize;

                            queue.UserPrintTicket.PageOrientation = PageOrientation;

                            var doc = PrintQueue.CreateXpsDocumentWriter(queue);

                            if (endIndex != 0)
                            {
                                doc.WritingProgressChanged += doc_WritingProgressChanged;
                            }

                            doc.Write(new PageRangeDocumentPaginator(startIndex, endIndex, p));

                            if (endIndex != 0)
                            {
                                doc.WritingProgressChanged -= doc_WritingProgressChanged;
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                        finally
                        {
                            ControlStatus = true;
                            ShowProgress  = false;

                            _dispatcher.BeginInvoke(new Action(() => Close()));
                        }
                    });
                }
                else
                {
                    ProgressValue = 0;

                    if (endIndex != 0)
                    {
                        ShowProgress = true;
                    }

                    ControlStatus   = false;
                    IsIndeterminate = false;

                    var p = PaginatorFactory.GetDocumentPaginator(_config);

                    p.PageSize = new Size(_paginator.PageSize.Width, _paginator.PageSize.Height);

                    var server = new LocalPrintServer();

                    var queue = server.GetPrintQueue(queueName);

                    queue.UserPrintTicket.PageMediaSize = PageSize;

                    queue.UserPrintTicket.PageOrientation = PageOrientation;

                    var doc = PrintQueue.CreateXpsDocumentWriter(queue);

                    if (endIndex != 0)
                    {
                        doc.WritingProgressChanged += doc_WritingProgressChanged;
                    }

                    doc.Write(new PageRangeDocumentPaginator(startIndex, endIndex, p));

                    if (endIndex != 0)
                    {
                        doc.WritingProgressChanged -= doc_WritingProgressChanged;
                    }

                    ControlStatus = true;
                    ShowProgress  = false;

                    _dispatcher.BeginInvoke(new Action(() => Close()));
                }
            }
        }
Exemple #28
0
        public bool Print(Printer printer, int pageCount,
                          Func <Size, PageOrientation> getOrientation, Func <int, int, Size, Visual> getPage,
                          Action <WritingProgressChangedEventArgs> progressChanged, Action <WritingCompletedEventArgs> printCompleted)
        {
            if (printer == null || string.IsNullOrEmpty(printer.Name))
            {
                return(false);
            }

            using (var printQueue = GetPrinter(printer.Name))
            {
                if (printQueue == null)
                {
                    return(false);
                }

                var printTicket = GetPrintTicket(printQueue, printer.Ticket);

                /*The first way
                 * var printDialog = new PrintDialog();
                 * printDialog.PrintQueue = printer;
                 * printDialog.PrintTicket = printTicket;
                 */

                //The second way
                printQueue.UserPrintTicket = printTicket;

                //Page Size  1 inch = 96 pixels
                Size originalPageSize;
                try
                {
                    var pageImageableArea = printQueue.GetPrintCapabilities(printTicket).PageImageableArea;
                    originalPageSize = new Size(pageImageableArea.ExtentWidth, pageImageableArea.ExtentHeight);
                }
                catch
                {
                    originalPageSize = new Size(printTicket.PageMediaSize.Width.Value, printTicket.PageMediaSize.Height.Value);
                }

                //Page Orientation
                if (getOrientation != null)
                {
                    if (getOrientation(originalPageSize) == PageOrientation.Landscape)
                    {
                        //exchange width and height
                        originalPageSize            = new Size(originalPageSize.Height, originalPageSize.Width);
                        printTicket.PageOrientation = System.Printing.PageOrientation.Landscape;
                    }
                    else
                    {
                        printTicket.PageOrientation = System.Printing.PageOrientation.Portrait;
                    }
                }
                else
                {
                    if (printTicket.PageOrientation == System.Printing.PageOrientation.Landscape)
                    {
                        originalPageSize = new Size(originalPageSize.Height, originalPageSize.Width);
                    }
                }

                try
                {
                    //The first way
                    //printDialog.PrintDocument(new LabelDocPaginator(pageCount, originalPageSize, getSpecifiedPage), "Print Label");

                    //The second way
                    DisposeXpsDocWriter();

                    _printCompleted  = printCompleted;
                    _progressChanged = progressChanged;

                    _xpsDocWriter = PrintQueue.CreateXpsDocumentWriter(printQueue);
                    _xpsDocWriter.WritingCompleted       += WritingCompleted;
                    _xpsDocWriter.WritingProgressChanged += WritingProgressChanged;

                    _docPaginator = new PrintDocPaginator(pageCount, originalPageSize, getPage);
                    _xpsDocWriter.WriteAsync(_docPaginator);
                }
                catch (Exception ex)
                {
                    DisposeXpsDocWriter();

                    _printCompleted  = null;
                    _progressChanged = null;

                    return(false);
                }
            }

            return(true);
        }