Exemplo n.º 1
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            WordDocument document = new WordDocument();

#if STORE_SB
            Stream inputStream = inputStream = execAssm.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Assets.Template_Report.doc");
            //Open Template document
            await document.OpenAsync(inputStream, FormatType.Word2013);

            inputStream.Dispose();
#else
            if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
            {
                Stream inputStream = inputStream = execAssm.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Assets.Template_Letter_WP.doc");

                await document.OpenAsync(inputStream, FormatType.Doc);

                inputStream.Dispose();
            }
            else
            {
                Stream inputStream;
                if (rdReport.IsChecked == true)
                {
                    inputStream = execAssm.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Assets.Template_Report.doc");
                }

                else
                {
                    inputStream = execAssm.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Assets.Template_Letter.doc");
                }

                //Open Template document
                await document.OpenAsync(inputStream, FormatType.Word2013);

                inputStream.Dispose();
            }
#endif
            #region Execute Mail merge
            if (rdExplicit.IsChecked.Value)
            {
                MailMergeDataSet       dataSet  = GetMailMergeDataSet();
                List <DictionaryEntry> commands = new List <DictionaryEntry>();
                //DictionaryEntry contain "Source table" (KEY) and "Command" (VALUE)
                DictionaryEntry entry = new DictionaryEntry("Employees", string.Empty);
                commands.Add(entry);

                // To retrive customer details
                entry = new DictionaryEntry("Customers", "EmployeeID = %Employees.EmployeeID%");
                commands.Add(entry);

                // To retrieve order details
                entry = new DictionaryEntry("Orders", "CustomerID = %Customers.CustomerID%");
                commands.Add(entry);

                //Executes nested Mail merge using explicit relational data.
                document.MailMerge.ExecuteNestedGroup(dataSet, commands);
            }
            else
            {
                MailMergeDataTable dataTable = GetMailMergeDataTable();
                //Executes nested Mail merge using implicit relational data.
                document.MailMerge.ExecuteNestedGroup(dataTable);
            }
            #endregion
            Save(rdDoc.IsChecked == true, document);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Gets the mail merge data set.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="System.Exception">reader</exception>
        /// <exception cref="XmlException">Unexpected xml tag  + reader.LocalName</exception>
        private MailMergeDataSet GetMailMergeDataSet()
        {
            List <EmployeeDetails> employees = new List <EmployeeDetails>();
            List <CustomerDetails> customers = new List <CustomerDetails>();
            List <OrderDetails>    orders    = new List <OrderDetails>();

            Stream stream = execAssm.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Assets.Employees.xml");

            XmlReader reader = XmlReader.Create(stream);

            if (reader == null)
            {
                throw new Exception("reader");
            }

            while (reader.NodeType != XmlNodeType.Element)
            {
                reader.Read();
            }

            if (reader.LocalName != "EmployeesList")
            {
                throw new XmlException("Unexpected xml tag " + reader.LocalName);
            }

            reader.Read();

            while (reader.NodeType == XmlNodeType.Whitespace)
            {
                reader.Read();
            }

            while (reader.LocalName != "EmployeesList")
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.LocalName)
                    {
                    case "Employees":
                        employees.Add(GetEmployee(reader, customers, orders));
                        break;
                    }
                }
                else
                {
                    reader.Read();
                    if ((reader.LocalName == "EmployeesList") && reader.NodeType == XmlNodeType.EndElement)
                    {
                        break;
                    }
                }
            }
            reader.Dispose();
            stream.Dispose();
            MailMergeDataSet dataSet = new MailMergeDataSet();

            dataSet.Add(new MailMergeDataTable("Employees", employees));
            dataSet.Add(new MailMergeDataTable("Customers", customers));
            dataSet.Add(new MailMergeDataTable("Orders", orders));
            return(dataSet);
        }
        // GET: /<controller>/
        public IActionResult NestedMailMerge(string Group1, string Group2, string Group3, string Button)
        {
            if (Group1 == null || Group2 == null || Group3 == null)
            {
                return(View());
            }
            string basePath = _hostingEnvironment.WebRootPath;

            string dataPath = string.Empty;

            if (Group2 == "Report")
            {
                dataPath = basePath + @"/DocIO/Template_Report.doc";
            }
            else
            {
                dataPath = basePath + @"/DocIO/Template_Letter.doc";
            }

            string     contenttype1 = "application/msword";
            string     dataPath1    = basePath + @"/DocIO/Template_Report.doc";
            string     dataPath2    = basePath + @"/DocIO/Template_Letter.doc";
            FileStream fileStream1  = new FileStream(dataPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            FileStream fileStream2  = new FileStream(dataPath2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            if (Button == "View Template")
            {
                if (Group2 == "Report")
                {
                    return(File(fileStream1, contenttype1, "Template_Report.doc"));
                }
                else
                {
                    return(File(fileStream2, contenttype1, "Template_Letter.doc"));
                }
            }
            fileStream1.Dispose();
            fileStream1 = null;
            fileStream2.Dispose();
            fileStream2 = null;
            // Creating a new document.
            WordDocument document = new WordDocument();
            // Load template
            FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            document.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;

            #region Execute Mail merge
            if (Group3 == "Explicit")
            {
                MailMergeDataSet       dataSet  = GetMailMergeDataSet(basePath);
                List <DictionaryEntry> commands = new List <DictionaryEntry>();
                //DictionaryEntry contain "Source table" (KEY) and "Command" (VALUE)
                DictionaryEntry entry = new DictionaryEntry("Employees", string.Empty);
                commands.Add(entry);

                // To retrive customer details
                entry = new DictionaryEntry("Customers", "EmployeeID = %Employees.EmployeeID%");
                commands.Add(entry);

                // To retrieve order details
                entry = new DictionaryEntry("Orders", "CustomerID = %Customers.CustomerID%");
                commands.Add(entry);

                //Executes nested Mail merge using explicit relational data.
                document.MailMerge.ExecuteNestedGroup(dataSet, commands);
            }
            else
            {
                MailMergeDataTable dataTable = GetMailMergeDataTable(basePath);
                //Executes nested Mail merge using implicit relational data.
                document.MailMerge.ExecuteNestedGroup(dataTable);
            }
            #endregion
            FormatType type        = FormatType.Docx;
            string     filename    = "Sample.docx";
            string     contenttype = "application/vnd.ms-word.document.12";
            #region Document SaveOption
            //Save as .doc format
            if (Group1 == "WordDoc")
            {
                type        = FormatType.Doc;
                filename    = "Sample.doc";
                contenttype = "application/msword";
            }
            //Save as .xml format
            else if (Group1 == "WordML")
            {
                type        = FormatType.WordML;
                filename    = "Sample.xml";
                contenttype = "application/msword";
            }
            #endregion Document SaveOption
            MemoryStream ms = new MemoryStream();
            document.Save(ms, type);
            document.Close();
            ms.Position = 0;
            return(File(ms, contenttype, filename));
        }
        /// <summary>
        /// Gets the mail merge data set.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="System.Exception">reader</exception>
        /// <exception cref="XmlException">Unexpected xml tag  + reader.LocalName</exception>
        private MailMergeDataSet GetMailMergeDataSet(string basePath)
        {
            List <EmployeeDetails> employees = new List <EmployeeDetails>();
            List <CustomerDetails> customers = new List <CustomerDetails>();
            List <OrderDetails>    orders    = new List <OrderDetails>();

            FileStream stream = new FileStream(basePath + @"/DocIO/Employees.xml", FileMode.OpenOrCreate);

            XmlReader reader = XmlReader.Create(stream);

            if (reader == null)
            {
                throw new Exception("reader");
            }

            while (reader.NodeType != XmlNodeType.Element)
            {
                reader.Read();
            }

            if (reader.LocalName != "EmployeesList")
            {
                throw new XmlException("Unexpected xml tag " + reader.LocalName);
            }

            reader.Read();

            while (reader.NodeType == XmlNodeType.Whitespace)
            {
                reader.Read();
            }

            while (reader.LocalName != "EmployeesList")
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.LocalName)
                    {
                    case "Employees":
                        employees.Add(GetEmployee(reader, customers, orders));
                        break;
                    }
                }
                else
                {
                    reader.Read();
                    if ((reader.LocalName == "EmployeesList") && reader.NodeType == XmlNodeType.EndElement)
                    {
                        break;
                    }
                }
            }
            reader.Dispose();
            stream.Dispose();
            MailMergeDataSet dataSet = new MailMergeDataSet();

            dataSet.Add(new MailMergeDataTable("Employees", employees));
            dataSet.Add(new MailMergeDataTable("Customers", customers));
            dataSet.Add(new MailMergeDataTable("Orders", orders));
            return(dataSet);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Update fields in the Word document
        /// </summary>
        /// <returns>Return the created Word document as stream</returns>
        public MemoryStream NestedMailMerge(string Group1, string Group2, string documentType, string button)
        {
            //if (Group2 == null || Group3 == null)
            //    return View();
            string basePath = @"wwwroot/";
            string dataPath = null;

            if (Group1 == "Report")
            {
                dataPath = basePath + @"data/docio/template-report.doc";
            }
            else
            {
                dataPath = basePath + @"data/docio/template-letter.doc";
            }
            FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            if (button == "View Template")
            {
                MemoryStream ms = new MemoryStream();
                fileStream.Position = 0;
                fileStream.CopyTo(ms);
                fileStream.Close();
                return(ms);
            }

            // Creating a new document.
            WordDocument document = new WordDocument();

            // Load template
            fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            document.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;

            #region Execute Mail merge
            if (Group2 == "Explicit")
            {
                MailMergeDataSet       dataSet  = GetMailMergeDataSet(basePath);
                List <DictionaryEntry> commands = new List <DictionaryEntry>();
                //DictionaryEntry contain "Source table" (KEY) and "Command" (VALUE)
                DictionaryEntry entry = new DictionaryEntry("Employees", string.Empty);
                commands.Add(entry);

                // To retrive customer details
                entry = new DictionaryEntry("Customers", "EmployeeID = %Employees.EmployeeID%");
                commands.Add(entry);

                // To retrieve order details
                entry = new DictionaryEntry("Orders", "CustomerID = %Customers.CustomerID%");
                commands.Add(entry);

                //Executes nested Mail merge using explicit relational data.
                document.MailMerge.ExecuteNestedGroup(dataSet, commands);
            }
            else
            {
                MailMergeDataTable dataTable = GetMailMergeDataTable(basePath);
                //Executes nested Mail merge using implicit relational data.
                document.MailMerge.ExecuteNestedGroup(dataTable);
            }
            #endregion
            #region Document SaveOption
            FormatType formatType = FormatType.Docx;
            //Save as .doc format
            if (documentType == "WordDoc")
            {
                formatType = FormatType.Doc;
            }
            //Save as .xml format
            else if (documentType == "WordML")
            {
                formatType = FormatType.WordML;
            }
            //Save the document as a stream and retrun the stream
            using (MemoryStream stream = new MemoryStream())
            {
                //Save the created Word document to MemoryStream
                document.Save(stream, formatType);
                document.Close();
                stream.Position = 0;
                return(stream);
            }
            #endregion Document SaveOption
        }
Exemplo n.º 6
0
        /// <summary>
        /// Performs Mail merge for nested groups in Word document.
        /// </summary>
        private void Button_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
        {
            //Gets the input Word document.
            string basePath = "syncfusion.dociodemos.winui.Assets.DocIO.";
            string dataPath = basePath + @"TemplateLetter.docx";

            //Creates a new Word document instance.
            using WordDocument document = new();
            Stream fileStream = assembly.GetManifestResourceStream(dataPath);

            //Opens an existing Word document.
            document.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();

            //Inserts page break at last paragraph, to populate each employee details in new page.
            Break pageBreak = new(document, BreakType.PageBreak);

            document.LastParagraph.ChildEntities.Insert(0, pageBreak);

            #region Execute Mail merge
            MailMergeDataSet       dataSet  = GetMailMergeDataSet(basePath);
            List <DictionaryEntry> commands = new();
            //DictionaryEntry contain "Source table" (KEY) and "Command" (VALUE)
            DictionaryEntry entry = new("Employees", string.Empty);
            commands.Add(entry);

            //Retrives customer details.
            entry = new DictionaryEntry("Customers", "EmployeeID = %Employees.EmployeeID%");
            commands.Add(entry);

            //Retrives order details.
            entry = new DictionaryEntry("Orders", "CustomerID = %Customers.CustomerID%");
            commands.Add(entry);

            //Executes nested Mail merge using explicit relational data.
            document.MailMerge.ExecuteNestedGroup(dataSet, commands);
            #endregion

            //Clears the items (Page break) in last paragraph to remove empty page after execution.
            document.LastParagraph.ChildEntities.Clear();

            #region Document SaveOption
            using MemoryStream ms = new();
            string filename = string.Empty;
            //Saves as .docx format.
            if (worddocx.IsChecked == true)
            {
                filename = "Orders Report.docx";
                //Saves the Word document to the memory stream.
                document.Save(ms, FormatType.Docx);
            }
            //Saves as .doc format.
            else if (worddoc.IsChecked == true)
            {
                filename = "Orders Report.doc";
                //Saves the Word document to the memory stream.
                document.Save(ms, FormatType.Doc);
            }
            //Saves as .pdf format.
            else if (pdf.IsChecked == true)
            {
                filename = "Orders Report.pdf";
                //Creates a new DocIORenderer instance.
                using DocIORenderer renderer = new();
                //Converts Word document into PDF.
                using PdfDocument pdfDoc = renderer.ConvertToPDF(document);
                //Saves the PDF document to the memory stream.
                pdfDoc.Save(ms);
            }
            ms.Position = 0;
            //Saves the memory stream as file.
            SaveHelper.SaveAndLaunch(filename, ms);
            #endregion Document SaveOption
        }
        /// <summary>
        /// generate word document as an asynchronous operation.
        /// </summary>
        /// <param name="documentRequest">The document request.</param>
        /// <param name="exportAsPdf">if set to <c>true</c> [export as PDF].</param>
        /// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>Task.</returns>
        public Task <Stream> GenerateDocumentAsync <TDocument, TDetails>(DocumentRequest <TDocument, TDetails> documentRequest, bool exportAsPdf = false, CancellationToken cancellationToken = default)
        {
            Argument.IsNotNull(documentRequest);

            Stream       result   = new MemoryStream();
            WordDocument document = null;

            try
            {
                if (documentRequest.Template is byte[] templateBytes && templateBytes.ToMemoryStream() is MemoryStream stream)
                {
                    using (document = new WordDocument(stream, Syncfusion.DocIO.FormatType.Docx))
                    {
                        if (documentRequest.Stationary is byte[] imageArray && imageArray.Length > 0)
                        {
                            //Adds picture watermark to the document.
                            var section   = document.Sections[0];
                            var paragraph = section.HeadersFooters.Header.AddParagraph();
                            var picture   = paragraph.AppendPicture(imageArray);
                            picture.TextWrappingStyle = TextWrappingStyle.Behind;
                            picture.Width             = section.PageSetup.PageSize.Width;
                            picture.Height            = section.PageSetup.PageSize.Height;
                            picture.HorizontalOrigin  = HorizontalOrigin.Page;
                            picture.VerticalOrigin    = VerticalOrigin.Page;
                        }

                        var dataSet  = new MailMergeDataSet();
                        var commands = new List <DictionaryEntry>();

                        var documentDataTable = new MailMergeDataTable(nameof(documentRequest.Document), documentRequest.Document);
                        dataSet.Add(documentDataTable);
                        commands.Add(new DictionaryEntry(documentDataTable.GroupName, string.Empty));

                        var detailsDataTable = new MailMergeDataTable(nameof(documentRequest.DocumentDetails), documentRequest.DocumentDetails);
                        dataSet.Add(detailsDataTable);
                        commands.Add(new DictionaryEntry(detailsDataTable.GroupName, string.Empty));

                        var alternativesDataTable = new MailMergeDataTable(nameof(documentRequest.DocumentAlternatives), documentRequest.DocumentAlternatives);
                        dataSet.Add(alternativesDataTable);
                        commands.Add(new DictionaryEntry(alternativesDataTable.GroupName, string.Empty));

                        document.MailMerge.MergeImageField      += MergeImageField;
                        document.MailMerge.RemoveEmptyParagraphs = true;
                        document.MailMerge.ExecuteNestedGroup(dataSet, commands);

                        foreach (var paragraph in mailMergeImgaeParagraph.EnsureNotNull())
                        {
                            if (paragraph.ChildEntities is not null)
                            {
                                foreach (ParagraphItem paraItem in paragraph.ChildEntities)
                                {
                                    if (paraItem is WPicture picture && paragraph.OwnerTextBody is WTableCell cell)
                                    {
                                        //Get the cell width and reduce the 5 points from total width
                                        //to avoid the image overlapping on the cell borders.
                                        var newWidth = cell.Width - 10;

                                        //Check whether the image width exceeds the cell width.
                                        if (picture.Width > newWidth)
                                        {
                                            var originalWidth  = picture.Width;
                                            var originalHeight = picture.Height;

                                            var nPercentH = newWidth / originalWidth;

                                            //Scaling the image to the cell width.
                                            picture.Height = Math.Max((int)Math.Round(originalHeight * nPercentH), 1) - 10; // Just in case;
                                            picture.Width  = newWidth;
                                        }

                                        break;
                                    }
                                }
                            }
                        }

                        if (exportAsPdf)
                        {
                            using (var iORenderer = new DocIORenderer())
                            {
                                iORenderer.Settings.ChartRenderingOptions.ImageFormat = Syncfusion.OfficeChart.ExportImageFormat.Jpeg;
                                iORenderer.Settings.EmbedFonts = true;

                                var pdfDocument = iORenderer.ConvertToPDF(document);
                                pdfDocument.Save(result);
                                pdfDocument.Close();
                            };
                        }
                        else
                        {
                            document.Save(result, Syncfusion.DocIO.FormatType.Docx);
                        }
                    }
                }
            }
            finally
            {
                result.Position = 0;

                if (document is not null)
                {
                    document.Close();
                }
            }

            return(Task.FromResult(result));
        }