Пример #1
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public string FunctionHandler(string input, ILambdaContext context)
        {
            string filePath = Path.GetFullPath(@"Data/Adventure.docx");

            //Load the file from the disk
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

            WordDocument document = new WordDocument(fileStream, FormatType.Docx);

            //Hooks the font substitution event
            document.FontSettings.SubstituteFont += FontSettings_SubstituteFont;

            DocIORenderer render = new DocIORenderer();

            PdfDocument pdf = render.ConvertToPDF(document);

            //Unhooks the font substitution event after converting to PDF
            document.FontSettings.SubstituteFont -= FontSettings_SubstituteFont;

            //Save the document into stream
            MemoryStream stream = new MemoryStream();

            //Save the PDF document
            pdf.Save(stream);
            document.Close();
            render.Dispose();
            return(Convert.ToBase64String(stream.ToArray()));
        }
        public async Task <byte[]> Render(PrintFormModel printFormModel, TemplateFile template, bool isNeedConvertToPdf = false)
        {
            await using (var stream = new MemoryStream(template.File.Content))
            {
                var wordDocument = new WordDocument(stream, FormatType.Docx);

                foreach (var(key, value) in printFormModel.Schema)
                {
                    wordDocument.ReplaceSingleLine(key, value, false, false);
                }

                await using (var outputStream = new MemoryStream())
                {
                    if (isNeedConvertToPdf)
                    {
                        var render = new DocIORenderer();
                        render.Settings.ChartRenderingOptions.ImageFormat = ExportImageFormat.Jpeg;
                        var pdfDocument = render.ConvertToPDF(wordDocument);
                        pdfDocument.Save(outputStream);
                        printFormModel.Template.FullName = FileHelper.ChangeFileExtension(printFormModel.Template.FullName);
                    }
                    else
                    {
                        wordDocument.Save(outputStream, FormatType.Docx);
                    }

                    return(outputStream.ToArray());
                }
            }
        }
        public IActionResult WordToPDF(string button)
        {
            if (button == null)
            {
                return(View());
            }
            Stream stream = GetWordDocument();

            if (stream != null)
            {
                try
                {
                    string output = (Request.Form.Files != null && Request.Form.Files.Count != 0) ? Path.GetFileNameWithoutExtension(Request.Form.Files[0].FileName) : "WordtoPDF";
                    // Loads document from stream.
                    WordDocument document = new WordDocument(stream, FormatType.Automatic);
                    // Creates a new instance of DocIORenderer class.
                    DocIORenderer render = new DocIORenderer();
                    // Converts Word document into PDF document.
                    PdfDocument  pdf          = render.ConvertToPDF(document);
                    MemoryStream memoryStream = new MemoryStream();
                    // Save the PDF document.
                    pdf.Save(memoryStream);
                    render.Dispose();
                    pdf.Close();
                    document.Close();
                    memoryStream.Position = 0;
                    return(File(memoryStream, "application/pdf", output + ".pdf"));
                }
                catch
                {
                    ViewBag.Message = string.Format("The input document could not be processed completely, Could you please email the document to [email protected] for troubleshooting.");
                }
            }
            return(View());
        }
Пример #4
0
        /// <summary>
        /// Generate a letter using Mail merge functionality of Essential DocIO
        /// </summary>
        /// <returns>Return the created Word document as stream</returns>
        public MemoryStream WordToPDF(string button, bool preserveStructureTags, bool preserveFormFields, bool preserveWordHeadingsToPDFBookmarks, bool showRevisions, bool showComments)
        {
            string     basePath   = @"wwwroot/";
            string     dataPath   = basePath + @"data/docio/doc-to-pdf.docx";
            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.Dispose();
                return(ms);
            }
            fileStream = null;
            // Load the template.
            FileStream   fileStreamPath = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            WordDocument document       = new WordDocument(fileStreamPath, FormatType.Doc);

            fileStreamPath.Dispose();
            fileStreamPath = null;
            DocIORenderer render = new DocIORenderer();

            if (preserveStructureTags)
            {
                render.Settings.AutoTag = true;
            }
            if (preserveFormFields)
            {
                render.Settings.PreserveFormFields = true;
            }
            render.Settings.ExportBookmarks = preserveWordHeadingsToPDFBookmarks ? Syncfusion.DocIO.ExportBookmarkType.Headings : Syncfusion.DocIO.ExportBookmarkType.Bookmarks;
            if (showRevisions)
            {
                //Enables to show the revision marks in the generated PDF for tracked changes or revisions in the Word document.
                document.RevisionOptions.ShowMarkup = RevisionType.Deletions | RevisionType.Formatting | RevisionType.Insertions;
            }
            if (showComments)
            {
                //Sets ShowInBalloons to render a document comments in converted PDF document.
                document.RevisionOptions.CommentDisplayMode = CommentDisplayMode.ShowInBalloons;
                //Sets the color to be used for Comment Balloon
                document.RevisionOptions.CommentColor = RevisionColor.Blue;
            }
            // Converts Word document into PDF document.
            PdfDocument pdf = render.ConvertToPDF(document);

            //Save the document as a stream and retrun the stream
            using (MemoryStream stream = new MemoryStream())
            {
                //Save the created PDF document to MemoryStream
                pdf.Save(stream);
                render.Dispose();
                pdf.Close();
                document.Close();
                stream.Position = 0;
                return(stream);
            }
        }
Пример #5
0
        /// <summary>
        /// <para>Render PDF</para>
        /// </summary>
        protected void CreatePDF()
        {
            // Creates a new instance of DocIORenderer class.
            DocIORenderer render = new DocIORenderer();

            // Converts Word document into PDF document.
            PDFGenerated = render.ConvertToPDF(DocumentTemplate);
            render.Dispose();
            DocumentTemplate.Dispose();
        }
Пример #6
0
        public IActionResult WordToPDF(string button, string renderingMode1, string renderingMode2, string renderingMode3, string renderingMode4)
        {
            if (button == null)
            {
                return(View());
            }
            Stream stream = GetWordDocument();

            if (stream != null)
            {
                try
                {
                    string output = (Request.Form.Files != null && Request.Form.Files.Count != 0) ? Path.GetFileNameWithoutExtension(Request.Form.Files[0].FileName) : "WordtoPDF";
                    // Loads document from stream.
                    WordDocument document = new WordDocument(stream, FormatType.Automatic);
                    stream.Dispose();
                    stream = null;
                    // Creates a new instance of DocIORenderer class.
                    DocIORenderer render = new DocIORenderer();
                    if (renderingMode1 == "PreserveStructureTags")
                    {
                        render.Settings.AutoTag = true;
                    }
                    if (renderingMode2 == "PreserveFormFields")
                    {
                        render.Settings.PreserveFormFields = true;
                    }
                    render.Settings.ExportBookmarks = renderingMode3 == "PreserveWordHeadingsToPDFBookmarks"
                                                           ? Syncfusion.DocIO.ExportBookmarkType.Headings
                                                         : Syncfusion.DocIO.ExportBookmarkType.Bookmarks;
                    if (renderingMode4 == "ShowRevisions")
                    {
                        //Enables to show the revision marks in the generated PDF for tracked changes or revisions in the Word document.
                        document.RevisionOptions.ShowMarkup = RevisionType.Deletions | RevisionType.Formatting | RevisionType.Insertions;
                    }
                    // Converts Word document into PDF document.
                    PdfDocument  pdf          = render.ConvertToPDF(document);
                    MemoryStream memoryStream = new MemoryStream();
                    // Save the PDF document.
                    pdf.Save(memoryStream);
                    render.Dispose();
                    pdf.Close();
                    document.Close();
                    memoryStream.Position = 0;
                    return(File(memoryStream, "application/pdf", output + ".pdf"));
                }
                catch
                {
                    ViewBag.Message = string.Format("The input document could not be processed completely, Could you please email the document to [email protected] for troubleshooting.");
                }
            }
            return(View());
        }
Пример #7
0
        public IActionResult WordToPDF(string button)
        {
            if (button == null)
            {
                return(View());
            }

            if (Request.Form.Files != null && Request.Form.Files.Count != 0)
            {
                // Gets the extension from file.
                string extension = Path.GetExtension(Request.Form.Files[0].FileName).ToLower();
                string output    = Path.GetFileNameWithoutExtension(Request.Form.Files[0].FileName);

                // Compares extension with supported extensions.
                if (extension == ".doc" || extension == ".docx" || extension == ".dot" || extension == ".dotx" || extension == ".dotm" || extension == ".docm" ||
                    extension == ".xml" || extension == ".rtf")
                {
                    Stream stream = new FileStream(Path.GetTempFileName(), FileMode.Create);
                    Request.Form.Files[0].CopyToAsync(stream);
                    try
                    {
                        // Loads document from stream.
                        WordDocument document = new WordDocument(stream, FormatType.Automatic);
                        // Creates a new instance of DocIORenderer class.
                        DocIORenderer render = new DocIORenderer();
                        // Converts Word document into PDF document.
                        PdfDocument  pdf          = render.ConvertToPDF(document);
                        MemoryStream memoryStream = new MemoryStream();
                        // Save the PDF document.
                        pdf.Save(memoryStream);
                        render.Dispose();
                        pdf.Close();
                        document.Close();
                        memoryStream.Position = 0;
                        return(File(memoryStream, "application/pdf", output + ".pdf"));
                    }
                    catch (Exception ex)
                    {
                        ViewBag.Message = string.Format("The input document could not be processed completely, Could you please email the document to [email protected] for troubleshooting.");
                    }
                }
                else
                {
                    ViewBag.Message = string.Format("Please choose Word format document to convert to PDF");
                }
            }
            else
            {
                ViewBag.Message = string.Format("Browse a Word document and then click the button to convert as a PDF document");
            }
            return(View());
        }
Пример #8
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            Assembly assembly = typeof(WordToPDF).GetTypeInfo().Assembly;
            // Creating a new document.
            WordDocument document = new WordDocument();

#if COMMONSB
            string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates.";
#else
            string rootPath = "SampleBrowser.DocIO.Samples.Templates.";
#endif
            Stream inputStream = assembly.GetManifestResourceStream(rootPath + "WordtoPDF.docx");

            // Loads the stream into Word Document.
            WordDocument wordDocument = new WordDocument(inputStream, Syncfusion.DocIO.FormatType.Automatic);

            //Sets ShowInBalloons to render a document comments in converted PDF document.
            wordDocument.RevisionOptions.CommentDisplayMode = CommentDisplayMode.ShowInBalloons;
            //Sets the color to be used for Comment Balloon
            wordDocument.RevisionOptions.CommentColor = RevisionColor.Blue;

            //Instantiation of DocIORenderer for Word to PDF conversion
            DocIORenderer render = new DocIORenderer();

            //Sets Chart rendering Options.
            render.Settings.ChartRenderingOptions.ImageFormat = ExportImageFormat.Jpeg;

            //Converts Word document into PDF document
            PdfDocument pdfDocument = render.ConvertToPDF(wordDocument);

            //Releases all resources used by the Word document and DocIO Renderer objects
            render.Dispose();

            wordDocument.Dispose();

            //Saves the PDF file
            MemoryStream outputStream = new MemoryStream();
            pdfDocument.Save(outputStream);

            //Closes the instance of PDF document object
            pdfDocument.Close();

            if (Device.RuntimePlatform == Device.UWP)
            {
                DependencyService.Get <ISaveWindowsPhone>()
                .Save("WordtoPDF.pdf", "application/pdf", outputStream);
            }
            else
            {
                DependencyService.Get <ISave>().Save("WordtoPDF.pdf", "application/pdf", outputStream);
            }
        }
Пример #9
0
        public async Task SfPdfSave(StorageFile docfile)
        {
            ChangeLoading(true);
            MainEdit.RequestedTheme = ElementTheme.Light;

            StorageFile cachefile = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync("sfcache.rtf", CreationCollisionOption.ReplaceExisting);

            CachedFileManager.DeferUpdates(cachefile);
            IRandomAccessStream randAccStream = await cachefile.OpenAsync(FileAccessMode.ReadWrite);

            MainEdit.Document.SaveToStream(TextGetOptions.FormatRtf, randAccStream);
            Debug.WriteLine("File saved");
            randAccStream.Dispose();

            Stream stream = await cachefile.OpenStreamForReadAsync();

            WordDocument document = new WordDocument(stream, FormatType.Rtf);
            StorageFile  cachedoc = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync("sfpdfcache.docx", CreationCollisionOption.ReplaceExisting);

            Stream savestream = await cachedoc.OpenStreamForWriteAsync();

            document.Save(savestream, FormatType.Docx);
            stream.Dispose();
            savestream.Dispose();

            DocIORenderer docIORenderer = new DocIORenderer();
            PdfDocument   pDFDocument   = docIORenderer.ConvertToPDF(await cachedoc.OpenStreamForReadAsync());

            pDFDocument.PageSettings.Size = PdfPageSize.A4;
            pDFDocument.PageSettings.SetMargins(250f);
            Stream savepdfstream = await docfile.OpenStreamForWriteAsync();

            pDFDocument.Save(savepdfstream);
            docIORenderer.Dispose();
            savepdfstream.Dispose();
            pDFDocument.Close();


            if (Settings.Default.ThemeDefault == true)
            {
                MainEdit.RequestedTheme = ElementTheme.Default;
            }
            if (Settings.Default.ThemeDark == true)
            {
                MainEdit.RequestedTheme = ElementTheme.Dark;
            }
            if (Settings.Default.ThemeLight == true)
            {
                MainEdit.RequestedTheme = ElementTheme.Light;
            }
            ChangeLoading(false);
        }
        public static async Task Run(
            [EventGridTrigger] EventGridEvent eventGridEvent,
            [Blob("{data.url}", FileAccess.Read)] Stream input,
            ILogger log)
        {
            try
            {
                if (input != null)
                {
                    var createdEvent = ((JObject)eventGridEvent.Data).ToObject <StorageBlobCreatedEventData>();

                    if (ShouldConvert(createdEvent.Url))
                    {
                        var storageAccount = CloudStorageAccount.Parse(BLOB_STORAGE_CONNECTION_STRING);
                        var blobClient     = storageAccount.CreateCloudBlobClient();

                        var targetContainer = blobClient.GetContainerReference(GetTargetContainerNameFromUrl(createdEvent.Url));
                        var targetBlobName  = GetTargetBlobNameFromUrl(createdEvent.Url);
                        var targetBlockBlob = targetContainer.GetBlockBlobReference(targetBlobName);

                        using (var output = new MemoryStream())
                            using (WordDocument wordDocument = new WordDocument(input, FormatType.Automatic))
                            {
                                //Creates an instance of DocToPDFConverter - responsible for Word to PDF conversion
                                DocIORenderer converter = new DocIORenderer();

                                //Converts Word document into PDF document
                                PdfDocument pdfDocument = converter.ConvertToPDF(wordDocument);

                                //Save the document into stream.
                                pdfDocument.Save(output);

                                //Closes the instance of PDF document object
                                pdfDocument.Close();

                                output.Position = 0;
                                await targetBlockBlob.UploadFromStreamAsync(output);
                            }
                    }
                    else
                    {
                        log.LogInformation($"Will NOT convert: {createdEvent.Url}");
                    }
                }
            }
            catch (Exception ex)
            {
                log.LogInformation(ex.Message);
                throw;
            }
        }
Пример #11
0
        public IActionResult CreateDocument()
        {
            //Opens the Word template document
            FileStream fileStreamPath = new FileStream(@"wwwroot/test_template.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            using (WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx))
            {
                //string[] fieldNames = { "ContactName", "CompanyName", "Address", "City", "Country", "Phone" };
                //string[] fieldValues = { "Nancy Davolio", "Syncfusion", "507 - 20th Ave. E.Apt. 2A", "Seattle, WA", "USA", "(206) 555-9857-x5467" };

                string[] fieldNames   = { "firstname", "lastname", "address", "age" };
                string[] fieldValues  = { "Dennis", "Huillca", "APV Agua Buena D-1 San Sebastian", "30" };
                string[] fieldValues2 = { "Roy", "Palacios", "Surco Lima", "31" };
                //Performs the mail merge
                document.MailMerge.Execute(fieldNames, fieldValues);
                document.MailMerge.Execute(fieldNames, fieldValues2);

                //Converts Word document to PDF
                DocIORenderer render      = new DocIORenderer();
                PdfDocument   pdfDocument = render.ConvertToPDF(document);
                render.Dispose();
                //adding the watermark
                PdfGraphics graphics = pdfDocument.Pages[0].Graphics;
                //set the font
                PdfFont          font  = new PdfStandardFont(PdfFontFamily.Helvetica, 60);
                PdfGraphicsState state = graphics.Save();
                graphics.SetTransparency(0.15f);
                graphics.RotateTransform(-30);
                graphics.DrawString("PREVIEW", font, PdfPens.Black, PdfBrushes.Red, new PointF(-40, 450));
                //Saves de pdf to disk
                FileStream outfs = new FileStream(@"wwwroot/foobar.pdf", FileMode.Create, FileAccess.Write);
                pdfDocument.Save(outfs);
                outfs.Close();
                pdfDocument.Close();

                //Saves the Word document to MemoryStream
                MemoryStream stream = new MemoryStream();
                document.Save(stream, FormatType.Docx);
                FileStream fs = new FileStream(@"wwwroot/foobar.docx", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                document.Save(fs, FormatType.Docx);
                fs.Close();
                //stream.WriteTo(fs);

                stream.Position = 0;
                //Download Word document in the browser
                return(File(stream, "application/msword", "Result.docx"));
            }
        }
Пример #12
0
 byte[] WordToPdf(Stream file)
 {
     _logger.LogDebug($"Start convert word file");
     byte[] buff;
     using (WordDocument document = new WordDocument(file, Syncfusion.DocIO.FormatType.Automatic))
         using (DocIORenderer render = new DocIORenderer())
             using (PdfDocument pdf = render.ConvertToPDF(document))
                 using (MemoryStream memoryStream = new MemoryStream())
                 {
                     pdf.Save(memoryStream);
                     memoryStream.Position = 0;
                     buff = memoryStream.ToArray();
                     _logger.LogDebug("FileInfoPDFService.WordToPdf....OK");
                     return(buff);
                 }
 }
Пример #13
0
        public async System.Threading.Tasks.Task <ActionResult> Index(string button)
        {
            if (button == null)
            {
                return(View());
            }
            ViewBag.Message = string.Empty;
            if (Request.Form.Files != null)
            {
                string extension = Path.GetExtension(Request.Form.Files[0].FileName).ToLower();

                if (extension == ".doc" || extension == ".docx" || extension == ".docm" ||
                    extension == ".xml")
                {
                    MemoryStream stream = new MemoryStream();
                    Request.Form.Files[0].CopyTo(stream);
                    try
                    {
                        WordDocument document = new WordDocument(stream, FormatType.Automatic);
                        stream.Dispose();
                        stream = null;

                        DocIORenderer render           = new DocIORenderer();
                        Syncfusion.Pdf.PdfDocument pdf = render.ConvertToPDF(document);

                        MemoryStream memoryStream = new MemoryStream();
                        pdf.Save(memoryStream);
                        render.Dispose();
                        document.Close();
                        pdf.Close();
                        memoryStream.Position = 0;

                        return(File(memoryStream, "application/pdf", "WordToPDF.pdf"));
                    }
                    catch (Exception ex)
                    {
                        ViewBag.Message = string.Format("The input document could not be processed completely.");
                    }
                }
                else
                {
                    ViewBag.Message = string.Format("Choose a Word format document to convert to PDF");
                }
            }

            return(View());
        }
Пример #14
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            string   resourcePath = "SampleBrowser.Samples.DocIO.Templates.WordtoPDF.docx";
            Assembly assembly     = Assembly.GetExecutingAssembly();
            Stream   fileStream   = assembly.GetManifestResourceStream(resourcePath);

            // Loads the stream into Word Document.
            WordDocument wordDocument = new WordDocument(fileStream, Syncfusion.DocIO.FormatType.Automatic);

            //Instantiation of DocIORenderer for Word to PDF conversion
            DocIORenderer render = new DocIORenderer();

            //Sets Chart rendering Options.
            render.Settings.ChartRenderingOptions.ImageFormat = ExportImageFormat.Jpeg;

            //Sets ShowInBalloons to render a document comments in converted PDF document.
            wordDocument.RevisionOptions.CommentDisplayMode = CommentDisplayMode.ShowInBalloons;
            //Sets the color to be used for Comment Balloon
            wordDocument.RevisionOptions.CommentColor = RevisionColor.Blue;

            //Converts Word document into PDF document
            PdfDocument pdfDocument = render.ConvertToPDF(wordDocument);

            //Releases all resources used by the Word document and DocIO Renderer objects
            render.Dispose();

            wordDocument.Dispose();

            MemoryStream pdfStream = new MemoryStream();

            //Save the converted PDF document into MemoryStream.
            pdfDocument.Save(pdfStream);
            pdfStream.Position = 0;

            //Close the PDF document.
            pdfDocument.Close(true);

            if (pdfStream != null)
            {
                SaveAndroid androidSave = new SaveAndroid();
                androidSave.Save("WordtoPDF.pdf", "application/pdf", pdfStream, m_context);
            }
        }
Пример #15
0
        /// <summary>
        /// 获得Word文件的预览图
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns>Word的预览</returns>
        public static async Task <IRandomAccessStream> GetWordPreviewAsync(string path)
        {
            StorageFile file = await StorageFile.GetFileFromPathAsync(path);

            var res = await file.OpenAsync(FileAccessMode.Read);

            WordDocument wordDocument = new WordDocument();

            wordDocument.Open(res.AsStream(), Syncfusion.DocIO.FormatType.Automatic);
            DocIORenderer render = new DocIORenderer();

            Syncfusion.Pdf.PdfDocument pdfDocument = render.ConvertToPDF(wordDocument);
            render.Dispose();
            wordDocument.Dispose();
            InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();

            pdfDocument.Save(ms.AsStream());
            currentFileType = PreviewModel.FileType.Office;
            return(await GetPDFPreviewFromStreamAsync(ms));
        }
Пример #16
0
        private async Task CreateCertificate(AppreciationCertificateModel model, string name)
        {
            // make a copy of the read-only template
            var templateFile =
                await StorageFile.GetFileFromApplicationUriAsync(
                    new Uri("ms-appx:///Assets/AppreciationCertTemplate.docx"));

            var copiedFile = await templateFile.CopyAsync(ApplicationData.Current.LocalFolder, "Certificates.docx", NameCollisionOption.ReplaceExisting);

            // load it into a new document
            var stream = await copiedFile.OpenReadAsync();

            var templateDoc = new WordDocument(stream.AsStream(), FormatType.Docx);

            // mailmerge
            string[] fieldNames  = { "Year", "Round", "Name", "Title", "Date" };
            string[] fieldValues = { model.Year, model.Round, model.Name, model.Title, model.Date };
            templateDoc.MailMerge.Execute(fieldNames, fieldValues);

            // save the new certificate
            MemoryStream templateStream = new MemoryStream();

            templateDoc.Save(templateStream, FormatType.Docx);
            await SaveFile(templateStream, name + ".docx");

            // convert to PDF
            DocIORenderer renderer = new DocIORenderer();
            PdfDocument   pdf      = renderer.ConvertToPDF(templateDoc);

            renderer.Dispose();
            templateDoc.Close();

            // save the PDF
            MemoryStream outputStream = new MemoryStream();

            pdf.Save(outputStream);
            await SaveFile(outputStream, name + ".pdf");

            pdf.Close();
        }
        public byte[] ConvertToPdf(WordDocument document)
        {
            DocIORenderer render      = new DocIORenderer();
            PdfDocument   pdfDocument = render.ConvertToPDF(document);

            render.Dispose();
            document.Dispose();

            byte[] byteArray;

            using (var stream = new MemoryStream())
            {
                pdfDocument.Save(stream);
                byteArray = stream.ToArray();
                stream.Dispose();
            }

            pdfDocument.Close();
            document.Close();

            return(byteArray);
        }
Пример #18
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            string   resourcePath = "SampleBrowser.Samples.DocIO.Templates.WordtoPDF.docx";
            Assembly assembly     = Assembly.GetExecutingAssembly();
            Stream   fileStream   = assembly.GetManifestResourceStream(resourcePath);
            // Loads the stream into Word Document.
            WordDocument wordDocument = new WordDocument(fileStream, Syncfusion.DocIO.FormatType.Automatic);

            //Instantiation of DocIORenderer for Word to PDF conversion
            DocIORenderer render = new DocIORenderer();

            //Sets Chart rendering Options.
            render.Settings.ChartRenderingOptions.ImageFormat = ExportImageFormat.Jpeg;

            //Converts Word document into PDF document
            PdfDocument pdfDocument = render.ConvertToPDF(wordDocument);

            //Releases all resources used by the Word document and DocIO Renderer objects
            render.Dispose();

            wordDocument.Dispose();

            MemoryStream stream = new MemoryStream();

            //Save the converted PDF document to MemoryStream.
            pdfDocument.Save(stream);
            stream.Position = 0;

            //Close the PDF document.
            pdfDocument.Close(true);

            if (stream != null)
            {
                SaveiOS iOSSave = new SaveiOS();
                iOSSave.Save("WordtoPDF.pdf", "application/pdf", stream);
            }
        }
Пример #19
0
        static void Main(string[] args)
        {
            //Open the file as Stream
            FileStream docStream = new FileStream(@"Adventure.docx", FileMode.Open, FileAccess.Read);
            //Loads file stream into Word document
            WordDocument wordDocument = new WordDocument(docStream, Syncfusion.DocIO.FormatType.Automatic);

            docStream.Dispose();
            //Instantiation of DocIORenderer for Word to PDF conversion
            DocIORenderer render = new DocIORenderer();
            //Converts Word document into PDF document
            PdfDocument pdfDocument = render.ConvertToPDF(wordDocument);

            //Releases all resources used by the Word document and DocIO Renderer objects
            render.Dispose();
            wordDocument.Dispose();
            //Saves the PDF file
            FileStream outputStream = new FileStream("Output.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);

            pdfDocument.Save(outputStream);
            //Closes the instance of PDF document object
            pdfDocument.Close();
            outputStream.Dispose();
        }
        private List <string> ConvertToImages(FileStream fs, List <string> returnStrings, Syncfusion.DocIO.FormatType type)
        {
            DocIO.WordDocument wd = new DocIO.WordDocument(fs, type);
            //Instantiation of DocIORenderer for Word to PDF conversion
            DocIORenderer render = new DocIORenderer();
            //Converts Word document into PDF document
            PdfDocument pdfDocument = render.ConvertToPDF(wd);

            //Releases all resources used by the Word document and DocIO Renderer objects
            render.Dispose();
            wd.Dispose();
            //Saves the PDF file
            MemoryStream outputStream = new MemoryStream();

            pdfDocument.Save(outputStream);
            outputStream.Position = 0;
            //Closes the instance of PDF document object
            pdfDocument.Close();

            PdfRenderer pdfExportImage = new PdfRenderer();

            //Loads the PDF document
            pdfExportImage.Load(outputStream);

            //Exports the PDF document pages into images
            Bitmap[] bitmapimage = pdfExportImage.ExportAsImage(0, pdfExportImage.PageCount - 1);
            foreach (Bitmap bitmap in bitmapimage)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    returnStrings.Add("data:image/png;base64," + Convert.ToBase64String(ms.ToArray()));
                }
            }
            return(returnStrings);
        }
Пример #21
0
        public static void ConvertDocToImage(string startupPath, string fileName)
        {
            string inputFile = Path.Combine(Directory.GetCurrentDirectory(), startupPath, fileName);

            FileStream fileStream = new FileStream(inputFile, FileMode.Open);
            //Loads file stream into Word document
            WordDocument document = new WordDocument(fileStream, FormatType.Docx);

            fileStream.Dispose();
            //Instantiation of DocIORenderer for Word to PDF conversion
            DocIORenderer render = new DocIORenderer();
            //Converts Word document into PDF document
            PdfDocument pdfDocument = render.ConvertToPDF(document);

            //Releases all resources used by the Word document and DocIO Renderer objects
            render.Dispose();
            document.Dispose();
            //Saves the PDF file
            MemoryStream outputStream = new MemoryStream();

            pdfDocument.Save(outputStream);
            outputStream.Position = 0;
            //Closes the instance of PDF document object
            pdfDocument.Close();

            PdfRenderer pdfExportImage = new PdfRenderer();

            //Loads the PDF document
            pdfExportImage.Load(outputStream, new Dictionary <string, string>());
            //Exports the PDF document pages into images
            Bitmap[] bitmapimage = pdfExportImage.ExportAsImage(0, pdfExportImage.PageCount - 1);
            for (int i = 0; i < pdfExportImage.PageCount; i++)
            {
                bitmapimage[i].Save(Path.Combine(Directory.GetCurrentDirectory(), startupPath, string.Format("{1}_page_{0}", i, fileName.Split('.')[0]) + ".png"));
            }
        }
        public IActionResult EditEquation(string Button, string Group1)
        {
            if (Button == null)
            {
                return(View());
            }
            string basePath    = _hostingEnvironment.WebRootPath;
            string dataPath    = basePath + @"/DocIO/Mathematical Equation.docx";
            string contenttype = "application/vnd.ms-word.document.12";
            // Load Template document stream.
            FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            if (Button == "View Template")
            {
                return(File(fileStream, contenttype, "Mathematical Equation.docx"));
            }

            // Creates an empty Word document instance.
            WordDocument document = new WordDocument();

            // Opens template document.
            document.Open(fileStream, FormatType.Docx);
            fileStream.Dispose();
            fileStream = null;
            //Gets the last section in the document
            WSection section = document.LastSection;
            //Gets paragraph from Word document
            WParagraph paragraph = document.LastSection.Body.ChildEntities[3] as WParagraph;

            //Gets MathML from the paragraph
            WMath math = paragraph.ChildEntities[0] as WMath;
            //Gets the radical equation
            IOfficeMathRadical mathRadical = math.MathParagraph.Maths[0].Functions[1] as IOfficeMathRadical;
            //Gets the fraction equation in radical
            IOfficeMathFraction mathFraction = mathRadical.Equation.Functions[0] as IOfficeMathFraction;
            //Gets the n-array in fraction
            IOfficeMathNArray mathNAry = mathFraction.Numerator.Functions[0] as IOfficeMathNArray;
            //Gets the math script in n-array
            IOfficeMathScript mathScript = mathNAry.Equation.Functions[0] as IOfficeMathScript;
            //Gets the delimiter in math script
            IOfficeMathDelimiter mathDelimiter = mathScript.Equation.Functions[0] as IOfficeMathDelimiter;

            //Gets the math script in delimiter
            mathScript = mathDelimiter.Equation[0].Functions[0] as IOfficeMathScript;
            //Gets the math run element in math script
            IOfficeMathRunElement mathParaItem = mathScript.Equation.Functions[0] as IOfficeMathRunElement;

            //Modifies the math text value
            (mathParaItem.Item as WTextRange).Text = "x";

            //Gets the math bar in delimiter
            IOfficeMathBar mathBar = mathDelimiter.Equation[0].Functions[2] as IOfficeMathBar;

            //Gets the math run element in bar
            mathParaItem = mathBar.Equation.Functions[0] as IOfficeMathRunElement;
            //Modifies the math text value
            (mathParaItem.Item as WTextRange).Text = "x";

            //Gets the paragraph from Word document
            paragraph = document.LastSection.Body.ChildEntities[6] as WParagraph;
            //Gets MathML from the paragraph
            math = paragraph.ChildEntities[0] as WMath;
            //Gets the math script equation
            mathScript = math.MathParagraph.Maths[0].Functions[0] as IOfficeMathScript;
            //Gets the math run element in math script
            mathParaItem = mathScript.Equation.Functions[0] as IOfficeMathRunElement;
            //Modifies the math text value
            (mathParaItem.Item as WTextRange).Text = "x";

            //Gets the paragraph from Word document
            paragraph = document.LastSection.Body.ChildEntities[7] as WParagraph;
            //Gets MathML from the paragraph
            WMath math2 = paragraph.ChildEntities[0] as WMath;

            //Gets bar equation
            mathBar = math2.MathParagraph.Maths[0].Functions[0] as IOfficeMathBar;
            //Gets the math run element in bar
            mathParaItem = mathBar.Equation.Functions[0] as IOfficeMathRunElement;
            //Gets the math text
            (mathParaItem.Item as WTextRange).Text = "x";

            string       filename = "";
            MemoryStream ms       = new MemoryStream();

            #region Document SaveOption
            if (Group1 == "WordDocx")
            {
                filename    = "EditEquation.docx";
                contenttype = "application/msword";
                document.Save(ms, FormatType.Docx);
            }
            else
            {
                filename    = "EditEquation.pdf";
                contenttype = "application/pdf";
                DocIORenderer renderer = new DocIORenderer();
                renderer.ConvertToPDF(document).Save(ms);
            }
            #endregion Document SaveOption
            document.Close();
            ms.Position = 0;
            return(File(ms, contenttype, filename));
        }
Пример #23
0
        void OnConvertClicked(object sender, EventArgs e)
        {
            //Initialize Word document
            WordDocument doc = new WordDocument();

            //Ensure Minimum
            doc.EnsureMinimal();
            //Set margins for page.
            doc.LastSection.PageSetup.Margins.All = 72;
            //Create new group shape
            GroupShape groupShape = new GroupShape(doc);

            //Append AutoShape
            Shape shape = new Shape(doc, AutoShapeType.RoundedRectangle);

            shape.Width  = 130;
            shape.Height = 45;
            //Set horizontal origin
            shape.HorizontalOrigin = HorizontalOrigin.Page;
            //Set vertical origin
            shape.VerticalOrigin = VerticalOrigin.Page;
            //Set vertical position
            shape.VerticalPosition = 122;
            //Set horizontal position
            shape.HorizontalPosition = 220;
            //Set AllowOverlap to true for overlapping shapes
            shape.WrapFormat.AllowOverlap = true;
            //Set Fill Color
            shape.FillFormat.Color = Syncfusion.Drawing.Color.Blue;
            //Set Content vertical alignment
            shape.TextFrame.TextVerticalAlignment = Syncfusion.DocIO.DLS.VerticalAlignment.Middle;
            //Add Texbody contents to Shape
            IWParagraph para = shape.TextBody.AddParagraph();

            para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            para.AppendText("Requirement").ApplyCharacterFormat(new WCharacterFormat(doc)
            {
                Bold = true, TextColor = Syncfusion.Drawing.Color.White, FontSize = 12, FontName = "Verdana"
            });
            groupShape.Add(shape);

            shape                  = new Shape(doc, AutoShapeType.DownArrow);
            shape.Width            = 45;
            shape.Height           = 45;
            shape.HorizontalOrigin = HorizontalOrigin.Page;
            shape.VerticalOrigin   = VerticalOrigin.Page;
            shape.VerticalPosition = 167;
            //Set horizontal position
            shape.HorizontalPosition      = 265;
            shape.WrapFormat.AllowOverlap = true;
            groupShape.Add(shape);

            shape                  = new Shape(doc, AutoShapeType.RoundedRectangle);
            shape.Width            = 130;
            shape.Height           = 45;
            shape.HorizontalOrigin = HorizontalOrigin.Page;
            shape.VerticalOrigin   = VerticalOrigin.Page;
            shape.VerticalPosition = 212;
            //Set horizontal position
            shape.HorizontalPosition              = 220;
            shape.WrapFormat.AllowOverlap         = true;
            shape.FillFormat.Color                = Syncfusion.Drawing.Color.Orange;
            shape.TextFrame.TextVerticalAlignment = VerticalAlignment.Middle;
            para = shape.TextBody.AddParagraph();
            para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            para.AppendText("Design").ApplyCharacterFormat(new WCharacterFormat(doc)
            {
                Bold = true, TextColor = Syncfusion.Drawing.Color.White, FontSize = 12, FontName = "Verdana"
            });
            groupShape.Add(shape);

            shape                  = new Shape(doc, AutoShapeType.DownArrow);
            shape.Width            = 45;
            shape.Height           = 45;
            shape.HorizontalOrigin = HorizontalOrigin.Page;
            shape.VerticalOrigin   = VerticalOrigin.Page;
            shape.VerticalPosition = 257;
            //Set horizontal position
            shape.HorizontalPosition      = 265;
            shape.WrapFormat.AllowOverlap = true;
            groupShape.Add(shape);

            shape                  = new Shape(doc, AutoShapeType.RoundedRectangle);
            shape.Width            = 130;
            shape.Height           = 45;
            shape.HorizontalOrigin = HorizontalOrigin.Page;
            shape.VerticalOrigin   = VerticalOrigin.Page;
            shape.VerticalPosition = 302;
            //Set horizontal position
            shape.HorizontalPosition              = 220;
            shape.WrapFormat.AllowOverlap         = true;
            shape.FillFormat.Color                = Syncfusion.Drawing.Color.Blue;
            shape.TextFrame.TextVerticalAlignment = VerticalAlignment.Middle;
            para = shape.TextBody.AddParagraph();
            para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            para.AppendText("Execution").ApplyCharacterFormat(new WCharacterFormat(doc)
            {
                Bold = true, TextColor = Syncfusion.Drawing.Color.White, FontSize = 12, FontName = "Verdana"
            });
            groupShape.Add(shape);

            shape                  = new Shape(doc, AutoShapeType.DownArrow);
            shape.Width            = 45;
            shape.Height           = 45;
            shape.HorizontalOrigin = HorizontalOrigin.Page;
            shape.VerticalOrigin   = VerticalOrigin.Page;
            shape.VerticalPosition = 347;
            //Set horizontal position
            shape.HorizontalPosition      = 265;
            shape.WrapFormat.AllowOverlap = true;
            groupShape.Add(shape);

            shape                  = new Shape(doc, AutoShapeType.RoundedRectangle);
            shape.Width            = 130;
            shape.Height           = 45;
            shape.HorizontalOrigin = HorizontalOrigin.Page;
            shape.VerticalOrigin   = VerticalOrigin.Page;
            shape.VerticalPosition = 392;
            //Set horizontal position
            shape.HorizontalPosition              = 220;
            shape.WrapFormat.AllowOverlap         = true;
            shape.FillFormat.Color                = Syncfusion.Drawing.Color.Violet;
            shape.TextFrame.TextVerticalAlignment = VerticalAlignment.Middle;
            para = shape.TextBody.AddParagraph();
            para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            para.AppendText("Testing").ApplyCharacterFormat(new WCharacterFormat(doc)
            {
                Bold = true, TextColor = Syncfusion.Drawing.Color.White, FontSize = 12, FontName = "Verdana"
            });
            groupShape.Add(shape);


            shape                  = new Shape(doc, AutoShapeType.DownArrow);
            shape.Width            = 45;
            shape.Height           = 45;
            shape.HorizontalOrigin = HorizontalOrigin.Page;
            shape.VerticalOrigin   = VerticalOrigin.Page;
            shape.VerticalPosition = 437;
            //Set horizontal position
            shape.HorizontalPosition      = 265;
            shape.WrapFormat.AllowOverlap = true;
            groupShape.Add(shape);


            shape                  = new Shape(doc, AutoShapeType.RoundedRectangle);
            shape.Width            = 130;
            shape.Height           = 45;
            shape.HorizontalOrigin = HorizontalOrigin.Page;
            shape.VerticalOrigin   = VerticalOrigin.Page;
            shape.VerticalPosition = 482;
            //Set horizontal position
            shape.HorizontalPosition              = 220;
            shape.WrapFormat.AllowOverlap         = true;
            shape.FillFormat.Color                = Syncfusion.Drawing.Color.PaleVioletRed;
            shape.TextFrame.TextVerticalAlignment = VerticalAlignment.Middle;
            para = shape.TextBody.AddParagraph();
            para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            para.AppendText("Release").ApplyCharacterFormat(new WCharacterFormat(doc)
            {
                Bold = true, TextColor = Syncfusion.Drawing.Color.White, FontSize = 12, FontName = "Verdana"
            });
            groupShape.Add(shape);
            doc.LastParagraph.ChildEntities.Add(groupShape);

            string       fileName    = null;
            string       ContentType = null;
            MemoryStream ms          = new MemoryStream();

            if (pdfButton != null && (bool)pdfButton.IsChecked)
            {
                fileName    = "GroupShapes.pdf";
                ContentType = "application/pdf";
                DocIORenderer renderer = new DocIORenderer();
                PdfDocument   pdfDoc   = renderer.ConvertToPDF(doc);
                pdfDoc.Save(ms);
                pdfDoc.Close();
            }
            else
            {
                fileName    = "GroupShapes.docx";
                ContentType = "application/msword";
                doc.Save(ms, FormatType.Docx);
            }

            //Reset the stream position
            ms.Position = 0;

            //Close the document instance.
            doc.Close();

            if (ms != null)
            {
                SaveiOS iOSSave = new SaveiOS();
                iOSSave.Save(fileName, ContentType, ms as MemoryStream);
            }
        }
Пример #24
0
        public ActionResult BarChart(string Group1)
        {
            if (Group1 == null)
            {
                return(View());
            }

            //A new document is created.
            WordDocument document = new WordDocument();
            //Add new section to the Word document
            IWSection section = document.AddSection();

            //Set page margins of the section
            section.PageSetup.Margins.All = 72;
            //Add new paragraph to the section
            IWParagraph paragraph = section.AddParagraph();

            //Apply heading style to the title paragraph
            paragraph.ApplyStyle(BuiltinStyle.Heading1);
            //Apply center alignment to the paragraph
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            //Append text to the paragraph
            paragraph.AppendText("Northwind Management Report").CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(46, 116, 181);
            //Add new paragraph
            paragraph = section.AddParagraph();
            //Set before spacing to the paragraph
            paragraph.ParagraphFormat.BeforeSpacing = 20;
            string basePath = _hostingEnvironment.WebRootPath;
            string dataPath = basePath + @"/DocIO/Excel_Template.xlsx";
            //Load the excel template as stream
            Stream excelStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read);
            //Create and Append chart to the paragraph with excel stream as parameter
            WChart BarChart = paragraph.AppendChart(excelStream, 1, "B2:C6", 470, 300);

            //Set chart data
            BarChart.ChartType  = OfficeChartType.Bar_Clustered;
            BarChart.ChartTitle = "Purchase Details";
            BarChart.ChartTitleArea.FontName = "Calibri (Body)";
            BarChart.ChartTitleArea.Size     = 14;
            //Set name to chart series
            BarChart.Series[0].Name = "Sum of Purchases";
            BarChart.Series[1].Name = "Sum of Future Expenses";
            //Set Chart Data table
            BarChart.HasDataTable             = true;
            BarChart.DataTable.HasBorders     = true;
            BarChart.DataTable.HasHorzBorder  = true;
            BarChart.DataTable.HasVertBorder  = true;
            BarChart.DataTable.ShowSeriesKeys = true;
            BarChart.HasLegend = false;
            //Setting background color
            BarChart.ChartArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(208, 206, 206);
            BarChart.PlotArea.Fill.ForeColor  = Syncfusion.Drawing.Color.FromArgb(208, 206, 206);
            //Setting line pattern to the chart area
            BarChart.PrimaryCategoryAxis.Border.LinePattern           = OfficeChartLinePattern.None;
            BarChart.PrimaryValueAxis.Border.LinePattern              = OfficeChartLinePattern.None;
            BarChart.ChartArea.Border.LinePattern                     = OfficeChartLinePattern.None;
            BarChart.PrimaryValueAxis.MajorGridLines.Border.LineColor = Syncfusion.Drawing.Color.FromArgb(175, 171, 171);
            //Set label for primary catagory axis
            BarChart.PrimaryCategoryAxis.CategoryLabels = BarChart.ChartData[2, 1, 6, 1];

            string       filename    = "";
            string       contenttype = "";
            MemoryStream ms          = new MemoryStream();

            #region Document SaveOption
            if (Group1 == "WordDocx")
            {
                filename    = "Sample.docx";
                contenttype = "application/msword";
                document.Save(ms, FormatType.Docx);
            }
            else if (Group1 == "WordML")
            {
                filename    = "Sample.xml";
                contenttype = "application/msword";
                document.Save(ms, FormatType.WordML);
            }
            else
            {
                filename    = "Sample.pdf";
                contenttype = "application/pdf";
                DocIORenderer renderer = new DocIORenderer();
                renderer.ConvertToPDF(document).Save(ms);
            }
            #endregion Document SaveOption
            document.Close();
            ms.Position = 0;
            return(File(ms, contenttype, filename));
        }
Пример #25
0
        public ActionResult PieChart(string Group1)
        {
            if (Group1 == null)
            {
                return(View());
            }
            string basePath = _hostingEnvironment.WebRootPath;
            string datapath = basePath + @"/DocIO/PieChart.docx";
            //A new document is created.
            FileStream   fileStream = new FileStream(datapath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            WordDocument document   = new WordDocument(fileStream, FormatType.Docx);
            //Create MailMergeDataTable
            MailMergeDataTable mailMergeDataTable = GetMailMergeDataTableProductDetails();

            //Merge the product table in the Word document
            document.MailMerge.ExecuteGroup(mailMergeDataTable);
            //Find the Placeholder of Pie chart to insert
            TextSelection selection = document.Find("<Pie Chart>", false, false);
            WParagraph    paragraph = selection.GetAsOneRange().OwnerParagraph;

            paragraph.ChildEntities.Clear();
            //Create and Append chart to the paragraph
            WChart pieChart = paragraph.AppendChart(446, 270);

            //Set chart data
            pieChart.ChartType  = OfficeChartType.Pie;
            pieChart.ChartTitle = "Best Selling Products";
            pieChart.ChartTitleArea.FontName = "Calibri (Body)";
            pieChart.ChartTitleArea.Size     = 14;
            GetChartData(pieChart, 0);
            //Create a new chart series with the name “Sales”
            IOfficeChartSerie pieSeries = pieChart.Series.Add("Sales");

            pieSeries.Values = pieChart.ChartData[2, 2, 11, 2];
            //Setting data label
            pieSeries.DataPoints.DefaultDataPoint.DataLabels.IsPercentage = true;
            pieSeries.DataPoints.DefaultDataPoint.DataLabels.Position     = OfficeDataLabelPosition.Outside;
            //Setting background color
            pieChart.ChartArea.Fill.ForeColor           = Syncfusion.Drawing.Color.FromArgb(242, 242, 242);
            pieChart.PlotArea.Fill.ForeColor            = Syncfusion.Drawing.Color.FromArgb(242, 242, 242);
            pieChart.ChartArea.Border.LinePattern       = OfficeChartLinePattern.None;
            pieChart.PrimaryCategoryAxis.CategoryLabels = pieChart.ChartData[2, 1, 11, 1];

            string       filename    = "";
            string       contenttype = "";
            MemoryStream ms          = new MemoryStream();

            #region Document SaveOption
            if (Group1 == "WordDocx")
            {
                filename    = "Sample.docx";
                contenttype = "application/msword";
                document.Save(ms, FormatType.Docx);
            }
            else if (Group1 == "WordML")
            {
                filename    = "Sample.xml";
                contenttype = "application/msword";
                document.Save(ms, FormatType.WordML);
            }
            else
            {
                filename    = "Sample.pdf";
                contenttype = "application/pdf";
                DocIORenderer renderer = new DocIORenderer();
                renderer.ConvertToPDF(document).Save(ms);
            }
            #endregion Document SaveOption
            document.Close();
            ms.Position = 0;
            return(File(ms, contenttype, filename));
        }
Пример #26
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            Assembly assembly = typeof(CreateEquation).GetTypeInfo().Assembly;

#if COMMONSB
            string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates.";
#else
            string rootPath = "SampleBrowser.DocIO.Samples.Templates.";
#endif
            Stream inputStream = assembly.GetManifestResourceStream(rootPath + "CreateEquation.docx");

            // Loads the stream into Word Document.
            WordDocument document = new WordDocument(inputStream, Syncfusion.DocIO.FormatType.Automatic);
            //Gets the last section in the document
            WSection section = document.LastSection;
            //Sets page margins
            document.LastSection.PageSetup.Margins.All = 72;
            //Adds new paragraph to the section
            IWParagraph paragraph = section.AddParagraph();

            //Appends text to paragraph
            IWTextRange textRange = paragraph.AppendText("Mathematical equations");
            textRange.CharacterFormat.FontSize            = 28;
            paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;
            paragraph.ParagraphFormat.AfterSpacing        = 12;

            #region Sum to the power of n
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is an expansion of the sum (1+X) to the power of n.");
            //Creates an equation with sum to the power of N
            CreateSumToThePowerOfN(paragraph);
            #endregion

            #region Fourier series
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is a Fourier series for the function of period 2L");
            //Creates a Fourier series equation
            CreateFourierseries(paragraph);
            #endregion

            #region Triple scalar product
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is an expansion of triple scalar product");
            //Creates a triple scalar product equation
            CreateTripleScalarProduct(paragraph);
            #endregion

            #region Gamma function
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is an expansion of gamma function");
            //Creates a gamma function equation
            CreateGammaFunction(paragraph);
            #endregion

            #region Vector relation
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is an expansion of vector relation ");
            //Creates a vector relation equation
            CreateVectorRelation(paragraph);
            #endregion

            string       filename     = "";
            string       contenttype  = "";
            MemoryStream outputStream = new MemoryStream();
            if (this.pdfButton.IsChecked != null && (bool)this.pdfButton.IsChecked)
            {
                filename    = "CreateEquation.pdf";
                contenttype = "application/pdf";
                DocIORenderer renderer = new DocIORenderer();
                PdfDocument   pdfDoc   = renderer.ConvertToPDF(document);
                pdfDoc.Save(outputStream);
                pdfDoc.Close();
            }
            else
            {
                filename    = "CreateEquation.docx";
                contenttype = "application/msword";
                document.Save(outputStream, FormatType.Docx);
            }
            document.Close();

            if (Device.RuntimePlatform == Device.UWP)
            {
                Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save(filename, contenttype, outputStream);
            }
            else
            {
                Xamarin.Forms.DependencyService.Get <ISave>().Save(filename, contenttype, outputStream);
            }
        }
        void OnButtonClicked(object sender, EventArgs e)
        {
            WordDocument doc = new WordDocument();

            doc.EnsureMinimal();

            WParagraph para = doc.LastParagraph;

            para.AppendText("Essential DocIO - Table of Contents");
            para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            para.ApplyStyle(BuiltinStyle.Heading4);

            para = doc.LastSection.AddParagraph() as WParagraph;
            para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            para.ApplyStyle(BuiltinStyle.Heading4);

            para = doc.LastSection.AddParagraph() as WParagraph;

            //Insert TOC
            TableOfContent toc = para.AppendTOC(1, 3);

            para.ApplyStyle(BuiltinStyle.Heading4);

            //Apply built-in paragraph formatting
            WSection section = doc.LastSection;

            #region Default Styles
            WParagraph newPara = section.AddParagraph() as WParagraph;
            newPara = section.AddParagraph() as WParagraph;
            newPara.AppendBreak(BreakType.PageBreak);
            WTextRange text = newPara.AppendText("Document with Default styles") as WTextRange;
            newPara.ApplyStyle(BuiltinStyle.Heading1);
            newPara = section.AddParagraph() as WParagraph;
            newPara.AppendText("This is the heading1 of built in style. This sample demonstrates the TOC insertion in a word document. Note that DocIO can only insert TOC field in a word document. It can not refresh or create TOC field. MS Word refreshes the TOC field after insertion. Please update the field or press F9 key to refresh the TOC.");

            section.AddParagraph();
            newPara = section.AddParagraph() as WParagraph;
            text    = newPara.AppendText("Section1") as WTextRange;
            newPara.ApplyStyle(BuiltinStyle.Heading2);
            newPara = section.AddParagraph() as WParagraph;
            newPara.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");

            section.AddParagraph();
            newPara = section.AddParagraph() as WParagraph;
            text    = newPara.AppendText("Paragraph1") as WTextRange;
            newPara.ApplyStyle(BuiltinStyle.Heading3);
            newPara = section.AddParagraph() as WParagraph;
            newPara.AppendText("This is the heading3 of built in style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text.");

            section.AddParagraph();
            newPara = section.AddParagraph() as WParagraph;
            text    = newPara.AppendText("Paragraph2") as WTextRange;
            newPara.ApplyStyle(BuiltinStyle.Heading3);
            newPara = section.AddParagraph() as WParagraph;
            newPara.AppendText("This is the heading3 of built in style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph.");

            section.AddParagraph();
            section           = doc.AddSection() as WSection;
            section.BreakCode = SectionBreakCode.NewPage;
            newPara           = section.AddParagraph() as WParagraph;
            text = newPara.AppendText("Section2") as WTextRange;
            newPara.ApplyStyle(BuiltinStyle.Heading2);
            newPara = section.AddParagraph() as WParagraph;
            newPara.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");

            section.AddParagraph();
            newPara = section.AddParagraph() as WParagraph;
            text    = newPara.AppendText("Paragraph1") as WTextRange;
            newPara.ApplyStyle(BuiltinStyle.Heading3);
            newPara = section.AddParagraph() as WParagraph;
            newPara.AppendText("This is the heading3 of built in style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text.");

            section.AddParagraph();
            newPara = section.AddParagraph() as WParagraph;
            text    = newPara.AppendText("Paragraph2") as WTextRange;
            newPara.ApplyStyle(BuiltinStyle.Heading3);
            newPara = section.AddParagraph() as WParagraph;
            newPara.AppendText("This is the heading3 of built in style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph.");
            #endregion

            toc.IncludePageNumbers    = true;
            toc.RightAlignPageNumbers = true;
            toc.UseHyperlinks         = true;
            toc.LowerHeadingLevel     = 1;
            toc.UpperHeadingLevel     = 3;

            toc.UseOutlineLevels = true;

            //Updates the table of contents.
            doc.UpdateTableOfContents();
            string       filename     = "";
            string       contenttype  = "";
            MemoryStream outputStream = new MemoryStream();
            if (pdfButton != null && (bool)pdfButton.IsChecked)
            {
                filename    = "Table Of Contents.pdf";
                contenttype = "application/pdf";
                DocIORenderer renderer = new DocIORenderer();
                PdfDocument   pdfDoc   = renderer.ConvertToPDF(doc);
                pdfDoc.Save(outputStream);
                pdfDoc.Close();
            }
            else
            {
                filename    = "Table Of Contents.docx";
                contenttype = "application/msword";
                doc.Save(outputStream, FormatType.Docx);
            }

            doc.Close();
            if (Device.RuntimePlatform == Device.UWP)
            {
                DependencyService.Get <ISaveWindowsPhone>()
                .Save(filename, contenttype, outputStream);
            }
            else
            {
                DependencyService.Get <ISave>().Save(filename, contenttype, outputStream);
            }
        }
Пример #28
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            string   resourcePath = "SampleBrowser.Samples.DocIO.Templates.CreateEquation.docx";
            Assembly assembly     = Assembly.GetExecutingAssembly();
            Stream   fileStream   = assembly.GetManifestResourceStream(resourcePath);

            // Loads the stream into Word Document.
            WordDocument document = new WordDocument(fileStream, Syncfusion.DocIO.FormatType.Automatic);
            //Gets the last section in the document
            WSection section = document.LastSection;

            //Sets page margins
            document.LastSection.PageSetup.Margins.All = 72;
            //Adds new paragraph to the section
            IWParagraph paragraph = section.AddParagraph();

            //Appends text to paragraph
            IWTextRange textRange = paragraph.AppendText("Mathematical equations");

            textRange.CharacterFormat.FontSize            = 28;
            paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;
            paragraph.ParagraphFormat.AfterSpacing        = 12;

            #region Sum to the power of n
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is an expansion of the sum (1+X) to the power of n.");
            //Creates an equation with sum to the power of N
            CreateSumToThePowerOfN(paragraph);
            #endregion

            #region Fourier series
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is a Fourier series for the function of period 2L");
            //Creates a Fourier series equation
            CreateFourierseries(paragraph);
            #endregion

            #region Triple scalar product
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is an expansion of triple scalar product");
            //Creates a triple scalar product equation
            CreateTripleScalarProduct(paragraph);
            #endregion

            #region Gamma function
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is an expansion of gamma function");
            //Creates a gamma function equation
            CreateGammaFunction(paragraph);
            #endregion

            #region Vector relation
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is an expansion of vector relation ");
            //Creates a vector relation equation
            CreateVectorRelation(paragraph);
            #endregion

            MemoryStream stream = new MemoryStream();
            //Set file content type
            string contentType = null;
            string fileName    = null;
            if (docxButton.Checked)
            {
                fileName    = "CreateEquation.docx";
                contentType = "application/msword";
                document.Save(stream, FormatType.Docx);
            }
            else
            {
                fileName    = "CreateEquation.pdf";
                contentType = "application/pdf";
                DocIORenderer renderer = new DocIORenderer();
                PdfDocument   pdfDoc   = renderer.ConvertToPDF(document);
                pdfDoc.Save(stream);

                pdfDoc.Close();
            }

            document.Dispose();
            if (stream != null)
            {
                SaveAndroid androidSave = new SaveAndroid();
                androidSave.Save(fileName, contentType, stream, m_context);
            }
        }
Пример #29
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            //Creates a new Word document
            WordDocument document = new WordDocument();
            //Adds new section to the document
            IWSection section = document.AddSection();

            //Sets page setup options
            section.PageSetup.Orientation = PageOrientation.Landscape;
            section.PageSetup.Margins.All = 72;
            section.PageSetup.PageSize    = new SizeF(792f, 612f);
            //Adds new paragraph to the section
            WParagraph paragraph = section.AddParagraph() as WParagraph;
            //Creates new group shape
            GroupShape groupShape = new GroupShape(document);

            //Adds group shape to the paragraph.
            paragraph.ChildEntities.Add(groupShape);

            //Create a RoundedRectangle shape with "Management" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(324f, 107.7f, 144f, 45f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(50, 48, 142), "Management", groupShape, document);

            //Create a BentUpArrow shape to connect with "Development" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(177.75f, 176.25f, 210f, 50f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "Sales" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(403.5f, 175.5f, 210f, 50f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a DownArrow shape to connect with "Production" shape
            CreateChildShape(AutoShapeType.DownArrow, new RectangleF(381f, 153f, 29.25f, 72.5f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a RoundedRectangle shape with "Development" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(135f, 226.45f, 110f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(104, 57, 157), "Development", groupShape, document);

            //Create a RoundedRectangle shape with "Production" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(341f, 226.5f, 110f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(149, 50, 118), "Production", groupShape, document);

            //Create a RoundedRectangle shape with "Sales" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(546.75f, 226.5f, 110f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(179, 63, 62), "Sales", groupShape, document);

            //Create a DownArrow shape to connect with "Software" and "Hardware" shape
            CreateChildShape(AutoShapeType.DownArrow, new RectangleF(177f, 265.5f, 25.5f, 20.25f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a DownArrow shape to connect with "Series" and "Parts" shape
            CreateChildShape(AutoShapeType.DownArrow, new RectangleF(383.25f, 265.5f, 25.5f, 20.25f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a DownArrow shape to connect with "North" and "South" shape
            CreateChildShape(AutoShapeType.DownArrow, new RectangleF(588.75f, 266.25f, 25.5f, 20.25f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "Software" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(129.5f, 286.5f, 60f, 33f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "Hardware" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(190.5f, 286.5f, 60f, 33f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "Series" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(336f, 287.25f, 60f, 33f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "Parts" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(397f, 287.25f, 60f, 33f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "North" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(541.5f, 288f, 60f, 33f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "South" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(602.5f, 288f, 60f, 33f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a RoundedRectangle shape with "Software" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(93f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(23, 187, 189), "Software", groupShape, document);

            //Create a RoundedRectangle shape with "Hardware" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(197.2f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(24, 159, 106), "Hardware", groupShape, document);

            //Create a RoundedRectangle shape with "Series" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(299.25f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(23, 187, 189), "Series", groupShape, document);

            //Create a RoundedRectangle shape with "Parts" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(404.2f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(24, 159, 106), "Parts", groupShape, document);

            //Create a RoundedRectangle shape with "North" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(505.5f, 321.75f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(23, 187, 189), "North", groupShape, document);

            //Create a RoundedRectangle shape with "South" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(609.7f, 321.75f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(24, 159, 106), "South", groupShape, document);

            string       filename     = "";
            string       contenttype  = "";
            MemoryStream outputStream = new MemoryStream();

            if (this.pdfButton.IsChecked != null && (bool)this.pdfButton.IsChecked)
            {
                filename    = "GroupShapes.pdf";
                contenttype = "application/pdf";
                DocIORenderer renderer = new DocIORenderer();
                PdfDocument   pdfDoc   = renderer.ConvertToPDF(document);
                pdfDoc.Save(outputStream);
                pdfDoc.Close();
            }
            else
            {
                filename    = "GroupShapes.docx";
                contenttype = "application/msword";
                document.Save(outputStream, FormatType.Docx);
            }
            document.Close();
            if (Device.RuntimePlatform == Device.UWP)
            {
                DependencyService.Get <ISaveWindowsPhone>()
                .Save(filename, contenttype, outputStream);
            }
            else
            {
                DependencyService.Get <ISave>().Save(filename, contenttype, outputStream);
            }
        }
Пример #30
0
        public async Task <IActionResult> GenerateDocument(int Id, string tokenId)
        {
            var LabTest = _context.TblLabTests
                          .Include(x => x.MethodNavigation)
                          .Include(x => x.BiodataNavigation)
                          .Include(x => x.BiodataNavigation.GenderNavigation)
                          .Include(x => x.TblLabTestsIndicatorsValues)
                          .Include(x => x.TblLabTestsSpecimen)
                          .FirstOrDefault(x => x.Id == Id);

            if (LabTest == null)
            {
                return(NotFound());
            }

            //Loads or opens an existing word document through Open method of WordDocument class
            Stream fs = new FileStream("Templates/result.docx", FileMode.Open, FileAccess.Read, FileShare.Read);

            WordDocument document = new WordDocument(fs, FormatType.Docx);

            if (document.Sections.Count < 1)
            {
                throw new Exception("Result template empty. Please contact your Application support.");
            }
            IWSection section = document.Sections[0];

            IWTable table = section.Tables[0];

            WParagraph p = (WParagraph)table.Rows[0].Cells[1].ChildEntities[0];

            p.AppendText(LabTest.BiodataNavigation.Fullname);

            p = (WParagraph)table.Rows[1].Cells[1].ChildEntities[0];
            string gardian = LabTest.BiodataNavigation.LegalGardianName;

            gardian = string.IsNullOrEmpty(gardian) ? "-" : gardian;
            p.AppendText(gardian);

            p = (WParagraph)table.Rows[2].Cells[1].ChildEntities[0];

            p.AppendText(LabTest.BiodataNavigation.Dateofbirth.ToString("dd/MMM/yyyy"));

            //skip 3


            //Repos.GenderRepos genders = new Repos.GenderRepos();


            int g_id = 1;

            foreach (var g in _context.TlkpGenders)
            {
                string tmp = g.Gender.Substring(0, 2).Trim().Trim('=');
                try
                {
                    p = (WParagraph)table.Rows[3].Cells[g_id].ChildEntities[0];
                    WCheckBox checkbox = p.AppendCheckBox();

                    if (LabTest.BiodataNavigation.Gender == g_id)
                    {
                        checkbox.Checked = true;
                    }

                    p.AppendText(" " + tmp);

                    g_id++;
                }
                catch
                {
                }
            }

            p = (WParagraph)table.Rows[4].Cells[1].ChildEntities[0];
            p.AppendText(LabTest.BiodataNavigation.EpidNo);

            //skip 5 for local phone number
            p = (WParagraph)table.Rows[5].Cells[1].ChildEntities[0];
            p.AppendText(LabTest.BiodataNavigation.LocalPhone ?? "-");

            p = (WParagraph)table.Rows[6].Cells[1].ChildEntities[0];
            p.AppendText(LabTest.BiodataNavigation.HomePhone ?? "-");

            p = (WParagraph)table.Rows[7].Cells[1].ChildEntities[0];
            p.AppendText(LabTest.BiodataNavigation.ResidentialAddress);

            //next table
            table = section.Tables[1];

            p = (WParagraph)table.Rows[0].Cells[1].ChildEntities[0];
            p.AppendText(LabTest.MethodNavigation.Methodname);

            int k = 1;


            foreach (var i in LabTest.TblLabTestsIndicatorsValues)
            {
                var iname = _context.TlkpTestIndicators.FirstOrDefault(x => x.Id == i.Indicator).IndicatorName;

                p = (WParagraph)table.Rows[k].Cells[0].ChildEntities[0];
                p.AppendText(iname);

                p = (WParagraph)table.Rows[k].Cells[1].ChildEntities[0];
                p.AppendText(i.IndicatorValue.Value.ToString());

                k++;
            }



            /*Dictionary<int, string> _dict = new Dictionary<int, string> {
             *  { 1, "POSITIVE"},
             *  { 2, "NEGATIVE"},
             *  { 97, "NO RESULT"}
             * };*/
            var p1 = (WParagraph)table.Rows[k].Cells[0].ChildEntities[0];

            p = (WParagraph)table.Rows[k].Cells[1].ChildEntities[0];
            WCheckBox checkbox1 = p.AppendCheckBox();

            if (LabTest.Interpretation == 2)
            {
                checkbox1.Checked = true;
                p1.AppendText("INTERPRETATION: NEGATIVE RESULT");
            }
            else if (LabTest.Interpretation > 2)
            {
                p1.AppendText("INTERPRETATION: UNKNOWN");
            }

            p.AppendText(" NEGATIVE");

            p         = (WParagraph)table.Rows[k + 1].Cells[1].ChildEntities[0];
            checkbox1 = p.AppendCheckBox();
            if (LabTest.Interpretation == 1)
            {
                checkbox1.Checked = true;
                p1.AppendText("INTERPRETATION: POSITIVE RESULT");
            }

            p.AppendText(" POSITIVE");

            //next table
            table = section.Tables[2];

            DateTime d1 = DateTime.Today;               // any date will do

            p = (WParagraph)table.Rows[0].Cells[1].ChildEntities[0];
            p.AppendText(LabTest.TestingDate.Value.ToString("dd/MMM/yyyy"));

            p = (WParagraph)table.Rows[1].Cells[1].ChildEntities[0];
            TimeSpan t   = LabTest.TestingTime.Value;
            string   chg = (d1 + t).ToString("hh:mm tt");

            p.AppendText(chg);

            p = (WParagraph)table.Rows[2].Cells[1].ChildEntities[0];
            p.AppendText(LabTest.ReportingDate.Value.ToString("dd/MMM/yyyy"));

            p   = (WParagraph)table.Rows[3].Cells[1].ChildEntities[0];
            t   = LabTest.ReportingTime.Value;
            chg = (d1 + t).ToString("hh:mm tt");
            p.AppendText(chg);

            //next table
            table = section.Tables[3];

            //Repos.SpecimenRepos _specimen = new Repos.SpecimenRepos();

            k = 1;
            foreach (var s in LabTest.TblLabTestsSpecimen)
            {
                bool other = s.Specimen == 99;

                var sname = _context.TlkpSpecimen.FirstOrDefault(x => x.Id == s.Specimen).Type;
                p = (WParagraph)table.Rows[k].Cells[0].ChildEntities[0];

                IWTextRange textRange = p.AppendText(sname + (other ? " (Specify)" : ""));
                textRange.CharacterFormat.FontSize = 8;


                p.ApplyStyle(BuiltinStyle.BlockText);
                p = (WParagraph)table.Rows[k].Cells[1].ChildEntities[0];
                if (other && !string.IsNullOrEmpty(s.SpecimenOther))
                {
                    textRange = p.AppendText(s.SpecimenOther);
                    textRange.CharacterFormat.FontSize = 10;
                }

                p         = (WParagraph)table.Rows[k].Cells[2].ChildEntities[0];
                checkbox1 = p.AppendCheckBox();
                if (s.Checked)
                {
                    checkbox1.Checked = true;
                }

                k++;
            }


            //
            //table = section.Tables[1];
            // p = (WParagraph)table.Rows[6].Cells[1].ChildEntities[0];
            //p.AppendText(LabTest.BioData.ResidentialAddress);


            DocIORenderer render = new DocIORenderer();
            //Converts Word document to PDF.
            PdfDocument pdfDocument = render.ConvertToPDF(document);

            //Release the resources used by the Word document and DocIO Renderer objects.

            render.Dispose();
            render.Dispose();
            document.Dispose();

            //add barcode
            PdfQRBarcode barcode = new PdfQRBarcode();

            barcode.ErrorCorrectionLevel = PdfErrorCorrectionLevel.High;
            //Set XDimension
            barcode.XDimension = 2.5f;
            //https://localhost:44353/LabTests/Details/
            string endpoint = configuration.GetConnectionString("ServerEndpoint");

            barcode.Text = string.Format("{0}LabTests/Details/{1}", endpoint, Id);
            //Creating new PDF Document
            //PdfDocument doc = new PdfDocument();
            //Adding new page to PDF document
            PdfPage page = pdfDocument.Pages[0];

            //Printing barcode on to the Pdf.
            //barcode.Draw(page, new PointF(25, 70));
            barcode.Draw(page, new PointF(250, 650));

            if (!string.IsNullOrEmpty(tokenId))
            {
                Response.Cookies.Append("fileDownloadToken", tokenId);
            }

            MemoryStream stream = new MemoryStream();

            //document.Save(stream, FormatType.Docx);
            pdfDocument.Save(stream);
            //return File(stream, "application/msword", "Sample.docx");
            return(File(stream.ToArray(), "application/octet-stream", "Draft.pdf"));
            //return RedirectToAction(nameof(Index));
        }