Example #1
0
        /// <summary>
        /// Creates a new document using DOM and ContentRange and saves it in a desired format.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/create-document.php
        /// </remarks>
        static void CreateUsingContentRange()
        {
            // Create a new document.
            DocumentCore dc = new DocumentCore();

            // Insert the formatted text into the document.
            dc.Content.End.Insert("Hello World!", new CharacterFormat()
            {
                FontName = "Verdana", Size = 65.5f, FontColor = Color.Orange
            });

            // Save the document in HTML format.
            string outFile = @"ContentRange.html";

            dc.Save(outFile, new HtmlFixedSaveOptions()
            {
                Title = "ContentRange"
            });

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile)
            {
                UseShellExecute = true
            });
        }
Example #2
0
        /// <summary>
        /// Creates a new document and saves it as Text using MemoryStream.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-text-net-csharp-vb.php
        /// </remarks>
        static void SaveToTextStream()
        {
            // There variables are necessary only for demonstration purposes.
            byte[] fileData = null;
            string filePath = @"Result-stream.txt";

            // Assume we already have a document 'dc'.
            DocumentCore dc = new DocumentCore();

            dc.Content.End.Insert("Hey Guys and Girls!");

            // Let's save our document to a MemoryStream.
            using (MemoryStream ms = new MemoryStream())
            {
                dc.Save(ms, new TxtSaveOptions());
                fileData = ms.ToArray();
            }
            File.WriteAllBytes(filePath, fileData);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath)
            {
                UseShellExecute = true
            });
        }
Example #3
0
        /// <summary>
        /// Convert RTF to DOCX (using Stream).
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/convert-rtf-to-docx-in-csharp-vb.php
        /// </remarks>
        static void ConvertFromStream()
        {
            // We need files only for demonstration purposes.
            // The conversion process will be done completely in memory.
            string inpFile = @"..\..\example.rtf";
            string outFile = @"ResultStream.docx";

            byte[] inpData = File.ReadAllBytes(inpFile);
            byte[] outData = null;

            using (MemoryStream msInp = new MemoryStream(inpData))
            {
                // Load a document.
                DocumentCore dc = DocumentCore.Load(msInp, new RtfLoadOptions());

                // Save the document to DOCX format.
                using (MemoryStream outMs = new MemoryStream())
                {
                    dc.Save(outMs, new DocxSaveOptions());
                    outData = outMs.ToArray();
                }
                // Show the result for demonstration purposes.
                if (outData != null)
                {
                    File.WriteAllBytes(outFile, outData);
                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile)
                    {
                        UseShellExecute = true
                    });
                }
            }
        }
Example #4
0
        /// <summary>
        /// Inserts a new paragraph into an existing PDF document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/insert-paragraphs-to-pdf-document-net-csharp-vb.php
        /// </remarks>
        static void InsertParagraph()
        {
            string inpFile = @"..\..\example.pdf";
            string outFile = @"Result.pdf";

            DocumentCore dc = DocumentCore.Load(inpFile);
            Paragraph    p  = new Paragraph(dc);

            p.Content.Start.Insert("Alexander Pushkin was a great russian romantic poet " +
                                   "and writer who is considered by a lot of people as the best russian poet and the founder " +
                                   "of contemporary russian literature.",
                                   new CharacterFormat()
            {
                Size = 20, FontName = "Verdana", FontColor = new Color("#358CCB")
            });
            p.ParagraphFormat.Alignment = HorizontalAlignment.Justify;

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

            dc.Save(outFile);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile)
            {
                UseShellExecute = true
            });
        }
Example #5
0
        /// <summary>
        /// Deletes a specific paragraphs in an existing DOCX and save it as new PDF.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/delete-paragraphs-in-docx-document-net-csharp-vb.php
        /// </remarks>
        static void DeleteParagraphs()
        {
            string filePath   = @"..\..\example.docx";
            string fileResult = @"Result.pdf";

            DocumentCore dc = DocumentCore.Load(filePath);

            // Note, remove paragraphs only inside the first section.
            Section section = dc.Sections[0];

            // Let's remove all paragraphs containing the text "Jack".
            for (int i = 0; i < section.Blocks.Count; i++)
            {
                if (section.Blocks[i].Content.Find("Jack").Count() > 0)
                {
                    section.Blocks.RemoveAt(i);
                    i--;
                }
            }
            dc.Save(fileResult);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath)
            {
                UseShellExecute = true
            });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(fileResult)
            {
                UseShellExecute = true
            });
        }
Example #6
0
        /// <summary>
        /// How to replace a hyperlink URL by a new address.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/hyperlinks-replace-url-csharp-vb-net.php
        /// </remarks>
        public static void ReplaceHyperlinksURL()
        {
            // Let us say, we've a DOCX document.
            // And we've to replace the all URLs by the custom.
            // Furthermore, let's save the result as PDF.

            string inpFile = @"..\..\Hyperlinks example.docx";
            string outFile = @"Result - URL.pdf";

            // Let's open our document.
            DocumentCore dc = DocumentCore.Load(inpFile);

            // Specify the custom URL.
            string customURL = "https://www.sautinsoft.com";

            // Loop by all hyperlinks and replace the URL (address).
            foreach (Hyperlink hpl in dc.GetChildElements(true, ElementType.Hyperlink))
            {
                hpl.Address = customURL;
            }

            // Save our document back, but in PDF format.
            dc.Save(outFile, new PdfSaveOptions()
            {
                Compliance = PdfCompliance.PDF_14
            });

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile)
            {
                UseShellExecute = true
            });
        }
Example #7
0
        public void CreatePDFFIleReport()
        {
            CreateWordFileReport(Program.expencesList, Program.incomeList);
            var document = DocumentCore.Load(@"C:\Users\user\source\repos\ZenMoney\ZenMoney\bin\Debug\OutputDocument.docx");

            document.Save(@"C:\Users\user\source\repos\ZenMoney\ZenMoney\bin\Debug/report.pdf");
        }
Example #8
0
        /// <summary>
        /// Convert PDF to RTF (file to file).
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/convert-pdf-to-rtf-in-csharp-vb.php
        /// </remarks>
        static void ConvertFromFile()
        {
            string inpFile = @"..\..\example.pdf";
            string outFile = @"Result.rtf";

            // Specifying PdfLoadOptions we explicitly set that a loadable document is PDF.
            PdfLoadOptions pdfLO = new PdfLoadOptions()
            {
                // 'false' - means to load vector graphics as is. Don't transform it to raster images.
                RasterizeVectorGraphics = false,

                // The PDF format doesn't have real tables, in fact it's a set of orthogonal graphic lines.
                // In case of 'true' the component will detect and recreate tables from graphic lines.
                DetectTables = false,

                // 'true' - Load embedded fonts from PDF document, even if the font with the same name is installed in your System.
                PreserveEmbeddedFonts = false
            };

            DocumentCore dc = DocumentCore.Load(inpFile, pdfLO);

            dc.Save(outFile);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile)
            {
                UseShellExecute = true
            });
        }
Example #9
0
        static void savefile(string text)
        {
            DocumentCore dc = new DocumentCore();

            SaveFileDialog savedi = new SaveFileDialog();

            List <string> alltext = text.Split(Environment.NewLine.ToCharArray()).ToList();

            savedi.Filter = "Docx files (*.docx)|*.docx|Text files (*.txt)|*.txt|All files (*.*)|*.*";
            if (savedi.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string extension = Path.GetExtension(savedi.FileName);
                if (extension == ".docx")
                {
                    dc.Content.End.Insert(text);
                    dc.Save(savedi.FileName, new DocxSaveOptions());
                }
                else
                {
                    if (extension == ".txt")
                    {
                        using (StreamWriter sw = new StreamWriter(savedi.FileName))
                        {
                            foreach (string line in alltext)
                            {
                                sw.WriteLine(line);
                            }
                        }
                    }
                }
            }
        }
Example #10
0
            public Table GetContent(DocumentCore docx, bool details)
            {
                Table table = new Table(docx);

                table.TableFormat.PreferredWidth = new TableWidth(100, TableWidthUnit.Percentage);

                table.Rows.Add(GetTitleAndDate(docx));

                TableCell cell = new TableCell(docx)
                {
                    ColumnSpan = 2
                };

                cell.Blocks.Add(Template.CreateParagraph(docx, Ult.GetOgr(Organization, Location), Template.FormatOganization));

                if (Topic != null)
                {
                    cell.Blocks.Add(Template.CreateParagraph(docx, Topic, Template.FormatNormal));
                }

                if (details)
                {
                    if (Description.Count > 0)
                    {
                        foreach (String item in Description)
                        {
                            cell.Blocks.Add(Template.CreateList(docx, item, Template.FormatNormal));
                        }
                    }
                }
                table.Rows.Add(new TableRow(docx, cell));


                return(table);
            }
Example #11
0
        /// <summary>
        /// Create a document and insert a paragraph using DocumentBuilder.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/documentbuilder-inserting-paragraph.php
        /// </remarks>

        static void InsertingParagraph()
        {
            DocumentCore    dc = new DocumentCore();
            DocumentBuilder db = new DocumentBuilder(dc);

            string resultPath = @"result.docx";

            // Insert the formatted text into the document using DocumentBuilder.
            db.CharacterFormat.FontName        = "Verdana";
            db.CharacterFormat.Size            = 16.5f;
            db.CharacterFormat.AllCaps         = true;
            db.CharacterFormat.Italic          = true;
            db.CharacterFormat.FontColor       = Color.Orange;
            db.ParagraphFormat.LeftIndentation = 30;
            db.Writeln("This paragraph has a Left Indentation of 30 points.");
            db.ParagraphFormat.SpecialIndentation = 50;
            db.Writeln("This paragraph retains the Left Indentation of 30 points and is supplemented by the first-line indent of 50 points.");

            // This method will clear all directly set formatting values.
            db.ParagraphFormat.ClearFormatting();
            db.CharacterFormat.ClearFormatting();
            db.Write("All directly set text and paragraph formatting values were cleared using DocumentBuilder.");

            // Save the document to the file in DOCX format.
            dc.Save(resultPath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(resultPath)
            {
                UseShellExecute = true
            });
        }
Example #12
0
        /// <summary>
        /// Create a document and add paragraphs as content and as element.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/element-manipulation.php
        /// </remarks>
        static void ElementManipulation()
        {
            string filePath = @"Result.docx";

            // Let's create a new document.
            DocumentCore dc  = new DocumentCore();
            Paragraph    par = new Paragraph(dc, "This is the first paragraph.");

            // Insert the clone of our Paragraph using ContentRange.
            dc.Content.End.Insert(par.Content);

            // Add our Paragraph in Block collection as Element.
            dc.Sections[0].Blocks.Add(par);

            // Again, insert the clone of our Paragraph using ContentRange.
            dc.Content.End.Insert(par.Content);

            // Change text in our Paragraph
            (par.Inlines[0] as Run).Text = "Now we are in the second paragraph.";

            // Find 3rd paragraph and change text in it.
            ((par.NextSibling as Paragraph).Inlines[0] as Run).Text = "This is the third paragraph.";

            // Save our document.
            dc.Save(filePath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath)
            {
                UseShellExecute = true
            });
        }
Example #13
0
        public TableRow Content(DocumentCore docx)
        {
            Table table = new Table(docx);

            table.TableFormat.PreferredWidth = new TableWidth(100, TableWidthUnit.Percentage);

            TableRow[] row = new TableRow[2];
            for (int r = 0; r < 2; r++)
            {
                row[r] = new TableRow(docx);
                for (int c = 0; c < 3; c++)
                {
                    TableCell subCell = new TableCell(docx);
                    subCell.CellFormat.Borders.SetBorders(MultipleBorderTypes.None, BorderStyle.None, Color.Auto, 0);
                    subCell.CellFormat.PreferredWidth = new TableWidth(35, TableWidthUnit.Percentage);
                    subCell.Blocks.Add(contacts[r * 3 + c].GetContent(docx));
                    subCell.ColumnSpan = 1;

                    row[r].Cells.Add(subCell);
                }
                table.Rows.Add(row[r]);
            }

            TableCell cell = new TableCell(docx, table);

            cell.CellFormat.PreferredWidth = new TableWidth(100, TableWidthUnit.Percentage);
            cell.ColumnSpan = 2;

            return(new TableRow(docx, cell));
        }
        private void buttonGetDocument_Click(object sender, EventArgs e)
        {
            SetDefaultDataTable();
            List <string>  lS1 = new List <string>(); // Лист всех элементов из .docx
            OpenFileDialog opf = new OpenFileDialog();

            opf.Filter = "Word 2007 Documents (*.docx)|*.docx";
            if (opf.ShowDialog() == DialogResult.OK)
            {
                string        filename = opf.FileName; // Path to Docx file.
                DocumentCore  dc       = DocumentCore.Load(filename);
                StringBuilder sb       = new StringBuilder();
                // Get content of each Run where the text color is Red.
                foreach (Paragraph run in dc.GetChildElements(true, ElementType.Paragraph))
                {
                    string   str     = run.Content.ToString();
                    string[] strpath = str.Split('\r'); // Не удавалось расплитить по '\r\n'. Расплититл по '\r'.
                    str = strpath[0];                   // Хвост отбросил.
                    if (str != "")                      // Проверка на какой-либо элемент. В том числе и филды.
                    {
                        lS1.Add(str);                   // Список всех элементов документа, где каждый первый - Id, а каждый второй - дата.
                    }
                }
                ToTable TTable    = new ToTable();
                string  FieldId   = lS1[0];
                string  FieldData = lS1[1];
                lS1.Remove(FieldId);
                lS1.Remove(FieldData);
                DataTable DT = TTable.ConvertToTable(lS1, FieldId, FieldData, GetPathAndName(opf.FileName)[1]);
                dataGridView1.DataSource = DT;
            }
        }
Example #15
0
        /// <summary>
        /// Creates a simple Pie Chart in a document.
        /// </summary>
        /// <remarks>
        /// See details at: https://sautinsoft.com/products/document/help/net/developer-guide/reporting-create-simple-pie-chart-in-pdf-net-csharp-vb.php
        /// </remarks>
        public static void PieChart()
        {
            DocumentCore dc = new DocumentCore();

            FloatingLayout fl = new FloatingLayout(
                new HorizontalPosition(20f, LengthUnit.Millimeter, HorizontalPositionAnchor.LeftMargin),
                new VerticalPosition(15f, LengthUnit.Millimeter, VerticalPositionAnchor.TopMargin),
                new Size(200, 200));

            Dictionary <string, double> chartData = new Dictionary <string, double>
            {
                { "Potato", 25 },
                { "Carrot", 16 },
                { "Salad", 10 },
                { "Cucumber", 10 },
                { "Tomato", 4 },
                { "Rice", 30 },
                { "Onion", 5 }
            };

            AddPieChart(dc, fl, chartData, true, "%", true);


            // Let's save the document into PDF format (you may choose another).
            string filePath = @"Pie Chart.pdf";

            dc.Save(filePath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath)
            {
                UseShellExecute = true
            });
        }
Example #16
0
        /// <summary>
        /// Creates a new document with a paragraph.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/paragraph.php
        /// </remarks>
        static void Paragraph()
        {
            DocumentCore dc = new DocumentCore();

            string filePath = @"Result-file.docx";

            dc.Sections.Add(
                new Section(dc,
                            new Paragraph(dc, "Text is right aligned.")
            {
                ParagraphFormat = new ParagraphFormat
                {
                    Alignment = HorizontalAlignment.Right
                }
            },
                            new Paragraph(dc, "This paragraph has the following properties: Left indentation is 15 points, right indentation is 5 centimeters, hanging indentation is 10 points, line spacing is exactly 14 points, space before and space after are 10 points.")
            {
                ParagraphFormat = new ParagraphFormat
                {
                    LeftIndentation    = 15,
                    RightIndentation   = LengthUnitConverter.Convert(5, LengthUnit.Centimeter, LengthUnit.Point),
                    SpecialIndentation = 10,
                    LineSpacing        = 14,
                    LineSpacingRule    = LineSpacingRule.Exactly,
                    SpaceBefore        = 10,
                    SpaceAfter         = 10
                }
            }));

            dc.Save(filePath);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath)
            {
                UseShellExecute = true
            });
        }
Example #17
0
        public string Read(string path)
        {
            var dc      = DocumentCore.Load(path);
            var runList = dc.GetChildElements(true, ElementType.Run).Select(x => x.Content.ToString());

            return(string.Concat(runList));
        }
Example #18
0
        /// <summary>
        /// Creates a new document and saves it as PDF file.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-pdf-net-csharp-vb.php
        /// </remarks>
        static void SaveToPdfFile()
        {
            // Assume we already have a document 'dc'.
            DocumentCore dc = new DocumentCore();

            dc.Content.End.Insert("Hey Guys and Girls!\nFrom file.", new CharacterFormat()
            {
                FontColor = Color.Green, Size = 20
            });

            string filePath = @"Result-file.pdf";

            dc.Save(filePath, new PdfSaveOptions()
            {
                Compliance       = PdfCompliance.PDF_A1a,
                PaginatorOptions = new PaginatorOptions()
                {
                    PreserveFormFields = true
                }
            });

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath)
            {
                UseShellExecute = true
            });
        }
Example #19
0
        /// <summary>
        /// Open a document and delete some content.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/delete-content-net-csharp-vb.php
        /// </remarks>
        public static void DeleteContent()
        {
            string loadPath = @"..\..\example.docx";
            string savePath = "Result.docx";

            DocumentCore dc = DocumentCore.Load(loadPath);

            // Remove the text "This" from all paragraphs in 1st section.
            foreach (Paragraph par in dc.Sections[0].GetChildElements(true, ElementType.Paragraph))
            {
                var findText = par.Content.Find("This");

                if (findText != null)
                {
                    foreach (ContentRange cr in findText)
                    {
                        cr.Delete();
                    }
                }
            }
            dc.Save(savePath);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(loadPath)
            {
                UseShellExecute = true
            });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(savePath)
            {
                UseShellExecute = true
            });
        }
Example #20
0
        /// <summary>
        /// Creates a new document and saves it as PDF/A using MemoryStream.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-pdf-net-csharp-vb.php
        /// </remarks>
        static void SaveToPdfStream()
        {
            // There variables are necessary only for demonstration purposes.
            byte[] fileData = null;
            string filePath = @"Result-stream.pdf";

            // Assume we already have a document 'dc'.
            DocumentCore dc = new DocumentCore();

            dc.Content.End.Insert("Hey Guys and Girls!\nFrom MemoryStream.", new CharacterFormat()
            {
                FontColor = Color.Orange, Size = 20
            });

            // Let's save our document to a MemoryStream.
            using (MemoryStream ms = new MemoryStream())
            {
                dc.Save(ms, new PdfSaveOptions()
                {
                    PageIndex  = 0,
                    PageCount  = 1,
                    Compliance = PdfCompliance.PDF_A1a
                });
                fileData = ms.ToArray();
            }
            File.WriteAllBytes(filePath, fileData);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath)
            {
                UseShellExecute = true
            });
        }
Example #21
0
        private static Section GetSectionForUser(DocumentCore docx, Users user)
        {
            var section = new Section(docx)
            {
                PageSetup = { PaperType = PaperType.A4 }
            };

            var par = new Paragraph(docx);

            section.Blocks.Add(par);

            foreach (var str in new[]
                     { user.Index, user.Address, $"{user.LastName} {user.FirstName} {user.MiddleName}" })
            {
                if (string.IsNullOrEmpty(str))
                {
                    continue;
                }
                var run = new Run(docx, str);
                par.Inlines.Add(run);
                par.Inlines.Add(new SpecialCharacter(docx, SpecialCharacterType.LineBreak));
            }

            par.ParagraphFormat.Alignment = HorizontalAlignment.Right;

            return(section);
        }
Example #22
0
        /// <summary>
        /// Delete a specific text from DOCX document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/delete-text-from-docx-document-net-csharp-vb.php
        /// </remarks>
        static void DeleteText()
        {
            string       filePath     = @"..\..\example.docx";
            string       fileResult   = @"Result.pdf";
            string       textToDelete = "document";
            DocumentCore dc           = DocumentCore.Load(filePath);

            int countDel = 0;

            foreach (ContentRange cr in dc.Content.Find(textToDelete).Reverse())
            {
                cr.Delete();
                countDel++;
            }
            Console.WriteLine("The text: \"" + textToDelete + "\" - was deleted " + countDel.ToString() + " time(s).");
            Console.ReadKey();

            dc.Save(fileResult);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath)
            {
                UseShellExecute = true
            });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(fileResult)
            {
                UseShellExecute = true
            });
        }
Example #23
0
        /// <summary>
        /// Merge all paragraphs into a single in an existing PDF document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/merge-paragraphs-in-pdf-document-net-csharp-vb.php
        /// </remarks>
        static void MergeParagraphs()
        {
            string       inpFile = @"..\..\example.pdf";
            string       outFile = @"Result.pdf";
            DocumentCore dc      = DocumentCore.Load(inpFile);

            Paragraph firstPar = dc.GetChildElements(true, ElementType.Paragraph).First() as Paragraph;

            int lastIndex = firstPar.Inlines.Count;

            foreach (Paragraph par in dc.GetChildElements(true, ElementType.Paragraph).Reverse().Where(p => p != firstPar))
            {
                int last = lastIndex;
                foreach (Inline inline in par.Inlines)
                {
                    firstPar.Inlines.Insert(last++, inline.Clone(true));
                }
                par.Content.Delete();
            }

            dc.Save(outFile);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(inpFile)
            {
                UseShellExecute = true
            });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile)
            {
                UseShellExecute = true
            });
        }
Example #24
0
        /// <summary>
        /// Creates a new document and applies formatting and styles.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/formatting-and-styles.php
        /// </remarks>
        static void FormattingAndStyles()
        {
            string docxPath = @"FormattingAndStyles.docx";

            // Let's create a new document.
            DocumentCore dc   = new DocumentCore();
            Run          run1 = new Run(dc, "This is Run 1 with character format Green. ");
            Run          run2 = new Run(dc, "This is Run 2 with style Red.");

            // Create a new character style.
            CharacterStyle redStyle = new CharacterStyle("Red");

            redStyle.CharacterFormat.FontColor = Color.Red;
            dc.Styles.Add(redStyle);

            // Apply the direct character formatting.
            run1.CharacterFormat.FontColor = Color.DarkGreen;

            // Apply only the style.
            run2.CharacterFormat.Style = redStyle;

            dc.Content.End.Insert(run1.Content);
            dc.Content.End.Insert(run2.Content);

            // Save our document into DOCX format.
            dc.Save(docxPath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(docxPath)
            {
                UseShellExecute = true
            });
        }
Example #25
0
        /// <summary>
        /// Find and replace a text using ContentRange.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/find-replace-content-net-csharp-vb.php
        /// </remarks>
        public static void FindAndReplace()
        {
            // Path to a loadable document.
            string loadPath = @"..\..\critique.docx";

            // Load a document intoDocumentCore.
            DocumentCore dc = DocumentCore.Load(loadPath);

            Regex regex = new Regex(@"bean", RegexOptions.IgnoreCase);

            //Find "Bean" and Replace everywhere on "Joker :-)"
            // Please note, Reverse() makes sure that action replace not affects to Find().
            foreach (ContentRange item in dc.Content.Find(regex).Reverse())
            {
                item.Replace("Joker");
            }

            // Save our document into PDF format.
            string savePath = "Replaced.pdf";

            dc.Save(savePath, new PdfSaveOptions());

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(loadPath)
            {
                UseShellExecute = true
            });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(savePath)
            {
                UseShellExecute = true
            });
        }
Example #26
0
        public static void ExtractPictures()
        {
            // Path to a document where to extract pictures.
            string filePath = @"..\..\..\..\..\..\Testing Files\example.pdf";

            // Directory to store extracted pictures:
            DirectoryInfo imageDirectory = new DirectoryInfo(Path.GetDirectoryName(filePath));
            string        imageTemplate  = "Picture";

            // Here we store extracted images.
            List <ImageData> imageInventory = new List <ImageData>();

            // Load the document.
            DocumentCore dc = DocumentCore.Load(filePath);

            // Extract all images from document, skip duplicates.
            foreach (Picture pict in dc.GetChildElements(true, ElementType.Picture))
            {
                // Let's avoid the adding of duplicates.
                if (imageInventory.Exists((img => (img.GetStream().Length == pict.ImageData.GetStream().Length))) == false)
                {
                    imageInventory.Add(pict.ImageData);
                }
            }

            // Save and show all images.
            for (int i = 0; i < imageInventory.Count; i++)
            {
                string imagePath = Path.Combine(imageDirectory.FullName, String.Format("{0}{1}.{2}", imageTemplate, i + 1, imageInventory[i].Format.ToString().ToLower()));
                File.WriteAllBytes(imagePath, imageInventory[i].GetStream().ToArray());
                System.Diagnostics.Process.Start(imagePath);
            }
        }
Example #27
0
        /// <summary>
        /// How to get a content from a document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/get-content-net-csharp-vb.php
        /// </remarks>
        public static void GetContent()
        {
            // Path to an input document.
            string documentPath = @"..\..\example.docx";

            DocumentCore dc = DocumentCore.Load(documentPath);

            StringBuilder sb = new StringBuilder();

            // Get content of each paragraph in the document.
            foreach (Paragraph par in dc.GetChildElements(true, ElementType.Paragraph))
            {
                // The property 'Content' returns the content as ContentRange.
                // Get content and append it into StringBuilder.
                sb.AppendFormat("Paragraph: {0}", par.Content.ToString());
                sb.AppendLine();
            }

            // Get content of each Run where the text color is Red.
            foreach (Run run in dc.GetChildElements(true, ElementType.Run))
            {
                if (run.CharacterFormat.FontColor == Color.Red)
                {
                    // The property 'Content' returns the content as ContentRange.
                    // Get content and append it into StringBuilder.
                    sb.AppendFormat("Red color: {0}", run.Content.ToString());
                    sb.AppendLine();
                }
            }
            Console.WriteLine(sb.ToString());
            Console.ReadKey();
        }
Example #28
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 #29
0
        /// <summary>
        /// Replace all Run elements with Bold formatting to Italic and mark them by yellow.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/manipulation.php
        /// </remarks>
        static void Manipulation()
        {
            string       filePath       = @"..\..\example.docx";
            DocumentCore dc             = DocumentCore.Load(filePath);
            string       filePathResult = @"Result-file.pdf";

            foreach (Run run in dc.GetChildElements(true, ElementType.Run))
            {
                if (run.CharacterFormat.Bold == true)
                {
                    run.CharacterFormat.Bold            = false;
                    run.CharacterFormat.Italic          = true;
                    run.CharacterFormat.BackgroundColor = Color.Yellow;
                }
            }
            dc.Save(filePathResult);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath)
            {
                UseShellExecute = true
            });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePathResult)
            {
                UseShellExecute = true
            });
        }
Example #30
0
        /// <summary>
        /// How to delete all hyperlink objects.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/hyperlinks-delete-url-csharp-vb-net.php
        /// </remarks>
        public static void DeleteHyperlinksObjects()
        {
            // Let us say, we've a DOCX document.
            // And we've to remove the hyperlink objects.

            string inpFile = @"..\..\Hyperlinks example.docx";
            string outFile = @"Result - Delete Hyperlinks completely.pdf";

            // Let's open our document.
            DocumentCore dc = DocumentCore.Load(inpFile);

            // Loop by all hyperlinks and replace the URL (address).
            foreach (Hyperlink hpl in dc.GetChildElements(true, ElementType.Hyperlink).Reverse())
            {
                hpl.ParentCollection.Remove(hpl);
            }

            // Save our document back, but in PDF format.
            dc.Save(outFile, new PdfSaveOptions()
            {
                Compliance = PdfCompliance.PDF_14
            });

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile)
            {
                UseShellExecute = true
            });
        }