Esempio n. 1
0
        /// <summary>
        /// Renders the document, by rendering each part of the document and concatenating them.
        /// </summary>
        /// <param name="dataContext">The data context, which is to be used during rendering. The document and its parts can bind to the contents of the data context.</param>
        /// <returns></returns>
        public async Task<FixedDocument> RenderAsync(object dataContext)
        {
            // Creates a new fixed document, which will contain the visual content of the parts of the document
            FixedDocument fixedDocument = new FixedDocument();

            // First all pages of all document parts are retrieved, before they are rendered, this is needed to compute the total number of pages
            IEnumerable<FixedPage> fixedPages = new List<FixedPage>();
            foreach (DocumentPart documentPart in this.Parts)
                fixedPages = fixedPages.Union(await documentPart.RenderAsync(dataContext));

            // Cycles over all of the fixed pages of the document and adds the visuals to the fixed document
            int currentPageNumber = 1;
            foreach (FixedPage fixedPage in fixedPages)
            {
                // Sets the current page number and the total number of pages, so that the fixed page is able to bind against them, the layout of the fixed page must be updated afterwards, because otherwise the bindings would not be updated during the exporting process
                fixedPage.SetValue(Document.pageNumberPropertyKey, currentPageNumber++);
                fixedPage.SetValue(Document.totalNumberOfPagesPropertyKey, fixedPages.Count());
                fixedPage.UpdateLayout();

                // Adds the newly rendered fixed page to the fixed document
                fixedDocument.Pages.Add(new PageContent { Child = fixedPage });
            }

            // Returns the rendered fixed document
            return fixedDocument;
        }
Esempio n. 2
0
 /// <summary>
 /// Write a single FixedDocument and close package
 /// </summary>
 public override void Write(FixedDocument fixedDocument)
 {
     Write(fixedDocument, null);
 }
        public FixedDocument ParseFixDocument(double height)
        {
            if (page == null || page.Items == null || page.Items.Length <= 0)
            {
                return(null);
            }
            //return String.Empty;

            if (printer == null)
            {
                return(null);
            }

            if (page.CodepageSpecified)
            {
                this.Codepage = (int)page.Codepage;
            }

            FixedDocument document = new FixedDocument();

            int margin = printer.Margin;
            List <TextBlock> tbList = new List <TextBlock>();
            //double width = 180;//178;//270;
            double width = printer.PaperWidth;

            TextBlock tb = new TextBlock()
            {
                Width = width, Margin = new Thickness(margin, margin, 0, margin), TextWrapping = System.Windows.TextWrapping.Wrap
            };

            tbList.Add(tb);
            bool   firstLine  = true;
            double lineHeight = 0;
            int    idx        = 0;

            foreach (Object elem in page.Items)
            {
                if (elem.GetType() == typeof(Line))
                {
                    tb.Measure(new Size(width, double.PositiveInfinity));
                    if (firstLine)
                    {
                        lineHeight = tb.DesiredSize.Height;
                        firstLine  = false;
                    }
                    if ((tb.DesiredSize.Height + lineHeight) >= height)
                    {
                        tb = new TextBlock()
                        {
                            Width = width, Margin = new Thickness(margin, margin, 0, margin), TextWrapping = System.Windows.TextWrapping.Wrap
                        };
                        tbList.Add(tb);
                        idx++;
                    }
                    Line line = elem as Line;
                    tb.Inlines.Add(ParseLine(line, width, margin));
                }
            }
            foreach (TextBlock textBlock in tbList)
            {
                StackPanel ticket = new StackPanel()
                {
                    Width = width
                };
                ticket.Children.Add(textBlock);
                FixedPage fixedPage = new FixedPage();
                fixedPage.Children.Add(ticket);
                PageContent pageContent = new PageContent();
                ((IAddChild)pageContent).AddChild(fixedPage);
                document.Pages.Add(pageContent);
            }

            return(document);
        }
Esempio n. 4
0
        /// <summary>
        /// Add page to a FixedDocument from string.
        /// </summary>
        /// <param name="document">Document to add to.</param>
        /// <param name="text">Text to add as page.</param>
        public static void AddPageFromText(this FixedDocument document, string text)
        {
            PageContent page = WPF.Documents.GeneratePageFromText(text);

            document.Pages.Add(page);
        }
Esempio n. 5
0
        private void CreateDocument_STAThread()
        {
            #region Prep
            System.Collections.ArrayList data = objData;
            //Create new document
            FixedDocument doc = new FixedDocument();
            //Set page size
            doc.DocumentPaginator.PageSize = new Size(PAPER_SIZE_WIDTH_96, PAPER_SIZE_HEIGHT_96);

            //Number of records
            double count = (double)data.Count;
            #endregion

            if (count > 0)
            {
                #region Declare Variables
                AveryBarcodeLabel label;

                //Determine number of pages to generate
                double pageCount = Math.Ceiling(count / LABELS_PER_SHEET);

                int dataIndex        = 0;
                int currentColumn    = 0;
                int currentPDFColumn = 0;
                int currentRow       = 0;

                iTextSharp.text.pdf.PdfPTable objPDFTable = null;
                #endregion

                #region Open PDF Document
                iTextSharp.text.Rectangle rectPaperSize = new iTextSharp.text.Rectangle((float)PAPER_SIZE_WIDTH_72, (float)PAPER_SIZE_HEIGHT_72);
                iTextSharp.text.Document  objPDFDoc     = CreatePagePDF(_strFilePathPDF, rectPaperSize, (float)SIDE_MARGIN_72, (float)SIDE_MARGIN_72, (float)(TOP_MARGIN_72), 0);
                //objPDFDoc.
                #endregion

                #region Define PDF Column Widths
                //Define PDF Column Widths
                float[] columnWidth = new float[5];
                columnWidth[0] = (float)LABEL_WIDTH_72;
                columnWidth[1] = (float)HORIZONTAL_GAP_72;
                columnWidth[2] = (float)LABEL_WIDTH_72;
                columnWidth[3] = (float)HORIZONTAL_GAP_72;
                columnWidth[4] = (float)LABEL_WIDTH_72;
                #endregion

                for (int i = 0; i < pageCount; i++)
                {
                    #region Prep XPS Page
                    //Create page
                    PageContent page      = new PageContent();
                    FixedPage   fixedPage = this.CreatePageXPS();
                    #endregion

                    //Create labels
                    for (int j = 0; j < 30; j++)
                    {
                        #region Set currentRow
                        if (j % 10 == 0)
                        {
                            currentRow = 0;
                        }
                        else
                        {
                            currentRow++;
                        }
                        #endregion

                        #region Set curentColumn (Vertically)
                        if (j < 10)
                        {
                            currentColumn = 0;
                        }
                        else if (j > 19)
                        {
                            currentColumn = 2;
                        }
                        else
                        {
                            currentColumn = 1;
                        }
                        #endregion

                        #region Set currentPDFColumn (Horizontally)
                        if (j % 3 == 0)
                        {
                            currentPDFColumn = 0;
                        }
                        else if (j % 3 == 1)
                        {
                            currentPDFColumn = 1;
                        }
                        else if (j % 3 == 2)
                        {
                            currentPDFColumn = 2;
                        }
                        #endregion

                        if (dataIndex < count)
                        {
                            #region Start a New Page When Necessary
                            if (dataIndex % 30 == 0 || dataIndex == 0)
                            {
                                if (objPDFTable != null)
                                {
                                    objPDFDoc.Add(objPDFTable);
                                    objPDFDoc.NewPage();
                                }
                                objPDFTable = new iTextSharp.text.pdf.PdfPTable(5);
                                objPDFTable.SetTotalWidth(columnWidth);
                                objPDFTable.LockedWidth = true;
                                //objPDFTable.SplitLate = false;
                                objPDFTable.SkipLastFooter = true;
                                objPDFTable.KeepTogether   = true;
                                //objPDFTable.ExtendLastRow = true;
                            }
                            #endregion

                            #region Get Data and Fill Lines
                            label = new AveryBarcodeLabel();

                            if (data[dataIndex].GetType() == typeof(AveryBarcodeLabel))
                            {
                                label = (AveryBarcodeLabel)data[dataIndex];
                            }
                            else if (data[dataIndex].GetType() == typeof(AveryLabelDataModel))
                            {
                                label = new AveryBarcodeLabel((AveryLabelDataModel)data[dataIndex]);
                            }
                            else if (data[dataIndex].GetType() == typeof(PostalAddress))
                            {
                                PostalAddress objAddr = (PostalAddress)data[dataIndex];
                                label.Line1 = objAddr.Reference;
                                label.Line2 = objAddr.Address1;
                                if (!StringFunctions.IsNullOrWhiteSpace(objAddr.Address2))
                                {
                                    label.Line2 += " " + objAddr.Address2;
                                }
                                if (!StringFunctions.IsNullOrWhiteSpace(objAddr.Address3))
                                {
                                    label.Line2 += " " + objAddr.Address3;
                                }
                                label.Line3 = objAddr.ToLocationString() + " " + objAddr.PostalCode;
                            }
                            else if (data[dataIndex].GetType() == typeof(AddressBookEntry))
                            {
                                AddressBookEntry objAddr = (AddressBookEntry)data[dataIndex];
                                label.Line1 = objAddr.FullName;
                                label.Line2 = objAddr.Address1;
                                if (!StringFunctions.IsNullOrWhiteSpace(objAddr.Address2))
                                {
                                    label.Line2 += " " + objAddr.Address2;
                                }
                                if (!StringFunctions.IsNullOrWhiteSpace(objAddr.Address3))
                                {
                                    label.Line2 += " " + objAddr.Address3;
                                }
                                label.Line3 = objAddr.ToLocationString() + " " + objAddr.PostalCode;
                                label.Email = objAddr.Email;
                                label.Phone = objAddr.Phone;
                            }

                            /*
                             * line1 = (string)data.Rows[dataIndex]["Name"];
                             * line2 = (string)data.Rows[dataIndex]["Address"];
                             * postalCode = (string)data.Rows[dataIndex]["PostalCode"];
                             * line3 = (string)data.Rows[dataIndex]["City"] + " " + (string)data.Rows[dataIndex]["State"] + " " + postalCode;
                             */
                            #endregion

                            #region Draw Label Cell in PDF
                            //Create individual label
                            iTextSharp.text.pdf.PdfPTable tblCell;

                            if ((label.Phone != null && label.Phone.Valid) || (label.Email != null && label.Email.Valid) || (label.Date != null && label.Date != DateTime.MinValue && label.Date != DateTime.MaxValue))
                            {
                                #region Label With Phone/Email/Date
                                Font objFont = new Font();
                                objFont.Size = Font.DEFAULTSIZE - 4;

                                tblCell = new iTextSharp.text.pdf.PdfPTable(2);

                                if (label.Date != null && label.Date != DateTime.MinValue && label.Date != DateTime.MaxValue)
                                {
                                    iTextSharp.text.pdf.PdfPCell objLine1 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line1, objFont));
                                    objLine1.Border = 0;
                                    tblCell.AddCell(objLine1);

                                    iTextSharp.text.pdf.PdfPCell objDate = new iTextSharp.text.pdf.PdfPCell(new Phrase("wd: " + label.Date.ToShortDateString(), objFont));
                                    objDate.HorizontalAlignment = 2; //Right
                                    objDate.Border = 0;
                                    tblCell.AddCell(objDate);
                                }
                                else
                                {
                                    iTextSharp.text.pdf.PdfPCell objLine1 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line1, objFont));
                                    objLine1.Border  = 0;
                                    objLine1.Colspan = 2;
                                    tblCell.AddCell(objLine1);
                                }

                                iTextSharp.text.pdf.PdfPCell objLine2 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line2, objFont));
                                objLine2.Border  = 0;
                                objLine2.Colspan = 2;
                                tblCell.AddCell(objLine2);

                                if (label.Phone != null && label.Phone.Valid)
                                {
                                    iTextSharp.text.pdf.PdfPCell objLine3 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line3, objFont));
                                    objLine3.Border = 0;
                                    objLine3.NoWrap = true;
                                    tblCell.AddCell(objLine3);

                                    iTextSharp.text.pdf.PdfPCell objPhone = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Phone.ToString(), objFont));
                                    objPhone.HorizontalAlignment = 2; //Right
                                    objPhone.Border = 0;
                                    tblCell.AddCell(objPhone);
                                }
                                else
                                {
                                    iTextSharp.text.pdf.PdfPCell objLine3 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line3, objFont));
                                    objLine3.Border  = 0;
                                    objLine3.Colspan = 2;
                                    tblCell.AddCell(objLine3);
                                }

                                if (label.Email != null && label.Email.Valid)
                                {
                                    iTextSharp.text.pdf.PdfPCell objEmail = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Email.ToString(), objFont));
                                    objEmail.HorizontalAlignment = 2; //Right
                                    objEmail.Border  = 0;
                                    objEmail.Colspan = 2;
                                    tblCell.AddCell(objEmail);
                                }

                                #endregion
                            }
                            else
                            {
                                #region Standard Address Label
                                tblCell = new iTextSharp.text.pdf.PdfPTable(1);

                                Font objNameFont = new Font();
                                objNameFont.Size = Font.DEFAULTSIZE - 1;
                                iTextSharp.text.pdf.PdfPCell objLine1 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line1, objNameFont));
                                objLine1.Border = 0;
                                tblCell.AddCell(objLine1);

                                Font objAddrFont = new Font();
                                objAddrFont.Size = Font.DEFAULTSIZE - 3;
                                iTextSharp.text.pdf.PdfPCell objLine2 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line2, objAddrFont));
                                objLine2.Border = 0;
                                tblCell.AddCell(objLine2);

                                if (!StringFunctions.IsNullOrWhiteSpace(label.Line3))
                                {
                                    iTextSharp.text.pdf.PdfPCell objLine3 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line3, objAddrFont));
                                    objLine3.Border = 0;
                                    tblCell.AddCell(objLine3);
                                }

                                #endregion
                            }
                            iTextSharp.text.pdf.PdfPCell pCell = new iTextSharp.text.pdf.PdfPCell(tblCell);
                            pCell.FixedHeight = (float)(LABEL_HEIGHT_72);
                            pCell.Padding     = 5;
                            pCell.Border      = 0;
                            objPDFTable.AddCell(pCell);
                            #endregion

                            #region Add Spacer Cell
                            iTextSharp.text.pdf.PdfPCell objGap = new iTextSharp.text.pdf.PdfPCell();
                            objGap.Border = 0;

                            if (currentPDFColumn == 0)
                            {
                                objPDFTable.AddCell(objGap);
                            }
                            else if (currentPDFColumn == 1)
                            {
                                objPDFTable.AddCell(objGap);
                            }
                            #endregion

                            #region Set XPS Position and Add to Document
                            //Set label location
                            if (currentColumn == 0)
                            {
                                FixedPage.SetLeft(label, SIDE_MARGIN_96);
                            }
                            else if (currentColumn == 1)
                            {
                                FixedPage.SetLeft(label, SIDE_MARGIN_96 + LABEL_WIDTH_96 + HORIZONTAL_GAP_96);
                            }
                            else
                            {
                                FixedPage.SetLeft(label, SIDE_MARGIN_96 + LABEL_WIDTH_96 * 2 + HORIZONTAL_GAP_96 * 2);
                            }
                            FixedPage.SetTop(label, TOP_MARGIN_96 + currentRow * LABEL_HEIGHT_96);

                            //Add label object to page
                            fixedPage.Children.Add(label);
                            #endregion

                            #region Finish Last PDF Row By Adding Blanks
                            if (dataIndex == count - 1) //If I'm on the last cell
                            {
                                if (currentPDFColumn != 3)
                                {
                                    while (currentPDFColumn != 3)
                                    {
                                        currentPDFColumn++;
                                        objPDFTable.AddCell(objGap);
                                    }
                                }
                            }
                            #endregion

                            dataIndex++;
                        }
                    }

                    #region Finalize XPS Page
                    //Invoke Measure(), Arrange() and UpdateLayout() for drawing
                    fixedPage.Measure(new Size(PAPER_SIZE_WIDTH_96, PAPER_SIZE_HEIGHT_96));
                    fixedPage.Arrange(new Rect(new Point(), new Size(PAPER_SIZE_WIDTH_96, PAPER_SIZE_HEIGHT_96)));
                    fixedPage.UpdateLayout();
                    ((IAddChild)page).AddChild(fixedPage);
                    doc.Pages.Add(page);
                    #endregion
                }

                #region Finalize PDF Document
                objPDFDoc.Add(objPDFTable);
                objPDFDoc.Close();
                #endregion
            }

            #region Write XPS Document
            if (!StringFunctions.IsNullOrWhiteSpace(_strFilePathXPS))
            {
                if (File.Exists(_strFilePathXPS))
                {
                    File.Delete(_strFilePathXPS);
                }
                XpsDocument xpsd = new XpsDocument(_strFilePathXPS, FileAccess.ReadWrite);
                System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd);
                xw.Write(doc);
                xpsd.Close();
            }
            #endregion
        }
 private InternalPrintProcessor(IPrintProcessor printProcessor, FixedDocument fixedDocument)
 {
     _printProcessor = printProcessor;
     _fixedDocument  = fixedDocument;
     _pageHelper     = CreateNewPageHelper();
 }
Esempio n. 7
0
 public void InsertDocument(int insertAfterDocIndex, FixedDocument fixedDocument)
 {
     _documents.Insert(insertAfterDocIndex, new RollUpFixedDocument(fixedDocument));
     _fixedDocumentSequence = null;
 }
        /// <summary>
        /// Generates a Report based on the current Configuration.
        /// Returns operation-result.
        /// </summary>
        // IMPORTANT: See this page about the VisualsToXpsDocument class:
        // http://msdn.microsoft.com/en-us/library/system.windows.xps.visualstoxpsdocument.aspx
        public OperationResult <int> Generate(ThreadWorker <int> Worker)
        {
            General.ContractRequiresNotNull(Worker);

            try
            {
                this.Configuration = this.OriginalConfiguration.GenerateDeepClone();    // Cloned to allow inter-thread use.

                var Result = new FixedDocument();
                IsAtGenerationStart = true;

                this.CurrentWorker = Worker;
                this.CurrentWorker.ReportProgress(0, "Starting.");

                // IMPORTANT: This page must be created to determine initial dimensions,
                //            even when the user selected to exclude it from the document.
                var TitlePage = this.CreateTitlePage(this.Configuration.DocSection_TitlePage);

                if (this.Configuration.DocSection_TitlePage)
                {
                    Result.Pages.Add(this.CreatePageContainer(TitlePage));
                }

                this.CurrentWorker.ReportProgress(1, "Generating Composition content.");

                // IMPORTANT: This ReportPagesMaker creation must be after the first page to get the page's dimensions.
                var PagesMaker = new ReportStandardPagesMaker(this);

                /* PENDING
                 * if (this.Configuration.DocSection_TableOfContents)
                 *  this.CreateTableOfContents().ForEach(page => Result.Pages.Add(this.CreatePageContainer(page))); */

                if (this.Configuration.DocSection_Composition)
                {
                    this.CreateCompositeContent(PagesMaker, this.SourceComposition, 0.0, 1.0, 90.0);
                }

                this.CurrentWorker.ReportProgress(90, "Generating Domain content.");
                if (this.Configuration.DocSection_Domain)
                {
                    this.CreateDomainContent(PagesMaker, this.SourceComposition.CompositeContentDomain);
                }

                this.CurrentWorker.ReportProgress(93, "Paginating.");
                var Pages = PagesMaker.GetPages();

                foreach (var Page in Pages)
                {
                    Result.Pages.Add(this.CreatePageContainer(Page));
                }

                this.CurrentWorker.ReportProgress(97, "Saving to temporal XPS document.");
                var FileName = General.GenerateRandomFileName(this.SourceComposition.TechName + "_TMP", "xps");
                this.GeneratedDocumentTempFilePath = Path.Combine(AppExec.ApplicationUserTemporalDirectory, FileName);

                Display.SaveDocumentAsXPS(Result, this.GeneratedDocumentTempFilePath);

                this.CurrentWorker.ReportProgress(100, "Generation complete.");
                this.CurrentWorker = null;
            }
            catch (Exception Problem)
            {
                this.CurrentWorker = null;
                return(OperationResult.Failure <int>("Cannot execute generation.\nProblem: " + Problem.Message));
            }

            return(OperationResult.Success <int>(0, "Generation complete."));
        }
Esempio n. 9
0
        public virtual FixedDocument CreateReportFixedDocument()
        {
            excel = new CExcelRenderer(rptCfg.ReportName);
            FixedDocument fd = new FixedDocument();

            ReportProgressUpdate updateFunc = GetProgressUpdateFunc();
            ReportStatusUpdate   doneFunc   = GetProgressDoneFunc();

            fd.DocumentPaginator.PageSize = PageSize;

            if (doneFunc != null)
            {
                doneFunc(false, false);
            }

            ArrayList arr = getRecordSet();

            if (arr == null)
            {
                return(fd);
            }

            int         cnt  = arr.Count;
            UReportPage area = null;

            createRowTemplates();
            excel.CalculateMergeCellRange(baseTemplateName);

            int i = 0;
            int r = 0;

            Size areaSize = GetAreaSize();

            AvailableSpace = areaSize.Height;

            CReportDataProcessingProperty property = null;

            while (i < arr.Count)
            {
                CTable o = (CTable)arr[i];

                if ((r == 0) || (property.IsNewPageRequired))
                {
                    AvailableSpace = areaSize.Height;

                    CurrentPage++;

                    FixedPage fp = new FixedPage();
                    fp.Margin = Margin;

                    PageContent pageContent = new PageContent();
                    ((System.Windows.Markup.IAddChild)pageContent).AddChild(fp);

                    area = initNewArea(areaSize);
                    fp.Children.Add(area);

                    if (isInRange(CurrentPage))
                    {
                        fd.Pages.Add(pageContent);
                        pages.Add(area);
                    }
                }

                property = DataToProcessingProperty(o, arr, i);
                if (property.IsNewPageRequired)
                {
                    //Do not create row if that row caused new page flow
                    //But create it in the next page instead
                    i--;
                    r--;
                }
                else
                {
                    ConstructUIRows(area, property);
                }

                if (updateFunc != null)
                {
                    updateFunc(i, cnt);
                }

                i++;
                r++;
            }

            if (doneFunc != null)
            {
                doneFunc(true, false);
            }

            keepFixedDoc = fd;
            return(fd);
        }
Esempio n. 10
0
        //-------------------------------------------------------------------
        //
        //  Constructors
        //
        //-------------------------------------------------------------------

        #region Constructors

        /// <summary>
        /// Constructor
        /// </summary>
        internal FixedDocumentPaginator(FixedDocument document)
        {
            _document = document;
        }
Esempio n. 11
0
        public void PrintDataGrid(FrameworkElement header, DataGrid grid, FrameworkElement footer, PrintDialog printDialog)
        {
            if (header == null)
            {
                header = new FrameworkElement(); header.Width = 1; header.Height = 1;
            }
            if (footer == null)
            {
                footer = new FrameworkElement(); footer.Width = 1; footer.Height = 1;
            }
            if (grid == null)
            {
                return;
            }

            Size pageSize = new Size(PageWidth, PageHeight);

            FixedDocument fixedDoc = new FixedDocument();

            fixedDoc.DocumentPaginator.PageSize = pageSize;

            double GridActualWidth = grid.ActualWidth == 0 ? 100 : grid.ActualWidth;

            double PageWidthWithMargin  = pageSize.Width - Margin * 2;
            double PageHeightWithMargin = pageSize.Height - Margin * 2;



            // scale the header
            double headerScale  = (header?.Width ?? 0) / PageWidthWithMargin;
            double headerWidth  = PageWidthWithMargin;
            double headerHeight = (header?.Height ?? 0) * headerScale;

            header.Height = headerHeight;
            header.Width  = headerWidth;
            // scale the footer
            double footerScale  = (footer?.Width ?? 0) / PageWidthWithMargin;
            double footerWidth  = PageWidthWithMargin;
            double footerHeight = (footer?.Height ?? 0) * footerScale;

            footer.Height = footerHeight;
            footer.Width  = footerWidth;

            int    pageNumber = 1;
            string Now        = DateTime.Now.ToShortDateString();

            //add the header
            FixedPage fixedPage = new FixedPage();

            fixedPage.Background = Brushes.White;
            fixedPage.Width      = pageSize.Width;
            fixedPage.Height     = pageSize.Height;

            FixedPage.SetTop(header, Margin);
            FixedPage.SetLeft(header, Margin);

            fixedPage.Children.Add(header);
            // its like cursor for current page Height to start add grid rows
            double CurrentPageHeight = headerHeight + 1 * cm;
            int    lastRowIndex      = 0;
            bool   IsFooterAdded     = false;

            for (; ;)
            {
                int AvaliableRowNumber;


                var SpaceNeededForRestRows = (CurrentPageHeight + (grid.Items.Count - lastRowIndex) * RowHeight);

                //To avoid printing the footer in a separate page
                if (SpaceNeededForRestRows > (pageSize.Height - footerHeight - Margin) && (SpaceNeededForRestRows < (pageSize.Height - Margin)))
                {
                    AvaliableRowNumber = (int)((pageSize.Height - CurrentPageHeight - Margin - footerHeight) / RowHeight);
                }
                // calc the Avaliable Row acording to CurrentPageHeight
                else
                {
                    AvaliableRowNumber = (int)((pageSize.Height - CurrentPageHeight - Margin) / RowHeight);
                }

                // create new page except first page cause we created it prev
                if (pageNumber > 1)
                {
                    fixedPage            = new FixedPage();
                    fixedPage.Background = Brushes.White;
                    fixedPage.Width      = pageSize.Width;
                    fixedPage.Height     = pageSize.Height;
                }

                // create new data grid with  columns width and binding
                DataGrid gridToAdd;
                gridToAdd = GetDataGrid(grid, GridActualWidth, PageWidthWithMargin);


                FixedPage.SetTop(gridToAdd, CurrentPageHeight); // top margin
                FixedPage.SetLeft(gridToAdd, Margin);           // left margin

                // add the avaliable rows to the cuurent grid
                for (int i = lastRowIndex; i < grid.Items.Count && i < AvaliableRowNumber + lastRowIndex; i++)
                {
                    gridToAdd.Items.Add(grid.Items[i]);
                }
                lastRowIndex += gridToAdd.Items.Count + 1;

                // add date
                TextBlock dateText = new TextBlock();
                if (DateVisibility)
                {
                    dateText.Visibility = Visibility.Visible;
                }
                else
                {
                    dateText.Visibility = Visibility.Hidden;
                }
                dateText.Text = Now;

                // add page number
                TextBlock PageNumberText = new TextBlock();
                if (PageNumberVisibility)
                {
                    PageNumberText.Visibility = Visibility.Visible;
                }
                else
                {
                    PageNumberText.Visibility = Visibility.Hidden;
                }
                PageNumberText.Text = "Page : " + pageNumber;

                FixedPage.SetTop(dateText, PageHeightWithMargin);
                FixedPage.SetLeft(dateText, Margin);

                FixedPage.SetTop(PageNumberText, PageHeightWithMargin);
                FixedPage.SetLeft(PageNumberText, PageWidthWithMargin - PageNumberText.Text.Length * 10);

                fixedPage.Children.Add(gridToAdd);
                fixedPage.Children.Add(dateText);
                fixedPage.Children.Add(PageNumberText);

                // calc Current Page Height to know the rest Height of this page
                CurrentPageHeight += gridToAdd.Items.Count * RowHeight;

                // all grid rows added
                if (lastRowIndex >= grid.Items.Count)
                {
                    // if footer have space it will be added to the same page
                    if (footerHeight < (PageHeightWithMargin - CurrentPageHeight))
                    {
                        FixedPage.SetTop(footer, CurrentPageHeight + Margin);
                        FixedPage.SetLeft(footer, Margin);

                        fixedPage.Children.Add(footer);
                        IsFooterAdded = true;
                    }
                }

                fixedPage.Measure(pageSize);
                fixedPage.Arrange(new Rect(new Point(), pageSize));
                fixedPage.UpdateLayout();

                PageContent pageContent = new PageContent();
                ((IAddChild)pageContent).AddChild(fixedPage);
                fixedDoc.Pages.Add(pageContent);

                pageNumber++;
                // go to start position : New page Top
                CurrentPageHeight = Margin;

                // this mean that lastRowIndex >= grid.Items.Count  and the footer dont have enough space
                if (lastRowIndex >= grid.Items.Count && !IsFooterAdded)
                {
                    FixedPage ffixedPage = new FixedPage();
                    ffixedPage.Background = Brushes.White;
                    ffixedPage.Width      = pageSize.Width;
                    ffixedPage.Height     = pageSize.Height;

                    FixedPage.SetTop(footer, Margin);
                    FixedPage.SetLeft(footer, Margin);

                    TextBlock fdateText = new TextBlock();
                    if (DateVisibility)
                    {
                        fdateText.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        fdateText.Visibility = Visibility.Hidden;
                    }
                    dateText.Text = Now;

                    TextBlock fPageNumberText = new TextBlock();
                    if (PageNumberVisibility)
                    {
                        fPageNumberText.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        fPageNumberText.Visibility = Visibility.Hidden;
                    }
                    fPageNumberText.Text = "Page : " + pageNumber;

                    FixedPage.SetTop(fdateText, PageHeightWithMargin);
                    FixedPage.SetLeft(fdateText, Margin);

                    FixedPage.SetTop(fPageNumberText, PageHeightWithMargin);
                    FixedPage.SetLeft(fPageNumberText, PageWidthWithMargin - PageNumberText.ActualWidth);

                    ffixedPage.Children.Add(footer);
                    ffixedPage.Children.Add(fdateText);
                    ffixedPage.Children.Add(fPageNumberText);

                    ffixedPage.Measure(pageSize);
                    ffixedPage.Arrange(new Rect(new Point(), pageSize));
                    ffixedPage.UpdateLayout();

                    PageContent fpageContent = new PageContent();
                    ((IAddChild)fpageContent).AddChild(ffixedPage);
                    fixedDoc.Pages.Add(fpageContent);
                    IsFooterAdded = true;
                }

                if (IsFooterAdded)
                {
                    break;
                }
            }
            PrintFixedDocument(fixedDoc, printDialog);
        }
Esempio n. 12
0
        public void PrintFixedDocument(FixedDocument fixedDoc, PrintDialog printDialog)
        {
            XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(printDialog.PrintQueue);

            writer.Write(fixedDoc, printDialog.PrintTicket);
        }
Esempio n. 13
0
        //</SnippetXpsSaveLoadFixedDocSeq>


        //<SnippetCreateFixedDocument>
        // ------------------------ CreateFixedDocument -----------------------
        /// <summary>
        ///   Creates an empty FixedDocument.</summary>
        /// <returns>
        ///   An empty FixedDocument without any content.</returns>
        private FixedDocument CreateFixedDocument()
        {
            FixedDocument fixedDocument = new FixedDocument();
            fixedDocument.DocumentPaginator.PageSize = new Size(96 * 8.5, 96 * 11);
            return fixedDocument;
        }
Esempio n. 14
0
 public override void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket, object userSuppliedState);
Esempio n. 15
0
 public override void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket);
Esempio n. 16
0
 /// <summary>
 /// Asynchronous Write a single FixedDocument and close package
 /// </summary>
 public override void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket)
 {
     throw new NotSupportedException();
 }
Esempio n. 17
0
 public override void WriteAsync(FixedDocument fixedDocument);
Esempio n. 18
0
        private void ViewDocument(string fullPath)
        {
            try
            {
                //Tests.Test1();
                //return;

                Stopwatch sw1   = new Stopwatch();
                Stopwatch sw2   = new Stopwatch();
                int       pages = 0;

                System.Windows.Input.Cursor cursor = Mouse.OverrideCursor;
                try
                {
                    Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;

                    sw1.Start();

                    DocumentCore dc;

                    if (fullPath.ToLower().EndsWith(".pdf"))
                    {
                        dc = DocumentCore.Load(fullPath, new PdfLoadOptions()
                        {
                            DetectTables = false
                        });
                    }
                    else
                    {
                        dc = DocumentCore.Load(fullPath);
                    }

                    sw1.Stop();

                    FixedDocument fd = new FixedDocument();
                    fd.Cursor = System.Windows.Input.Cursors.Arrow;

                    sw2.Start();

                    foreach (SautinSoft.Document.DocumentPage page in dc.GetPaginator().Pages)
                    {
                        fd.Pages.Add(CreatePageContent(page));
                        pages++;
                    }

                    sw2.Stop();

                    documentViewer.Document = fd;

                    dc = null;
                }
                finally
                {
                    Mouse.OverrideCursor = cursor;
                    GC.Collect();
                }

                documentViewer.UpdateLayout();

                _lastLoadedDocument = fullPath;
                Viewer.Title        = "Document .Net Viewer - " + fullPath;

                LoadedCaption.Content   = @"Loaded (ms): " + sw1.ElapsedMilliseconds;
                RenderedCaption.Content = @"Rendered (ms): " + sw2.ElapsedMilliseconds;
                UpdateStatus();
            }
            catch (Exception ex)
            {
                _lastLoadedDocument     = null;
                documentViewer.Document = null;
                documentViewer.UpdateLayout();
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Esempio n. 19
0
 public int AddDocument(FixedDocument fixedDocument)
 {
     _documents.Add(new RollUpFixedDocument(fixedDocument));
     _fixedDocumentSequence = null;
     return(DocumentCount - 1);
 }
Esempio n. 20
0
 /// <summary>
 ///     Saves the <see cref="FixedDocument" /> to the given location.
 /// </summary>
 /// <param name="fixedDocument">The document to save.</param>
 /// <param name="fileName">The location where to the document should be saved.</param>
 public static void SaveFixedDocument(FixedDocument fixedDocument, string fileName)
 {
     WriteXps(fixedDocument, fileName);
 }
Esempio n. 21
0
 // ----------------- PrintSingleFixedContentDocument ------------------
 /// <summary>
 ///   Synchronously prints of a given fixed
 ///   document to a specified document writer.</summary>
 /// <param name="xpsdw">
 ///   The document writer to output to.</param>
 /// <param name="fd">
 ///   The fixed document to print.</param>
 private void PrintSingleFixedContentDocument(
     XpsDocumentWriter xpsdw, FixedDocument fd)
 {
     xpsdw.Write(fd);    // Write the FixedDocument as a document.
 }
Esempio n. 22
0
        /// <summary>
        /// Async Write a single FixedDocument and close stream
        /// </summary>
        public override void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket)
        {
            CheckDisposed();

            _xpsDocumentWriter.WriteAsync(fixedDocument, printTicket);
        }
Esempio n. 23
0
        internal void GenerateFixedDocument(List <Artikel_art> liste, int zahl)
        {
            bool ok;                   // Parse
            int  anzahldavor     = 0;  // anzahl der Aufkeber die ausgelassen werden sollen
            int  aufkleberanzahl = 12; // Anzahl der zu druckenden Aufkleber pro Blatt

            #region Positionen frei lassen
            if (uiTBAnzahlDavor.Text.Trim() != "")                        // Wenn das Feld nicht leer gelassen wurde
            {
                ok = int.TryParse(uiTBAnzahlDavor.Text, out anzahldavor); // Dann Parses

                if (!ok || anzahldavor > aufkleberanzahl - 1)             // Prüfen ob eine gültige Zahl übergeben wurde
                {
                    MessageBox.Show("Anzahl der davor gedruckten Aufkleber ist keine gültige Zahl [1 bis " + (aufkleberanzahl - 1) + "]", "Druckfehler");
                    return;
                }
                // Dann Fälle abprüfen, um die ausgellassen Positionen hinzuzufügen
                // Davor gedruckte Anzahl < als die vorherig eingetragene
                if (aufklebeberdavor > anzahldavor)
                {
                    _idListe.RemoveRange(0, aufklebeberdavor);
                    aufklebeberdavor = 0;
                    for (int i = 0; i < anzahldavor; i++)
                    {
                        _idListe.Insert(i, null);

                        aufklebeberdavor = anzahldavor;
                    }
                }
                // Davor gedruckte Anzahl > als die vorherig eingetragene
                else
                {
                    for (int i = 0; i < anzahldavor; i++)
                    {
                        if (_idListe.Count() < anzahldavor || _idListe[i] != null)
                        {
                            _idListe.Insert(i, null);
                        }
                        aufklebeberdavor = anzahldavor;
                    }
                }
            }


            // Wenn das Feld "" ist
            // davor gedruckte Anzahl wird zurückgesetzt
            else if (aufklebeberdavor > 0)
            {
                _idListe.RemoveRange(0, aufklebeberdavor);
                aufklebeberdavor = 0;
            }
            #endregion Positionen frei lassen

            #region Artikel2Id
            // Id von übergebenen Artikeln wird gesammelt

            //int zahl = 1000;
            if (liste != null)
            {
                rmanzahl.Add(0);
                foreach (var item in liste)
                {
                    if (item.iId != null)
                    {
                        int?[] zwischen = new int?[2];
                        rmanzahl[rmanzahl.Count() - 1]++;
                        int?id = item.iId;
                        if (id != null)
                        {
                            zwischen[0] = id;
                            zwischen[1] = zahl;
                            _idListe.Add(zwischen);
                        }
                    }
                }
            }
            #endregion Artikel2Id

            // Wenn Aufkleber zum Drucken da sind
            if (_idListe.Count() != 0)
            {
                #region Id2Aufkleber
                List <Aufkleber> array = new List <Aufkleber>();
                for (int i = 0; i < _idListe.Count(); i++)
                {
                    if (_idListe[i] != null)
                    {
                        int?[] zwischen = new int?[2];
                        zwischen = _idListe[i];
                        if (zwischen[0] != null)
                        {
                            _db = new Database();
                            if (zwischen[1] > 1)
                            {
                                Aufkleber aZwischen = _db.LadeAufkleber((int)zwischen[0]);

                                for (int j = 0; j < zwischen[1]; j++)
                                {
                                    array.Add(aZwischen);
                                }
                            }
                            else
                            {
                                array.Add(_db.LadeAufkleber((int)zwischen[0])); // Aufkleber Array wird aus DB geladen
                            }
                        }
                    }
                    else
                    {
                        array.Add(null); // freier Platz (bereits gedruckte Aufkleber)
                    }
                }
                #endregion Id2Aufkleber
                #region Dokument mit Aufklebern erstellen
                // Dokument erstellen
                uiDocumentViewer.FitToMaxPagesAcross(1);
                Size          pagesize = new Size(Cm2Dip(21), Cm2Dip(29.7)); // DIN A4
                FixedDocument document = new FixedDocument();
                document.DocumentPaginator.PageSize = pagesize;

                double  oben;
                double  links;
                int     counter;
                decimal seiten;

                seiten = ((decimal)array.Count()) / ((decimal)aufkleberanzahl);

                int stellearray = 0;
                int maxarray    = aufkleberanzahl;

                // Seiten mit Aufklebern hinzufügen
                for (int i = 0; i < seiten; i++)
                {
                    oben    = 0.0;
                    links   = 0.75;
                    counter = 1;

                    // Neue Seite
                    FixedPage page1 = new FixedPage
                    {
                        Width  = document.DocumentPaginator.PageSize.Width,
                        Height = document.DocumentPaginator.PageSize.Height
                    };

                    // Neuer Aufkleber
                    for (int j = stellearray; j < maxarray && j < array.Count(); j++)
                    {
                        // Nur wenn der Aufkleber nicht ausgelassen werden soll
                        if (array[j] != null)
                        {
                            UcAufkleber p1e1 = new UcAufkleber();
                            p1e1.DataContext = array[j];
                            p1e1.Margin      = new Thickness(Cm2Dip(links), Cm2Dip(oben), 0, 0);
                            p1e1.Width       = Cm2Dip(9);
                            p1e1.Height      = Cm2Dip(4.5);
                            page1.Children.Add(p1e1);
                        }
                        // Position des nächsten Aufklebers festlegen
                        if (counter == 2)
                        {
                            counter = 1;
                            oben   += 4.5;
                            links   = 0.75;
                        }
                        else
                        {
                            counter++;
                            links += 9.75;
                        }
                    }

                    // Inhalt zur Seite hinzufügen
                    PageContent page3Content = new PageContent();
                    ((IAddChild)page3Content).AddChild(page1);
                    document.Pages.Add(page3Content);
                    stellearray += aufkleberanzahl;
                    maxarray    += aufkleberanzahl;
                }

                // Dokument erstellen
                uiDocumentViewer.Document = document;
                #endregion Dokument mit Aufklebern erstellen
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Async Write a single FixedDocument and close stream
        /// </summary>
        public override void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket, object userState)
        {
            CheckDisposed();

            _xpsDocumentWriter.WriteAsync(fixedDocument, printTicket, userState);
        }
Esempio n. 25
0
        private void Btn_ExportReport_Click(object sender, RoutedEventArgs e)
        {
            List <string>    pagename = new List <string>();
            List <FixedPage> fps      = new List <FixedPage>();

            if (tempIndex == -1)
            {
                errorMessage tempError = new errorMessage("설계안을 먼저 선택하세요.");
                return;
            }

            // 배치도 테스트

            List <CorePlan>  tempCorePlans  = new List <CorePlan>();
            List <FloorPlan> tempFloorPlans = new List <FloorPlan>();

            foreach (List <CoreProperties> i in MainPanel_AGOutputList[tempIndex].CoreProperties)
            {
                foreach (CoreProperties j in i)
                {
                    tempCorePlans.Add(new CorePlan(j));
                }
            }

            for (int i = 0; i < MainPanel_AGOutputList[tempIndex].HouseholdProperties.Count(); i++)
            {
                for (int j = 0; j < MainPanel_AGOutputList[tempIndex].HouseholdProperties[i][0].Count(); j++)
                {
                    tempFloorPlans.Add(new FloorPlan(MainPanel_AGOutputList[tempIndex].HouseholdProperties[i][0][j], MainPanel_planLibraries));
                }
            }

            foreach (CorePlan i in tempCorePlans)
            {
                List <Curve> tempCrvs = i.normals;
                tempCrvs.AddRange(i.others);
                tempCrvs.AddRange(i.walls);

                foreach (Curve j in tempCrvs)
                {
                    RhinoDoc.ActiveDoc.Objects.AddCurve(j);
                }
            }


            foreach (FloorPlan i in tempFloorPlans)
            {
                List <Curve> tempCrvs = i.all;

                foreach (Curve j in tempCrvs)
                {
                    RhinoDoc.ActiveDoc.Objects.AddCurve(j);
                }
            }

            // 배치도 테스트 끝

            List <System.Windows.Documents.FixedPage> FixedPageList = new List <System.Windows.Documents.FixedPage>();

            FixedDocument currentDoc = new FixedDocument();

            currentDoc.DocumentPaginator.PageSize = new Size(1240, 1753);

            List <Page> pagesToVIew = new List <Page>();

            //page1 표지

            Reports.xmlcover cover = new Reports.xmlcover();
            cover.SetTitle = TuringAndCorbusierPlugIn.InstanceClass.page1Settings.ProjectName;

            fps.Add(cover.fixedPage);
            pagename.Add("Cover");

            //page2 건축개요

            Reports.xmlBuildingReport buildingReport = new Reports.xmlBuildingReport(MainPanel_AGOutputList[tempIndex]);

            fps.Add(buildingReport.fixedPage);
            pagename.Add("buildingReport");

            //page3~ 세대타입별 개요

            List <HouseholdStatistics> uniqueHouseHoldProperties = MainPanel_AGOutputList[tempIndex].HouseholdStatistics.ToList();

            List <string> typeString          = MainPanel_AGOutputList[tempIndex].AreaTypeString();
            double        coreAreaSum         = MainPanel_AGOutputList[tempIndex].GetCoreAreaSum();
            double        UGParkingLotAreaSum = MainPanel_AGOutputList[tempIndex].ParkingLotUnderGround.GetAreaSum();
            double        publicFacilityArea  = MainPanel_AGOutputList[tempIndex].GetPublicFacilityArea();
            double        serviceArea         = -1000; //*****

            for (int i = 0; i < uniqueHouseHoldProperties.Count(); i++)
            {
                HouseholdProperties i_Copy = new HouseholdProperties(uniqueHouseHoldProperties[i].ToHouseholdProperties());

                i_Copy.Origin = new Point3d(i_Copy.Origin.X, i_Copy.Origin.Y, 0);

                double tempCoreArea       = coreAreaSum / MainPanel_AGOutputList[tempIndex].GetExclusiveAreaSum() * i_Copy.GetExclusiveArea();
                double tempParkingLotArea = UGParkingLotAreaSum / MainPanel_AGOutputList[tempIndex].GetExclusiveAreaSum() * i_Copy.GetExclusiveArea();

                Reports.xmlUnitReport unitReport = new Reports.xmlUnitReport(i_Copy, typeString[i], tempCoreArea, tempParkingLotArea, publicFacilityArea, serviceArea, uniqueHouseHoldProperties[i].Count);
                unitReport.setUnitPlan(uniqueHouseHoldProperties[i], MainPanel_planLibraries);

                fps.Add(unitReport.fixedPage);
                pagename.Add("unitReport" + (i + 1).ToString());
            }

            //page4

            /*
             * //아직 평면 드로잉 안끝남 (20160504);
             *
             * ImageFilePath = generateImageFileName(imageFileName, tempImageNumber);
             * Report.BasicPage plans = new Report.BasicPage("배치도");
             * plans.SetTypicalPlan = typicalPlan.drawTipicalPlan(MainPanel_AGOutputList[tempIndex].HouseHoldProperties, MainPanel_AGOutputList[tempIndex].CoreProperties, MainPanel_AGOutputList[tempIndex].buildingOutline, MainPanel_AGOutputList[tempIndex].Plot, 0);
             *
             * List<Rectangle3d> tempParkingLotBoundary = new List<Rectangle3d>();
             *
             * foreach(ParkingLot i in MainPanel_AGOutputList[tempIndex].ParkingLot)
             * {
             *  tempParkingLotBoundary.Add(i.Boundary);
             * }
             *
             * FixedPageList.Add(GeneratePDF.CreateFixedPage(plans));
             * /*
             *
             * //page5
             *
             * Report.BasicPage section = new Report.BasicPage("단면도");
             *
             * FixedPageList.Add(GeneratePDF.CreateFixedPage(section));
             */

            //page6

            /*
             *
             * Reports.xmlRegulationCheck regCheck = new Reports.xmlRegulationCheck(MainPanel_AGOutputList[tempIndex]);
             *
             * fps.Add(regCheck.fixedPage);
             * pagename.Add("regCheck");
             */

            TuringAndCorbusierPlugIn.InstanceClass.showmewindow.showmeinit(fps, pagename, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.ProjectName);


            RhinoApp.WriteLine(pagename.ToArray().Length.ToString());

            TuringAndCorbusierPlugIn.InstanceClass.showmewindow.Show();
            //TuringAndCorbusierPlugIn.InstanceClass.showmewindow

            //pdf 생성

            //GeneratePDF.SaveFixedDocument(FixedPageList);
            //GeneratePDF.CreatePortableFile(userControlList, "C://Program Files (x86)//이주데이타//가로주택정비//" + "testFile.xps");

            /*
             * GeneratePDF.CreaterPortableFile(FixedPageList, "C://Program Files (x86)//이주데이타//가로주택정비//" + "testFile.xps");
             * GeneratePDF.SavePdfFromXps();
             */
        }
Esempio n. 26
0
        /// <summary>
        /// Creates a <see cref="FixedDocument"/> containing the text.
        /// </summary>
        /// <param name="pageSize">Size of the page.</param>
        /// <param name="documentTitle">The document title (can be <see langword="null"/>).</param>
        /// <returns>A <see cref="FixedDocument"/>.</returns>
        /// <remarks>This document can be used for printing.</remarks>
        public FixedDocument CreateFixedDocument(Size pageSize, string documentTitle)
        {
            // Create fixed document with the specified page size.
            var fixedDocument = new FixedDocument();

            fixedDocument.DocumentPaginator.PageSize = pageSize;

            // We add a hardcoded border.
            var borderPadding = new Thickness(96, 90, 96, 80);

            // CreateFlowDocument() creates the highlighted, word-wrapped pages for us.
            var flowDocument = CreateFlowDocument(pageSize, borderPadding);
            var paginator    = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;

            paginator.ComputePageCount();

            // Loop through all pages and add a FixedPage for each page in the FlowDocument.
            var numberOfPages = paginator.PageCount;

            for (int pageNumber = 0; pageNumber < numberOfPages; pageNumber++)
            {
                var fixedPage = new FixedPage
                {
                    Width  = fixedDocument.DocumentPaginator.PageSize.Width,
                    Height = fixedDocument.DocumentPaginator.PageSize.Height
                };

                // The first child of the FixedPage is a DocumentPageView control that displays
                // a page of the FlowDocument.
                var documentPageView = new DocumentPageView
                {
                    DocumentPaginator = paginator,
                    PageNumber        = pageNumber,
                };
                fixedPage.Children.Add(documentPageView);

                // The second child of the FixedPage is a header with document title and page number.
                var header = new Grid
                {
                    Margin = new Thickness(borderPadding.Left, 60, 0, 0),
                    Width  = pageSize.Width - borderPadding.Left - borderPadding.Right,
                };
                header.Children.Add(new Border
                {
                    BorderBrush     = Brushes.Black,
                    BorderThickness = new Thickness(0, 0, 0, 0.5),
                });
                header.Children.Add(new TextBlock(new Run($"{pageNumber + 1} / {numberOfPages}"))
                {
                    FontFamily          = new FontFamily("Times New Roman"),
                    FontSize            = 10,
                    HorizontalAlignment = HorizontalAlignment.Right,
                    Margin = new Thickness(0, 0, 0, 3),
                });
                header.Children.Add(new TextBlock(new Run(documentTitle))
                {
                    FontFamily          = new FontFamily("Times New Roman"),
                    FontSize            = 10,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Margin = new Thickness(0, 0, 0, 3),
                });
                fixedPage.Children.Add(header);

                // Add the FixedPage to the FixedDocument.
                PageContent pageContent = new PageContent();
                ((IAddChild)pageContent).AddChild(fixedPage);
                fixedDocument.Pages.Add(pageContent);
            }

            return(fixedDocument);
        }
 /// <summary>
 /// Write a single FixedDocument and close package
 /// </summary>
 public override void Write(FixedDocument fixedDocument, PrintTicket printTicket)
 {
     SerializeObjectTree(fixedDocument);
 }
Esempio n. 28
0
 /// <summary>
 /// Asynchronous Write a single FixedDocument and close package
 /// </summary>
 public abstract void WriteAsync(FixedDocument fixedDocument);
Esempio n. 29
0
        public override FixedDocument CreateFixedDocument()
        {
            FixedDocument fd = new FixedDocument();

            ReportProgressUpdate updateFunc = GetProgressUpdateFunc();
            ReportStatusUpdate   doneFunc   = GetProgressDoneFunc();

            fd.DocumentPaginator.PageSize = PageSize;

            if (doneFunc != null)
            {
                doneFunc(false, false);
            }

            Parameter.SetFieldValue("DOCUMENT_TYPE", ((int)CashDocumentType.CashDocXfer).ToString());
            ArrayList arr = OnixWebServiceAPI.GetCashDocList(Parameter);

            if (arr == null)
            {
                return(fd);
            }

            int         cnt  = arr.Count;
            UReportPage area = null;

            createRowTemplates();
            int i = 0;

            Size areaSize = GetAreaSize();

            AvailableSpace = areaSize.Height;

            CReportDataProcessingProperty property = null;

            while (i < arr.Count)
            {
                CTable o = (CTable)arr[i];

                if ((i == 0) || (property.IsNewPageRequired))
                {
                    AvailableSpace = areaSize.Height;

                    CurrentPage++;

                    FixedPage fp = new FixedPage();
                    fp.Margin = Margin;

                    PageContent pageContent = new PageContent();
                    ((System.Windows.Markup.IAddChild)pageContent).AddChild(fp);

                    fd.Pages.Add(pageContent);
                    area = initNewArea(areaSize);

                    pages.Add(area);
                    fp.Children.Add(area);
                }

                property = DataToProcessingProperty(o, arr, i);
                if (property.IsNewPageRequired)
                {
                    //Do not create row if that row caused new page flow
                    //But create it in the next page instead
                    i--;
                }
                else
                {
                    ConstructUIRows(area, property);
                }

                if (updateFunc != null)
                {
                    updateFunc(i, cnt);
                }

                i++;
            }

            if (doneFunc != null)
            {
                doneFunc(true, false);
            }

            keepFixedDoc = fd;
            return(fd);
        }
Esempio n. 30
0
 public abstract void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket);
Esempio n. 31
0
 /// <summary>
 /// Write a single FixedDocument and close package
 /// </summary>
 public override void Write(FixedDocument fixedDocument, PrintTicket printTicket)
 {
     Write(fixedDocument.DocumentPaginator, printTicket);
 }
Esempio n. 32
0
 public abstract void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket, object userState);
Esempio n. 33
0
 /// <summary>
 /// Asynchronous Write a single FixedDocument and close package
 /// </summary>
 public override void WriteAsync(FixedDocument fixedDocument, object userState)
 {
     throw new NotSupportedException();
 }
Esempio n. 34
0
        public void Execute(object parameter)
        {
            if (parameter is FrameworkElement)
            {
                FrameworkElement objectToPrint = parameter as FrameworkElement;
                PrintDialog      printDialog   = new PrintDialog();
                if ((bool)printDialog.ShowDialog().GetValueOrDefault())
                {
                    Mouse.OverrideCursor = Cursors.Wait;
                    PrintCapabilities capabilities =
                        printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket);
                    double        dpiScale = 300.0 / 96.0;
                    FixedDocument document = new FixedDocument();
                    try
                    {
                        // Change the layout of the UI Control to match the width of the printer page
                        objectToPrint.Width = capabilities.PageImageableArea.ExtentWidth;
                        objectToPrint.UpdateLayout();
                        objectToPrint.Measure(new System.Windows.Size(double.PositiveInfinity, double.PositiveInfinity));
                        System.Windows.Size size = new System.Windows.Size(capabilities.PageImageableArea.ExtentWidth,
                                                                           objectToPrint.DesiredSize.Height);
                        objectToPrint.Measure(size);
                        size = new System.Windows.Size(capabilities.PageImageableArea.ExtentWidth,
                                                       objectToPrint.DesiredSize.Height);
                        objectToPrint.Measure(size);
                        objectToPrint.Arrange(new Rect(size));

                        // Convert the UI control into a bitmap at 300 dpi
                        double             dpiX = 300;
                        double             dpiY = 300;
                        RenderTargetBitmap bmp  = new RenderTargetBitmap(Convert.ToInt32(
                                                                             capabilities.PageImageableArea.ExtentWidth * dpiScale),
                                                                         Convert.ToInt32(objectToPrint.ActualHeight * dpiScale),
                                                                         dpiX, dpiY, PixelFormats.Pbgra32);
                        bmp.Render(objectToPrint);

                        // Convert the RenderTargetBitmap into a bitmap we can more readily use
                        PngBitmapEncoder png = new PngBitmapEncoder();
                        png.Frames.Add(BitmapFrame.Create(bmp));
                        Bitmap bmp2;
                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            png.Save(memoryStream);
                            bmp2 = new System.Drawing.Bitmap(memoryStream);
                        }
                        document.DocumentPaginator.PageSize =
                            new System.Windows.Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight);

                        // break the bitmap down into pages
                        int pageBreak         = 0;
                        int previousPageBreak = 0;
                        int pageHeight        =
                            Convert.ToInt32(capabilities.PageImageableArea.ExtentHeight * dpiScale);
                        while (pageBreak < bmp2.Height - pageHeight)
                        {
                            pageBreak += pageHeight;  // Where we thing the end of the page should be

                            // Keep moving up a row until we find a good place to break the page
                            while (!IsRowGoodBreakingPoint(bmp2, pageBreak))
                            {
                                pageBreak--;
                            }

                            PageContent pageContent = generatePageContent(bmp2, previousPageBreak,
                                                                          pageBreak, document.DocumentPaginator.PageSize.Width,
                                                                          document.DocumentPaginator.PageSize.Height, capabilities);
                            document.Pages.Add(pageContent);
                            previousPageBreak = pageBreak;
                        }

                        // Last Page
                        PageContent lastPageContent = generatePageContent(bmp2, previousPageBreak,
                                                                          bmp2.Height, document.DocumentPaginator.PageSize.Width,
                                                                          document.DocumentPaginator.PageSize.Height, capabilities);
                        document.Pages.Add(lastPageContent);
                    }
                    finally
                    {
                        // Scale UI control back to the original so we don't effect what is on the screen
                        objectToPrint.Width = double.NaN;
                        objectToPrint.UpdateLayout();
                        objectToPrint.LayoutTransform = new ScaleTransform(1, 1);
                        System.Windows.Size size = new System.Windows.Size(capabilities.PageImageableArea.ExtentWidth,
                                                                           capabilities.PageImageableArea.ExtentHeight);
                        objectToPrint.Measure(size);
                        objectToPrint.Arrange(new Rect(new System.Windows.Point(capabilities.PageImageableArea.OriginWidth,
                                                                                capabilities.PageImageableArea.OriginHeight), size));
                        Mouse.OverrideCursor = null;
                    }
                    printDialog.PrintDocument(document.DocumentPaginator, "Print Document Name");
                }
            }
        }