Example #1
0
        public static void TOC_Update()
        {
            // Let's create a simple document.
            DocumentCore dc = new DocumentCore();

            // DocumentCore.Serial = "put your serial here";

            //It's easy to load any document.
            dc = DocumentCore.Load(@"..\..\..\..\..\..\Testing Files\toc.docx");

            // Update TOC (TOC can be updated only after all document content is added).
            var toc = (TableOfEntries)dc.GetChildElements(true, ElementType.TableOfEntries).FirstOrDefault();

            toc.Update();

            // Update TOC's page numbers.
            // Page numbers are automatically updated in that case.
            dc.GetPaginator(new PaginatorOptions()
            {
                UpdateFields = true
            });

            // Save DOCX to a file
            dc.Save(@"..\..\..\..\..\..\Testing Files\TOC_Updated.docx");
            ShowResult(@"..\..\..\..\..\..\Testing Files\TOC_Updated.docx");
        }
Example #2
0
        /// <summary>
        /// How to rasterize a document - save the document pages as images.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/rasterize-save-document-pages-as-picture-net-csharp-vb.php
        /// </remarks>
        static void RasterizeDocument()
        {
            // Rasterizing - it's process of converting the document pages into raster images.
            // In this example we'll show how to rasterize/save a document page into PNG picture.

            string pngFile = @"Result.png";

            // Let's create a simple PDF document.
            DocumentCore dc = new DocumentCore();

            // Add new section.
            Section section = new Section(dc);

            dc.Sections.Add(section);

            // Let's set page size A4.
            section.PageSetup.PaperType         = PaperType.A4;
            section.PageSetup.PageMargins.Left  = LengthUnitConverter.Convert(10, LengthUnit.Millimeter, LengthUnit.Point);
            section.PageSetup.PageMargins.Right = LengthUnitConverter.Convert(10, LengthUnit.Millimeter, LengthUnit.Point);

            // Add any text on 1st page.
            Paragraph par1 = new Paragraph(dc);

            par1.ParagraphFormat.Alignment = HorizontalAlignment.Center;
            section.Blocks.Add(par1);

            // Let's create a characterformat for text in the 1st paragraph.
            CharacterFormat cf = new CharacterFormat()
            {
                FontName = "Verdana", Size = 86, FontColor = new SautinSoft.Document.Color("#FFFF00")
            };

            Run text1 = new Run(dc, "You are welcome!");

            text1.CharacterFormat = cf;
            par1.Inlines.Add(text1);

            // Create the document paginator to get separate document pages.
            DocumentPaginator documentPaginator = dc.GetPaginator(new PaginatorOptions()
            {
                UpdateFields = true
            });

            // To get high-quality image, lets set 300 dpi.
            int dpi = 300;

            // Get the 1st page.
            DocumentPage page = documentPaginator.Pages[0];

            // Rasterize/convert the page into PNG image.
            Bitmap image = page.Rasterize(dpi, SautinSoft.Document.Color.LightGray);

            image.Save(pngFile, System.Drawing.Imaging.ImageFormat.Png);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(pngFile)
            {
                UseShellExecute = true
            });
        }
Example #3
0
        /// <summary>
        /// Insert a picture to custom page and position into existing DOCX document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/insert-picture-jpg-image-to-custom-docx-page-and-position-net-csharp-vb.php
        /// </remarks>
        static void InsertPictureToCustomPageAndPosition()
        {
            // In this example we'll insert the picture to 1st after the word "Sign:".

            string inpFile  = @"..\..\example.docx";
            string outFile  = @"Result.docx";
            string pictFile = @"..\..\picture.jpg";

            DocumentCore      dc = DocumentCore.Load(inpFile);
            DocumentPaginator dp = dc.GetPaginator();

            // Find the text "Sign:" on the 1st page.
            ContentRange cr = dp.Pages[0].Content.Find("Sign:").LastOrDefault();

            if (cr != null)
            {
                Picture pic = new Picture(dc, pictFile);
                cr.End.Insert(pic.Content);
            }
            // Save the document as new DOCX and open it.
            dc.Save(outFile);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile)
            {
                UseShellExecute = true
            });
        }
Example #4
0
        /// <summary>
        /// Rasterizing - save Text document as PNG and JPEG images.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/rasterize-save-text-document-as-png-jpeg-images-net-csharp-vb.php
        /// </remarks>
        static void RasterizeTxtToPicture()
        {
            // In this example we'll how rasterize/save 1st and 2nd pages of Text document
            // as PNG and JPEG images.
            string inputFile = @"..\..\example.txt";
            string jpegFile  = "Result.jpg";
            string pngFile   = "Result.png";
            // The file format is detected automatically from the file extension: ".txt".
            // But as shown in the example below, we can specify TxtLoadOptions as 2nd parameter
            // to explicitly set that a loadable document has Text format.
            DocumentCore dc = DocumentCore.Load(inputFile, new TxtLoadOptions()
            {
                Encoding = System.Text.Encoding.UTF8
            });

            DocumentPaginator documentPaginator = dc.GetPaginator(new PaginatorOptions()
            {
                UpdateFields = true
            });

            int dpi = 300;

            int pagesToRasterize = 2;
            int currentPage      = 1;

            foreach (DocumentPage page in documentPaginator.Pages)
            {
                // Save the page into Bitmap image with specified dpi and background.
                Bitmap picture = page.Rasterize(dpi, SautinSoft.Document.Color.White);

                // Save the Bitmap to a PNG file.
                if (currentPage == 1)
                {
                    picture.Save(pngFile);
                }
                else if (currentPage == 2)
                {
                    // Save the Bitmap to a JPEG file.
                    picture.Save(jpegFile);
                }

                currentPage++;

                if (currentPage > pagesToRasterize)
                {
                    break;
                }
            }

            // Open the results for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(pngFile)
            {
                UseShellExecute = true
            });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(jpegFile)
            {
                UseShellExecute = true
            });
        }
Example #5
0
        /// <summary>
        /// Rasterizing - save PDF document as PNG and JPEG images.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/rasterize-save-pdf-document-as-png-jpeg-images-net-csharp-vb.php
        /// </remarks>
        static void RasterizePdfToPicture()
        {
            // In this example we'll how rasterize/save 1st and 2nd pages of PDF document
            // as PNG and JPEG images.
            string inputFile = @"..\..\example.pdf";
            string jpegFile  = "Result.jpg";
            string pngFile   = "Result.png";

            DocumentCore dc = DocumentCore.Load(inputFile, new PdfLoadOptions()
            {
                DetectTables   = false,
                ConversionMode = PdfConversionMode.Exact
            });

            DocumentPaginator documentPaginator = dc.GetPaginator(new PaginatorOptions()
            {
                UpdateFields = true
            });

            int dpi = 300;

            int pagesToRasterize = 2;
            int currentPage      = 1;

            foreach (DocumentPage page in documentPaginator.Pages)
            {
                // Save the page into Bitmap image with specified dpi and background.
                Bitmap picture = page.Rasterize(dpi, SautinSoft.Document.Color.White);

                // Save the Bitmap to a PNG file.
                if (currentPage == 1)
                {
                    picture.Save(pngFile);
                }
                else if (currentPage == 2)
                {
                    // Save the Bitmap to a JPEG file.
                    picture.Save(jpegFile);
                }

                currentPage++;

                if (currentPage > pagesToRasterize)
                {
                    break;
                }
            }

            // Open the results for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(pngFile)
            {
                UseShellExecute = true
            });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(jpegFile)
            {
                UseShellExecute = true
            });
        }
Example #6
0
        /// <summary>
        /// Loads a document and split it by separate pages. Saves the each page into PDF format.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/split-docx-document-by-pages-in-pdf-format-net-csharp-vb.php
        /// </remarks>
        static void SplitDocumentByPages()
        {
            string            filePath   = @"..\..\example.docx";
            DocumentCore      dc         = DocumentCore.Load(filePath);
            string            folderPath = Path.GetFullPath(@"Result-files");
            DocumentPaginator dp         = dc.GetPaginator();

            for (int i = 0; i < dp.Pages.Count; i++)
            {
                DocumentPage page = dp.Pages[i];
                Directory.CreateDirectory(folderPath);

                // Save the each page to PDF format.
                page.Save(folderPath + @"\Page - " + i.ToString() + ".pdf", SaveOptions.PdfDefault);
            }
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(folderPath)
            {
                UseShellExecute = true
            });
        }
        public void SplitDocumentByPages()
        {
            string       filePath = @"C:\Users\sodrk\Desktop\net\doc.rtf";
            DocumentCore dc       = DocumentCore.Load(filePath);

            DocumentPaginator dp = dc.GetPaginator();

            for (int i = 0; i < dp.Pages.Count; i++)
            {
                DocumentPage page = dp.Pages[i];
                Directory.CreateDirectory(folderPath);

                page.Save(folderPath + @"\Page - " + (i + 1).ToString() + ".pdf", SautinSoft.Document.SaveOptions.PdfDefault);
            }
            LoadPages(dp.Pages.Count);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(folderPath)
            {
                UseShellExecute = true
            });
        }
Example #8
0
        /// <summary>
        /// Loads a document and saves all pages as images.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/save-document-as-image-net-csharp-vb.php
        /// </remarks>
        static void SaveToImage()
        {
            string       filePath   = @"..\..\example.docx";
            DocumentCore dc         = DocumentCore.Load(filePath);
            string       folderPath = Path.GetFullPath(@"Result-files");

            DocumentPaginator dp = dc.GetPaginator();

            for (int i = 0; i < dp.Pages.Count; i++)
            {
                DocumentPage page = dp.Pages[i];
                // For example, set DPI: 72, Background: White.
                Bitmap image = page.Rasterize(72, SautinSoft.Document.Color.White);
                Directory.CreateDirectory(folderPath);
                image.Save(folderPath + @"\Page - " + i.ToString() + ".png", ImageFormat.Png);
            }
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(folderPath)
            {
                UseShellExecute = true
            });
        }
Example #9
0
        /// <summary>
        /// Load a document and save all pages as separate PNG &amp; Jpeg images.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/pagination-save-document-pages-as-png-jpg-jpeg-net-csharp-vb.php
        /// </remarks>
        static void SeparateDocumentToImagePages()
        {
            string            filePath   = @"..\..\example.docx";
            DocumentCore      dc         = DocumentCore.Load(filePath);
            string            folderPath = Path.GetFullPath(@"Result-files");
            DocumentPaginator dp         = dc.GetPaginator();

            for (int i = 0; i < dp.Pages.Count; i++)
            {
                DocumentPage page = dp.Pages[i];
                Directory.CreateDirectory(folderPath);

                // Save the each page as Bitmap.
                Bitmap bmp = page.Rasterize(300, SautinSoft.Document.Color.White);
                // Save the bitmap to PNG and JPEG.
                bmp.Save(folderPath + @"\Page (PNG) - " + (i + 1).ToString() + ".png");
                bmp.Save(folderPath + @"\Page (Jpeg) - " + (i + 1).ToString() + ".jpg");
            }
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(folderPath)
            {
                UseShellExecute = true
            });
        }
Example #10
0
        private void ConvertPdf(string fileName, UploadType type, int announcementId = 0)
        {
            var newFileName = $"{Path.GetFileNameWithoutExtension(fileName)}.jpg";
            var dest        = FilesUtilities.GetRelativePath(fileName, type, announcementId);

            if (announcementId != 0)
            {
                dest = $"{Path.GetDirectoryName(dest)}/{Path.GetFileName(dest)}";
            }
            var newDest = FilesUtilities.GetRelativePdfFile(newFileName, type, announcementId);
            var theFile = Path.Combine(_webRootPath, dest);
            var newFile = Path.Combine(_webRootPath, newDest);

            Path.GetDirectoryName(newFile).CreateDirectory();
            newFile = newFile.SlashConverter();
            DocumentCore      document = DocumentCore.Load(theFile);
            DocumentPaginator dp       = document.GetPaginator(new PaginatorOptions());
            var page = dp.Pages[0];

            using (var image = page.Rasterize(800, Color.White))
            {
                image.Save(newFile);
            }
        }
Example #11
0
        /// <summary>
        /// Creates a new Image document using DocumentBuilder wizard.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/create-image-document-net-csharp-vb.php
        /// </remarks>
        public static void CreateImageUsingDocumentBuilder()
        {
            // Set a path to our document.
            string docPath = @"Result-DocumentBuilder.png";

            // Create a new document and DocumentBuilder.
            DocumentCore    dc = new DocumentCore();
            DocumentBuilder db = new DocumentBuilder(dc);

            // Set page size A4.
            Section section = db.Document.Sections[0];

            section.PageSetup.PaperType = PaperType.A4;

            // Add 1st paragraph with formatted text.
            db.CharacterFormat.FontName  = "Verdana";
            db.CharacterFormat.Size      = 16;
            db.CharacterFormat.FontColor = SautinSoft.Document.Color.Orange;
            db.Write("This is a first line in 1st paragraph!");
            // Add a line break into the 1st paragraph.
            db.InsertSpecialCharacter(SpecialCharacterType.LineBreak);
            // Add 2nd line to the 1st paragraph, create 2nd paragraph.
            db.Writeln("Let's type a second line.");
            // Specify the paragraph alignment.
            (section.Blocks[0] as Paragraph).ParagraphFormat.Alignment = HorizontalAlignment.Center;

            // Add text into the 2nd paragraph.
            db.CharacterFormat.ClearFormatting();
            db.CharacterFormat.Size      = 25;
            db.CharacterFormat.FontColor = SautinSoft.Document.Color.Blue;
            db.CharacterFormat.Bold      = true;
            db.Write("This is a first line in 2nd paragraph.");
            // Insert a line break into the 2nd paragraph.
            db.InsertSpecialCharacter(SpecialCharacterType.LineBreak);
            // Insert 2nd line with own formatting to the 2nd paragraph.
            db.CharacterFormat.Size           = 20;
            db.CharacterFormat.FontColor      = SautinSoft.Document.Color.DarkGreen;
            db.CharacterFormat.UnderlineStyle = UnderlineType.Single;
            db.CharacterFormat.Bold           = false;
            db.Write("This is a second line.");

            // Add a graphics figure into the paragraph.
            db.CharacterFormat.ClearFormatting();
            Shape shape = db.InsertShape(SautinSoft.Document.Drawing.Figure.SmileyFace, new SautinSoft.Document.Drawing.Size(50, 50, LengthUnit.Millimeter));

            // Specify outline and fill.
            shape.Outline.Fill.SetSolid(new SautinSoft.Document.Color("#358CCB"));
            shape.Outline.Width = 3;
            shape.Fill.SetSolid(SautinSoft.Document.Color.Orange);

            // Save the 1st document page to the file in PNG format.
            Bitmap page = dc.GetPaginator().Pages[0].Rasterize(300, SautinSoft.Document.Color.White);

            page.Save(docPath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(docPath)
            {
                UseShellExecute = true
            });
        }
Example #12
0
        /// <summary>
        /// Update table of contents in word document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/update-table-of-contents-in-word-document-net-csharp-vb.php
        /// </remarks>
        public static void TOC()
        {
            string pathFile   = @"..\..\toc.docx";
            string resultFile = "UpdatedTOC.docx";

            // Load a .docx document with TOC.
            DocumentCore dc = DocumentCore.Load(pathFile);

            Paragraph p = new Paragraph(dc);

            p.Content.Start.Insert("I was born in the year 1632, in the city of York, of a good family, though not of that country, " +
                                   "my father being a foreigner of Bremen, who settled first at Hull.  He got a good estate by merchandise, and leaving " +
                                   "off his trade, lived afterwards at York, from whence he had married my mother, whose relations were named Robinson, " +
                                   "a very good family in that country, and from whom I was called Robinson Kreutznaer; but, by the usual corruption " +
                                   "of words in England, we are now called-nay we call ourselves and write our name-Crusoe; and so my companions always " +
                                   "called me. I had two elder brothers, one of whom was lieutenant-colonel to an English regiment of foot in Flanders, " +
                                   "formerly commanded by the famous Colonel Lockhart, and was killed at the battle near Dunkirk against the Spaniards.",

                                   new CharacterFormat()
            {
                Size = 28
            });
            p.ParagraphFormat.Alignment = HorizontalAlignment.Justify;

            // Insert the paragraph as 6th element in the 1st section.
            dc.Sections[0].Blocks.Insert(5, p);

            Paragraph p1 = new Paragraph(dc);

            p1.Content.Start.Insert("That evil influence which carried me first away from my father’s house-which hurried me into the " +
                                    "wild and indigested notion of raising my fortune, and that impressed those conceits so forcibly upon me as to make me " +
                                    "deaf to all good advice, and to the entreaties and even the commands of my father-I say, the same influence, whatever " +
                                    "it was, presented the most unfortunate of all enterprises to my view; and I went on board a vessel bound to the coast " +
                                    "of Africa; or, as our sailors vulgarly called it, a voyage to Guinea. It was my great misfortune that in all these " +
                                    "adventures I did not ship myself as a sailor; when, though I might indeed have worked a little harder than ordinary, " +
                                    "yet at the same time I should have learnt the duty and office of a fore-mast man, and in time might have qualified " +
                                    "myself for a mate or lieutenant, if not for a master.  But as it was always my fate to choose for the worse, so I did " +
                                    "here; for having money in my pocket and good clothes upon my back, I would always go on board in the habit of " +
                                    "a gentleman; and so I neither had any business in the ship, nor learned to do any.",

                                    new CharacterFormat()
            {
                Size = 28
            });
            p1.ParagraphFormat.Alignment = HorizontalAlignment.Justify;

            // Insert the paragraph as 10th element in the 1st section.
            dc.Sections[0].Blocks.Insert(9, p1);

            // Update TOC (TOC can be updated only after all document content is added).
            TableOfEntries toc = (TableOfEntries)dc.GetChildElements(true, ElementType.TableOfEntries).FirstOrDefault();

            toc.Update();

            // Update TOC's page numbers.
            // Page numbers are automatically updated in that case.
            dc.GetPaginator(new PaginatorOptions()
            {
                UpdateFields = true
            });

            // Change default character formatting for all text inside TOC
            CharacterFormat cf = new CharacterFormat();

            cf.Size      = 20;
            cf.FontColor = Color.Blue;
            foreach (Inline inline in toc.GetChildElements(true, ElementType.Run, ElementType.SpecialCharacter))
            {
                if (inline is Run)
                {
                    ((Run)inline).CharacterFormat = cf.Clone();
                }
                else
                {
                    ((SpecialCharacter)inline).CharacterFormat = cf.Clone();
                }
            }

            // Save the document as new DOCX file.
            dc.Save(resultFile);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(resultFile)
            {
                UseShellExecute = true
            });
        }
Example #13
0
        /// <summary>
        /// Create extended table of contents in word document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/create-extended-table-of-contents-in-word-document-net-csharp-vb.php
        /// </remarks>
        public static void ExtendedTOC()
        {
            string resultFile = "Extended-Table-Of-Contents.docx";
            // First of all, create an instance of DocumentCore.
            DocumentCore dc = new DocumentCore();

            // Create and add Heading1 style. For "Chapter 1" and "Chapter 2".
            ParagraphStyle Heading1Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading1, dc);

            Heading1Style.ParagraphFormat.LineSpacing = 3;
            Heading1Style.CharacterFormat.Size        = 18;
            // #358CCB - blue
            Heading1Style.CharacterFormat.FontColor = new Color("#358CCB");
            dc.Styles.Add(Heading1Style);

            // Create and add Heading2 style. For "SupChapter 1-1" and "SubChapter 2-1".
            ParagraphStyle Heading2Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading2, dc);

            Heading2Style.ParagraphFormat.LineSpacing = 2;
            Heading2Style.CharacterFormat.Size        = 14;
            // #FF9900 - orange
            Heading2Style.CharacterFormat.FontColor = new Color("#FF9900");
            dc.Styles.Add(Heading2Style);

            // Create and add TOC style.
            ParagraphStyle TOCStyle = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Subtitle, dc);

            TOCStyle.ParagraphFormat.OutlineLevel = OutlineLevel.BodyText;
            TOCStyle.ParagraphFormat.Alignment    = HorizontalAlignment.Center;
            TOCStyle.CharacterFormat.Bold         = true;
            // #358CCB - blue
            TOCStyle.CharacterFormat.FontColor = new Color("#358CCB");
            dc.Styles.Add(TOCStyle);

            // Add new section.
            Section section = new Section(dc);

            dc.Sections.Add(section);

            // Add TOC Header.
            section.Blocks.Add(
                new Paragraph(dc, "Table of Contents")
            {
                ParagraphFormat = { Style = TOCStyle }
            });

            // Create and add TOC (Table of Contents).
            section.Blocks.Add(new TableOfEntries(dc, FieldType.TOC));

            // Add TOC Ending.
            section.Blocks.Add(
                new Paragraph(dc, "The End")
            {
                ParagraphFormat = { Alignment = HorizontalAlignment.Center, BackgroundColor = Color.Gray }
            });

            // Add the document content (Chapter 1).
            // Add Chapter 1.
            section.Blocks.Add(
                new Paragraph(dc, "Chapter 1")
            {
                ParagraphFormat =
                {
                    Style           = Heading1Style,
                    PageBreakBefore = true
                }
            });

            // Add SubChapter 1-1.
            section.Blocks.Add(
                new Paragraph(dc, String.Format("Subchapter 1-1"))
            {
                ParagraphFormat =
                {
                    Style = Heading2Style
                }
            });

            // Add the content of Chapter 1 / Subchapter 1-1.
            section.Blocks.Add(
                new Paragraph(dc,
                              "«Document.Net» will help you in development of applications which operates with DOCX, RTF, PDF, HTML and Text documents.After adding of the reference to(SautinSoft.Document.dll) - it's 100% C# managed assembly you will be able to create a new document, parse an existing, modify anything what you want.")
            {
                ParagraphFormat = new ParagraphFormat
                {
                    LeftIndentation    = 10,
                    RightIndentation   = 10,
                    SpecialIndentation = 20,
                    LineSpacing        = 20,
                    LineSpacingRule    = LineSpacingRule.Exactly,
                    SpaceBefore        = 20,
                    SpaceAfter         = 20
                }
            });

            // Let's add another page break into.
            section.Blocks.Add(
                new Paragraph(dc,
                              new SpecialCharacter(dc, SpecialCharacterType.PageBreak)));

            // Add the document content (Chapter 2).
            // Add Chapter 2.
            section.Blocks.Add(
                new Paragraph(dc, "Chapter 2")
            {
                ParagraphFormat =
                {
                    Style = Heading1Style
                }
            });

            // Add SubChapter 2-1.
            section.Blocks.Add(
                new Paragraph(dc, String.Format("Subchapter 2-1"))
            {
                ParagraphFormat =
                {
                    Style = Heading2Style
                }
            });

            // Add the content of Chapter 2 / Subchapter 2-1.
            section.Blocks.Add(
                new Paragraph(dc,
                              "Requires only .Net 4.0 or above. Our product is compatible with all .Net languages and supports all Operating Systems where .Net Framework can be used. Note that «Document .Net» is entirely written in managed C#, which makes it absolutely standalone and an independent library. Of course, No dependency on Microsoft Word.")
            {
                ParagraphFormat = new ParagraphFormat
                {
                    LeftIndentation    = 10,
                    RightIndentation   = 10,
                    SpecialIndentation = 20,
                    LineSpacing        = 20,
                    LineSpacingRule    = LineSpacingRule.Exactly,
                    SpaceBefore        = 20,
                    SpaceAfter         = 20
                }
            });

            // Update TOC (TOC can be updated only after all document content is added).
            var tableofcontents = (TableOfEntries)dc.GetChildElements(true, ElementType.TableOfEntries).FirstOrDefault();

            tableofcontents.Update();

            // Apply the style for the TOC.
            foreach (Paragraph par in tableofcontents.Entries)
            {
                par.ParagraphFormat.Style = TOCStyle;
            }

            // Update TOC's page numbers.
            // Page numbers are automatically updated in that case.
            dc.GetPaginator(new PaginatorOptions()
            {
                UpdateFields = true
            });

            // Save the document as DOCX file.
            dc.Save(resultFile);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(resultFile)
            {
                UseShellExecute = true
            });
        }
Example #14
0
        public static void TOC()
        {
            // Let's create a simple document.
            DocumentCore dc = new DocumentCore();
            // DocumentCore.Serial = "put your serial here";

            // Create and add Heading 1 style for TOC.
            ParagraphStyle Heading1Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading1, dc);

            dc.Styles.Add(Heading1Style);

            // Create and add Heading 2 style for TOC.
            ParagraphStyle Heading2Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading2, dc);

            dc.Styles.Add(Heading2Style);

            // Add new section.
            Section section = new Section(dc);

            dc.Sections.Add(section);

            // Add TOC title in the DOCX document.
            section.Blocks.Add(new Paragraph(dc, "Table of Contents"));

            // Create and add new TOC.
            section.Blocks.Add(new TableOfEntries(dc, FieldType.TOC));

            section.Blocks.Add(new Paragraph(dc, "The end."));

            // Let's add a page break into our paragraph.
            section.Blocks.Add(
                new Paragraph(dc,
                              new SpecialCharacter(dc, SpecialCharacterType.PageBreak)));

            // Add document content.
            // Add Chapter 1
            section.Blocks.Add(
                new Paragraph(dc, "Chapter 1")
            {
                ParagraphFormat =
                {
                    Style = Heading1Style
                }
            });

            // Add SubChapter 1-1
            section.Blocks.Add(
                new Paragraph(dc, String.Format("Subchapter 1-1"))
            {
                ParagraphFormat =
                {
                    Style = Heading2Style
                }
            });
            // Add the content of Chapter 1 / Subchapter 1-1
            section.Blocks.Add(
                new Paragraph(dc,
                              "«Document .Net» will help you in development of applications which operates with DOCX, RTF, PDF and Text documents. After adding of the reference to (SautinSoft.Document.dll) - it's 100% C# managed assembly you will be able to create a new document, parse an existing, modify anything what you want."));

            // Let's add an another page break into our paragraph.
            section.Blocks.Add(
                new Paragraph(dc,
                              new SpecialCharacter(dc, SpecialCharacterType.PageBreak)));

            // Add document content.
            // Add Chapter 2
            section.Blocks.Add(
                new Paragraph(dc, "Chapter 2")
            {
                ParagraphFormat =
                {
                    Style = Heading1Style
                }
            });

            // Add SubChapter 2-1
            section.Blocks.Add(
                new Paragraph(dc, String.Format("Subchapter 2-1"))
            {
                ParagraphFormat =
                {
                    Style = Heading2Style
                }
            });

            // Add the content of Chapter 2 / Subchapter 2-1
            section.Blocks.Add(
                new Paragraph(dc,
                              "Requires only .Net 4.0 or above. Our product is compatible with all .Net languages and supports all Operating Systems where .Net Framework can be used. Note that «Document .Net» is entirely written in managed C#, which makes it absolutely standalone and an independent library. Of course, No dependency on Microsoft Word."));

            // Update TOC (TOC can be updated only after all document content is added).
            var toc = (TableOfEntries)dc.GetChildElements(true, ElementType.TableOfEntries).FirstOrDefault();

            toc.Update();

            // Update TOC's page numbers.
            // Page numbers are automatically updated in that case.
            dc.GetPaginator(new PaginatorOptions()
            {
                UpdateFields = true
            });

            // Save DOCX to a file
            dc.Save("Table-Of-Contents.docx");
            ShowResult("Table-Of-Contents.docx");
        }
        private void MenuItem_Click_3(object sender, RoutedEventArgs e)
        {
            TreeViewItem temp = (FoldersTree.SelectedItem as TreeViewItem);

            if (temp == null || (temp.Tag as PathNode).Type != 2)
            {
                return;
            }

            string fullPath = (temp.Tag as PathNode).FullPath;

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.FileName         = System.IO.Path.GetFileNameWithoutExtension(fullPath);
            saveFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(fullPath);
            saveFileDialog.Filter           = "Microsoft Word (DOCX)|*.docx|Rich Text Format (RTF)|*.rtf|Portable Document Format (PDF)|*.pdf|HyperText Markup Language (HTML)|*.html|HyperText Markup Language (HTML) Fixed|*.html|Images (Png)|*.png";
            saveFileDialog.FilterIndex      = (System.IO.Path.GetExtension(fullPath).ToLower() == ".pdf") ? 1 : 3;
            saveFileDialog.AddExtension     = true;
            saveFileDialog.OverwritePrompt  = true;
            saveFileDialog.ValidateNames    = true;

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    System.Windows.Input.Cursor cursor = Mouse.OverrideCursor;
                    string openFile = "";
                    try
                    {
                        Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;

                        DocumentCore dc = DocumentCore.Load(fullPath);

                        switch (saveFileDialog.FilterIndex)
                        {
                        case 4:
                            openFile = saveFileDialog.FileName;
                            dc.Save(saveFileDialog.FileName, new HtmlFlowingSaveOptions());
                            break;

                        case 6:
                        {
                            SautinSoft.Document.DocumentPaginator dp = dc.GetPaginator();
                            string path     = System.IO.Path.GetDirectoryName(saveFileDialog.FileName);
                            string fileName = System.IO.Path.GetFileNameWithoutExtension(saveFileDialog.FileName);
                            for (int idx = 0; idx < dp.Pages.Count; ++idx)
                            {
                                string s = System.IO.Path.Combine(path, fileName + (idx + 1).ToString() + ".png");
                                if (string.IsNullOrEmpty(openFile))
                                {
                                    openFile = s;
                                }
                                dp.Pages[idx].Rasterize(200).Save(s);
                            }
                        }
                        break;

                        default:
                            openFile = saveFileDialog.FileName;
                            dc.Save(saveFileDialog.FileName);
                            break;
                        }

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

                    System.Diagnostics.Process.Start(openFile);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
Example #16
0
        /// <summary>
        /// Creates a new Image document using DOM directly.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/create-image-document-net-csharp-vb.php
        /// </remarks>
        public static void CreateImageUsingDOM()
        {
            // Set a path to our document.
            string docPath = @"Result-DocumentCore.png";

            // Create a new document.
            DocumentCore dc = new DocumentCore();

            // Add new section.
            Section section = new Section(dc);

            dc.Sections.Add(section);

            // Let's set page size A4.
            section.PageSetup.PaperType = PaperType.A4;

            // Add two paragraphs
            Paragraph par1 = new Paragraph(dc);

            par1.ParagraphFormat.Alignment = HorizontalAlignment.Center;
            section.Blocks.Add(par1);

            // Let's create a characterformat for text in the 1st paragraph.
            CharacterFormat cf = new CharacterFormat()
            {
                FontName = "Verdana", Size = 16, FontColor = SautinSoft.Document.Color.Orange
            };
            Run run1 = new Run(dc, "This is a first line in 1st paragraph!");

            run1.CharacterFormat = cf;
            par1.Inlines.Add(run1);

            // Let's add a line break into the 1st paragraph.
            par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak));
            // Copy the formatting.
            Run run2 = run1.Clone();

            run2.Text = "Let's type a second line.";
            par1.Inlines.Add(run2);

            // Add 2nd paragraph.
            Paragraph par2 = new Paragraph(dc, new Run(dc, "This is a first line in 2nd paragraph.", new CharacterFormat()
            {
                Size = 25, FontColor = SautinSoft.Document.Color.Blue, Bold = true
            }));

            section.Blocks.Add(par2);
            SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak);

            par2.Inlines.Add(lBr);
            Run run3 = new Run(dc, "This is a second line.", new CharacterFormat()
            {
                Size = 20, FontColor = SautinSoft.Document.Color.DarkGreen, UnderlineStyle = UnderlineType.Single
            });

            par2.Inlines.Add(run3);

            // Add a graphics figure into the paragraph.
            Shape shape = new Shape(dc, new InlineLayout(new SautinSoft.Document.Drawing.Size(50, 50, LengthUnit.Millimeter)));

            // Specify outline and fill.
            shape.Outline.Fill.SetSolid(new  SautinSoft.Document.Color("#358CCB"));
            shape.Outline.Width = 3;
            shape.Fill.SetSolid(SautinSoft.Document.Color.Orange);
            shape.Geometry.SetPreset(Figure.SmileyFace);
            par2.Inlines.Add(shape);

            // Save the 1st document page to the file in PNG format.
            Bitmap page = dc.GetPaginator().Pages[0].Rasterize(300, SautinSoft.Document.Color.White);

            page.Save(docPath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(docPath)
            {
                UseShellExecute = true
            });
        }
        //public static async Task<List<string>> Converter(Converter m)
        public static async Task <List <string> > Converter()
        {
            List <string> list    = null;
            List <Stream> streams = null;
            string        items   = String.Empty;

            try
            {
                //string filePath = @"C:\Users\emeka\Desktop\docfile.docx";
                string            filePath   = @"docx\Page-0.docx";
                string            folderPath = @"docx";
                DocumentCore      dc         = DocumentCore.Load(filePath);
                DocumentPaginator dp         = dc.GetPaginator();
                //int pageCount = dp.Pages.Count;


                var          html         = string.Empty;
                MemoryStream outputStream = new MemoryStream();
                dc.Save(outputStream, SautinSoft.Document.SaveOptions.DocxDefault);
                //streams.Add(outputStream);

                Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("@31382e332e30PWw2APLjHFJqVBHCGcjP09i81aSl9kjUJ/eeyQ+uJGQ=");

                using (WordDocument mainDocument = new WordDocument(outputStream, FormatType.Automatic))
                {
                    string       _html  = null;
                    MemoryStream stream = new MemoryStream();

                    //Sets the style sheet type
                    mainDocument.SaveOptions.HtmlExportOmitXmlDeclaration = true;
                    mainDocument.SaveOptions.HtmlExportHeadersFooters     = true;
                    mainDocument.Save(stream, FormatType.Html);

                    stream.Position = 0;
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        _html = reader.ReadToEnd();
                    }

                    list.Add(_html);
                }



                //string filePath = @"C:\Users\emeka\Desktop\docfile.docx";
                //string folderPath = @"docx";
                //DocumentCore dc = DocumentCore.Load(filePath);
                //DocumentPaginator dp = dc.GetPaginator();
                //int pageCount = dp.Pages.Count;

                //streams = new List<Stream>();
                //list = new List<string>();

                //for (int i = 0; i < pageCount; i++)
                //{
                //    DocumentPage page = dp.Pages[i];
                //    MemoryStream outputStream = new MemoryStream();
                //    var html = string.Empty;
                //    page.Save(outputStream, SautinSoft.Document.SaveOptions.DocxDefault);

                //    page.Save(folderPath + @"\Page-" + i.ToString() + ".docx", SautinSoft.Document.SaveOptions.DocxDefault);
                //    streams.Add(outputStream);
                //}

                //foreach (var item in streams)
                //{
                //    using (WordDocument mainDocument = new WordDocument(item, FormatType.Automatic))
                //    {
                //        string _html = null;
                //        MemoryStream stream = new MemoryStream();

                //        //Sets the style sheet type
                //        mainDocument.SaveOptions.HtmlExportOmitXmlDeclaration = true;
                //        mainDocument.SaveOptions.HtmlExportHeadersFooters = true;
                //        mainDocument.Save(stream, FormatType.Html);

                //        stream.Position = 0;
                //        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                //        {
                //            _html = reader.ReadToEnd();
                //        }

                //        list.Add(_html);
                //    }
                //}



                // if (!string.IsNullOrEmpty(m.Base64))
                //{
                //var bytes = await Base64ToByteArray(m.Base64);
                //Stream _contents = new MemoryStream(bytes);

                //DocumentCore dc = DocumentCore.Load(_contents, LoadOptions.DocxDefault);
                //DocumentPaginator dp = dc.GetPaginator();
                //int pageCount = dp.Pages.Count;

                //list = new List<string>();
                //for (int i = 0; i < pageCount; i++)
                //{
                //    DocumentPage page = dp.Pages[i];

                //    list.Add(page.Content.ToString());
                //}



                //using (WordDocument mainDocument = new WordDocument(_contents, FormatType.Docx))
                //{
                //    //string rtf = null;
                //    MemoryStream stream = new MemoryStream();
                //    mainDocument.SaveOptions.HtmlExportOmitXmlDeclaration = true;
                //    mainDocument.SaveOptions.HtmlExportHeadersFooters = true;
                //    mainDocument.SaveOptions.OptimizeRtfFileSize = true;

                //    mainDocument.Save(stream, FormatType.Docx);


                //    //DocumentCore dc = DocumentCore.Load(_contents, LoadOptions.DocxDefault);
                //    //DocumentPaginator dp = dc.GetPaginator();
                //    //int pageCount = dp.Pages.Count;
                //    //for (int i = 0; i < pageCount; i++)
                //    //{
                //    //    DocumentPage page = dp.Pages[i];
                //    //}

                //    //stream.Position = 0;
                //    //using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                //    //{
                //    //    rtf = reader.ReadToEnd();
                //    //}

                //    //SautinSoft.RtfToHtml r = new SautinSoft.RtfToHtml();



                //    //string rtfString = File.ReadAllText(rtf);

                //    // Let's store all images inside the HTML document.
                //    //r.ImageStyle.IncludeImageInHtml = true;

                //    //string htmlString = r.ConvertString(rtf);

                //    //list = htmlString;
                //}
                //}
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return(list);
        }
Example #18
0
        /// <summary>
        /// Insert a picture to custom pages into existing DOCX document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/insert-picture-jpg-image-to-custom-docx-page-net-csharp-vb.php
        /// </remarks>
        static void InsertPictureToCustomPages()
        {
            // In this example we'll insert the picture to 1st and 3rd pages
            // of DOCX document into specific positions.

            string inpFile  = @"..\..\example.docx";
            string outFile  = @"Result.docx";
            string pictFile = @"..\..\picture.jpg";

            DocumentCore      dc = DocumentCore.Load(inpFile);
            DocumentPaginator dp = dc.GetPaginator();


            // Step 1: Put the picture to 1st page.

            // Create the Picture object from Jpeg file.
            Picture pict = new Picture(dc, pictFile);

            // Specify the picture size and position.
            pict.Layout = FloatingLayout.Floating(
                new HorizontalPosition(70, LengthUnit.Millimeter, HorizontalPositionAnchor.Margin),
                new VerticalPosition(23, LengthUnit.Millimeter, VerticalPositionAnchor.Margin),
                new Size(LengthUnitConverter.Convert(1, LengthUnit.Inch, LengthUnit.Point),
                         pict.Layout.Size.Height * LengthUnitConverter.Convert(1, LengthUnit.Inch, LengthUnit.Point) / pict.Layout.Size.Width));

            // Put the picture behind the text
            (pict.Layout as FloatingLayout).WrappingStyle = WrappingStyle.BehindText;

            // Find the 1st Element in the 1st page.
            Element e1 = dp.Pages[0].ElementsOnPage.FirstOrDefault(e => e is Run);

            // Insert the picture at this Element.
            e1.Content.End.Insert(pict.Content);


            // Step 2: Put the picture to 3rd page.
            if (dp.Pages.Count >= 3)
            {
                // Find the 1st Element on the 3rd page.
                Element e2 = dp.Pages[2].ElementsOnPage.FirstOrDefault(e => e is Run);

                // Create another picture
                Picture pict2 = new Picture(dc, pictFile);
                pict2.Layout = FloatingLayout.Floating(
                    new HorizontalPosition(10, LengthUnit.Millimeter, HorizontalPositionAnchor.Margin),
                    new VerticalPosition(20, LengthUnit.Millimeter, VerticalPositionAnchor.Margin),
                    new Size(LengthUnitConverter.Convert(1, LengthUnit.Inch, LengthUnit.Point),
                             pict2.Layout.Size.Height * LengthUnitConverter.Convert(1, LengthUnit.Inch, LengthUnit.Point) / pict2.Layout.Size.Width)
                    );
                (pict2.Layout as FloatingLayout).WrappingStyle = WrappingStyle.BehindText;

                // Insert the picture at this Element.
                e2.Content.End.Insert(pict2.Content);
            }
            // Save the document as new DOCX and open it.
            dc.Save(outFile);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile)
            {
                UseShellExecute = true
            });
        }