static void Main()
    {
        // If using Professional version, put your serial key below.
        SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

        var workbook = ExcelFile.Load("IllustrationsAndShapes.xlsx");

        var sb = new StringBuilder();

        var worksheet = workbook.Worksheets[0];

        sb.AppendFormat("Sheet left margin is: {0} pixels.", Math.Round(LengthUnitConverter.Convert(worksheet.PrintOptions.LeftMargin, LengthUnit.Inch, LengthUnit.Pixel)));
        sb.AppendLine();

        sb.AppendFormat("Width of column A is: {0} pixels.", Math.Round(LengthUnitConverter.Convert(worksheet.Columns[0].Width, LengthUnit.ZeroCharacterWidth256thPart, LengthUnit.Pixel)));
        sb.AppendLine();

        sb.AppendFormat("Height of row 1 is: {0} pixels.", Math.Round(LengthUnitConverter.Convert(worksheet.Rows[0].Height, LengthUnit.Twip, LengthUnit.Pixel)));
        sb.AppendLine();

        var picture = worksheet.Pictures[1];

        sb.AppendFormat("Image width x height is: {0} centimeters x {1} centimeters.",
                        Math.Round(picture.Position.GetWidth(LengthUnit.Centimeter), 2),
                        Math.Round(picture.Position.GetHeight(LengthUnit.Centimeter), 2));

        Console.WriteLine(sb.ToString());
    }
Esempio n. 2
0
        static void dataEntry(ref ExcelWorksheet sheet, ref Data data, ref string[] yearMonths)
        {
            string[]  header = new string[] { "Month", "Sales" };
            const int pos    = 7;

            // +7 for the merged cells , +1 for header.
            for (int i = pos; i < data._period + 1 + pos; i++)
            {
                for (int j = 1, k = header.Length + 1; j < k; j++)
                {
                    // For Header.
                    if (i == pos)
                    {
                        sheet.Cells[i, j].Value             = header[j - 1];
                        sheet.Cells[i, j].Style.Font.Weight = ExcelFont.BoldWeight;
                        sheet.Columns[j].Width = (int)LengthUnitConverter.Convert(3, LengthUnit.Centimeter, LengthUnit.ZeroCharacterWidth256thPart);
                    }
                    else
                    {
                        if (j == 1 && i <= data._period + pos)
                        {
                            // Minus one for zero Index and another because of j.
                            sheet.Cells[i, j].Value = yearMonths[(data.bMonth - 2) + i - pos];
                            sheet.Columns[j].Width  = (int)LengthUnitConverter.Convert(3, LengthUnit.Centimeter, LengthUnit.ZeroCharacterWidth256thPart);
                        }
                        else if (j == 2 && i <= data._period + pos)
                        {
                            sheet.Cells[i, j].Style.NumberFormat = "\"$\"#,##0";
                            sheet.Cells[i, j].Value = data.sales[(i - 1 - pos)];
                        }
                    }
                    sheet.Cells[i, j].Style.HorizontalAlignment = HorizontalAlignmentStyle.Center;
                }
            }
        }
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        DocumentModel document = DocumentModel.Load("Reading.docx");

        StringBuilder sb = new StringBuilder();

        sb.AppendLine("Page size (width X height):");

        double width  = document.Sections[0].PageSetup.PageWidth;
        double height = document.Sections[0].PageSetup.PageHeight;

        foreach (LengthUnit unit in Enum.GetValues(typeof(LengthUnit)))
        {
            sb.AppendFormat(
                "{0} X {1} {2}",
                LengthUnitConverter.Convert(width, LengthUnit.Point, unit),
                LengthUnitConverter.Convert(height, LengthUnit.Point, unit),
                unit.ToString().ToLowerInvariant());

            sb.AppendLine();
        }

        Console.WriteLine(sb.ToString());
    }
Esempio n. 4
0
        /// <summary>
        /// How to convert between different units.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/unit-conversion.php
        public static void UsingUnitConversion()
        {
            DocumentCore dc = new DocumentCore();

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

            s1.PageSetup.PageWidth          = LengthUnitConverter.Convert(100, LengthUnit.Millimeter, LengthUnit.Point);
            s1.PageSetup.PageHeight         = LengthUnitConverter.Convert(1, LengthUnit.Inch, LengthUnit.Point);
            s1.PageSetup.PageMargins.Left   = LengthUnitConverter.Convert(0.3, LengthUnit.Centimeter, LengthUnit.Point);
            s1.PageSetup.PageMargins.Top    = LengthUnitConverter.Convert(7, LengthUnit.Pixel, LengthUnit.Point);
            s1.PageSetup.PageMargins.Right  = LengthUnitConverter.Convert(100, LengthUnit.Twip, LengthUnit.Point);
            s1.PageSetup.PageMargins.Bottom = LengthUnitConverter.Convert(5, LengthUnit.Millimeter, LengthUnit.Point);

            dc.Sections.Add(s1);
            s1.Content.Start.Insert("You are welcome!", new CharacterFormat()
            {
                FontColor = Color.Orange, Size = 36
            });

            dc.Save("Result.docx");

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("Result.docx")
            {
                UseShellExecute = true
            });
        }
Esempio n. 5
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
            });
        }
Esempio n. 6
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
            });
        }
Esempio n. 7
0
        /// <summary>
        /// Create a new table with rows and cells merged by vertical (rowspan) and horizontal (colspan).
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/table-with-merged-rows-and-cells.php
        /// </remarks>
        public static void MergeRowsAndCellsInTable()
        {
            DocumentCore dc = new DocumentCore();

            Table table = new Table(dc,
                                    new TableRow(dc,
                                                 new TableCell(dc, new Paragraph(dc, "Cell 1-1")),
                                                 new TableCell(dc, new Paragraph(dc, "Cell 1-2")),
                                                 new TableCell(dc, new Paragraph(dc, "Cell 1-3")),
                                                 new TableCell(dc, new Paragraph(dc, "Cell 1-4"))),

                                    new TableRow(dc,
                                                 new TableCell(dc, new Paragraph(dc, "Cell 2-1 -> 3-2"))
            {
                RowSpan    = 2,
                ColumnSpan = 2
            },
                                                 new TableCell(dc, new Paragraph(dc, "Cell 2-3 -> 2-4"))
            {
                ColumnSpan = 2
            }),

                                    new TableRow(dc,
                                                 new TableCell(dc)
            {
                ColumnSpan = 2
            },
                                                 new TableCell(dc, new Paragraph(dc, "Cell 3-3")),
                                                 new TableCell(dc, new Paragraph(dc, "Cell 3-4"))),

                                    new TableRow(dc,
                                                 new TableCell(dc, new Paragraph(dc, "Cell 4-1"))),
                                    new TableRow(dc,
                                                 new TableCell(dc, new Paragraph(dc, "Cell 5-1"))));

            table.TableFormat.DefaultCellPadding = new Padding(10, LengthUnit.Pixel);

            // Set the table width to 10 cm and convert it to points.
            double tableWidthInPoints = LengthUnitConverter.Convert(10, LengthUnit.Centimeter, LengthUnit.Point);

            table.TableFormat.PreferredWidth = new TableWidth(tableWidthInPoints, TableWidthUnit.Point);
            for (int r = 0; r < table.Rows.Count; r++)
            {
                for (int c = 0; c < table.Rows[r].Cells.Count; c++)
                {
                    TableCell cell = table.Rows[r].Cells[c];
                    cell.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Dashed, Color.Black, 1);
                    cell.CellFormat.BackgroundColor = new Color("#FFCC00");
                }
            }

            dc.Sections.Add(new Section(dc, table));

            dc.Save("MergedTableCells.docx");
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("MergedTableCells.docx")
            {
                UseShellExecute = true
            });
        }
Esempio n. 8
0
        // This sample shows how to work with shapes.
        public static void Shapes()
        {
            string pictPath     = @"..\..\..\..\..\..\Testing Files\image1.jpg";
            string documentPath = @"Shapes.docx";

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

            // Create shape 1 with fill and outline.
            Shape shp1 = new Shape(dc, Layout.Floating(
                                       new HorizontalPosition(25f, LengthUnit.Millimeter, HorizontalPositionAnchor.LeftMargin),
                                       new VerticalPosition(20f, LengthUnit.Millimeter, VerticalPositionAnchor.TopMargin),
                                       new Size(200, 100)
                                       ));

            // Specify outline and fill using a picture.
            shp1.Outline.Fill.SetSolid(Color.DarkGreen);
            shp1.Outline.Width = 2;

            // Set fill for this shape.
            shp1.Fill.SetSolid(Color.Orange);

            // Create shape 2 with some text inside, 100mm*20mm.
            Shape shp2 = new Shape(dc, Layout.Floating(
                                       new HorizontalPosition(100f, LengthUnit.Millimeter, HorizontalPositionAnchor.LeftMargin),
                                       new VerticalPosition(20f, LengthUnit.Millimeter, VerticalPositionAnchor.TopMargin),
                                       new Size(LengthUnitConverter.Convert(100f, LengthUnit.Millimeter, LengthUnit.Point),
                                                LengthUnitConverter.Convert(20f, LengthUnit.Millimeter, LengthUnit.Point))
                                       ));

            // Specify outline and fill using a picture.
            shp2.Outline.Fill.SetSolid(Color.LightGray);
            shp2.Outline.Width = 0.5;

            // Create a new paragraph with a formatted text.
            Paragraph p    = new Paragraph(dc);
            Run       run1 = new Run(dc, "Welcome to International Software Developer conference!");

            run1.CharacterFormat.FontName = "Helvetica";
            run1.CharacterFormat.Size     = 14f;
            run1.CharacterFormat.Italic   = true;
            p.Inlines.Add(run1);

            // Add the paragraph into the shp2.Text property.
            shp2.Text.Blocks.Add(p);

            // Add our shapes into the document.
            dc.Content.End.Insert(shp1.Content);
            dc.Content.End.Insert(shp2.Content);

            // Save the document to DOCX format.
            dc.Save(documentPath);

            // Open the result for demonstation purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(documentPath)
            {
                UseShellExecute = true
            });
        }
Esempio n. 9
0
        public string SignFile(string base64, string userSignature, double x, double y)
        {
            byte[] file   = Convert.FromBase64String(base64);
            Stream stream = new MemoryStream(file);

            ComponentInfo.SetLicense("FREE-LIMITED-KEY");
            ComponentInfo.FreeLimitReached += (sender, e) => e.FreeLimitReachedAction = FreeLimitReachedAction.ContinueAsTrial;


            DocumentModel document = DocumentModel.Load(stream, LoadOptions.PdfDefault);

            //            DocumentModel document = DocumentModel.Load(@"c:\users\matth\documents\visual studio 2017\Projects\SignMe3\SignMe3\wwwroot\resources\file.pdf");

            var section = new Section(document);

            document.Sections.Add(section);

            Paragraph paragraph = new Paragraph(document);

            section.Blocks.Add(paragraph);


            var pathToResources = @"c:\users\matth\documents\visual studio 2017\Projects\SignMe3\SignMe3\wwwroot\images\";


            var    shapeSize = new Size(2, 1, LengthUnit.Centimeter);
            var    topmargin = LengthUnitConverter.Convert(document.Sections[0].PageSetup.PageMargins.Left, LengthUnit.Point, LengthUnit.Pixel);
            double width     = LengthUnitConverter.Convert(document.Sections[0].PageSetup.PageWidth, LengthUnit.Point, LengthUnit.Pixel);
            double height    = LengthUnitConverter.Convert(document.Sections[0].PageSetup.PageHeight, LengthUnit.Point, LengthUnit.Pixel);

            var picture = new Picture(document, new MemoryStream(System.IO.File.ReadAllBytes(Path.Combine(pathToResources, "Matt Signature.png"))), PictureFormat.Png,
                                      new FloatingLayout(
                                          new HorizontalPosition(x, LengthUnit.Pixel, HorizontalPositionAnchor.LeftMargin),
                                          new VerticalPosition(y - topmargin, LengthUnit.Pixel, VerticalPositionAnchor.TopMargin), shapeSize)
            {
                WrappingStyle = TextWrappingStyle.InFrontOfText
            }, ShapeType.Rectangle);

            picture.Outline.Width = 1;
            picture.Outline.Fill.SetSolid(Color.Blue);

            // Fill is visible because picture contains transparent pixels.
            picture.Fill.SetSolid(Color.Orange);
            paragraph.Inlines.Add(picture);

            document.Content.Start.InsertRange(paragraph.Content);

            byte[] fileContents;
            var    options = SaveOptions.PdfDefault;

            // Save document to DOCX format in byte array.
            using (var memoryStream = new MemoryStream())
            {
                document.Save(memoryStream, options);
                fileContents = memoryStream.ToArray();
            }
            return(Convert.ToBase64String(fileContents));
        }
Esempio n. 10
0
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        DocumentModel document = new DocumentModel();

        Section section = new Section(document,
                                      new Paragraph(document,
                                                    new Run(document, "First line"),
                                                    new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                                                    new Run(document, "Second line"),
                                                    new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                                                    new Run(document, "Third line")),
                                      new Paragraph(document,
                                                    new SpecialCharacter(document, SpecialCharacterType.ColumnBreak),
                                                    new Run(document, "First line"),
                                                    new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                                                    new Run(document, "Second line"),
                                                    new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                                                    new Run(document, "Third line")));

        PageSetup pageSetup = section.PageSetup;

        // Specify text columns.
        pageSetup.TextColumns = new TextColumnCollection(2)
        {
            LineBetween  = true,
            EvenlySpaced = false
        };
        pageSetup.TextColumns[0].Width = LengthUnitConverter.Convert(1, LengthUnit.Inch, LengthUnit.Point);
        pageSetup.TextColumns[1].Width = LengthUnitConverter.Convert(2.3, LengthUnit.Inch, LengthUnit.Point);

        // Specify paper type.
        pageSetup.PaperType = PaperType.A5;

        document.Sections.Add(section);

        // Specify line numbering.
        document.Sections.Add(
            new Section(document,
                        new Paragraph(document,
                                      new Run(document, "First line"),
                                      new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                                      new Run(document, "Second line"),
                                      new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                                      new Run(document, "Third line")))
        {
            PageSetup = new PageSetup()
            {
                PaperType = PaperType.A5,
                LineNumberRestartSetting = LineNumberRestartSetting.NewPage
            }
        });

        document.Save("Page Setup.docx");
    }
        public void ExportErrorsWord(List <List <string> > Errors, string name)
        {
            Section section = new Section(dc);

            dc.Sections.Add(section);
            section.PageSetup.PaperType = PaperType.A4;
            Paragraph par = new Paragraph(dc);

            section.Blocks.Add(par);
            par.ParagraphFormat.Alignment = HorizontalAlignment.Center;
            Run run1 = new Run(dc, name);

            run1.CharacterFormat = new CharacterFormat()
            {
                FontName = "Times New Roman", Size = 18.0, FontColor = new Color(112, 173, 71)
            };
            par.Inlines.Add(run1);

            Paragraph p = new Paragraph(dc);

            p.ParagraphFormat.Alignment = HorizontalAlignment.Left;
            section.Blocks.Add(p);
            section.PageSetup.PageMargins = new PageMargins()
            {
                Top    = LengthUnitConverter.Convert(5, LengthUnit.Millimeter, LengthUnit.Point),
                Right  = LengthUnitConverter.Convert(5, LengthUnit.Millimeter, LengthUnit.Point),
                Bottom = LengthUnitConverter.Convert(5, LengthUnit.Millimeter, LengthUnit.Point),
                Left   = LengthUnitConverter.Convert(5, LengthUnit.Millimeter, LengthUnit.Point)
            };
            int data = 1;

            foreach (List <string> c in Errors)
            {
                foreach (string e in c)
                {
                    string template = "{0}. Помилка. {1}";
                    string message  = string.Format(template, data, e);
                    p.Content.End.Insert(message, new CharacterFormat()
                    {
                        Size = 14.0, FontColor = Color.Black
                    });
                    p.ParagraphFormat.SpaceAfter = 0;
                    p.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak));
                    p.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak));
                    data++;
                }
            }

            string filePath = @"C:/2 курс/ Errors.docx";

            dc.Save(filePath);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath)
            {
                UseShellExecute = true
            });
        }
Esempio n. 12
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            #region//Utils
            //String Builder
            StringBuilder sb = new StringBuilder();

            //Collector
            Collector collector = new Collector();

            //UnitConvertor
            LengthUnitConverter converter = new LengthUnitConverter();

            // Application context.
            var uidoc = commandData.Application.ActiveUIDocument;
            var doc   = uidoc.Document;
            #endregion

            #region//Check if we are in the Revit project , not in family one.
            if (doc.IsFamilyDocument)
            {
                Message.Display("Can't use command in family document", WindowType.Warning);
                return(Result.Cancelled);
            }
            #endregion

            #region//create new directory
            string append      = "schedules ";
            string pathName    = doc.PathName.ToString();
            string title       = doc.Title.ToString();
            int    titleLength = title.Length + 4;
            string newpath     = pathName.Remove(pathName.Length - titleLength, titleLength);

            string folder = newpath + append + DateTime.Now.ToString("yyyMMdd HH'u'mm'm'");
            Directory.CreateDirectory(folder);
            //sb.Append(folder);
            #endregion

            #region//ViewSchedule collector
            List <View> List_ViewSchedules = collector.GetViewSchedules(doc, ViewType.Schedule);
            //sb.Append("\n"+ List_ViewSchedules);
            #endregion

            #region//Export Options
            ViewScheduleExportOptions options = new ViewScheduleExportOptions();
            #endregion

            #region//Export Schedules
            foreach (ViewSchedule V in List_ViewSchedules)
            {
                V.Export(folder, V.Name + ".csv", options);
            }
            #endregion

            //TaskDialog.Show("TEST", sb.ToString());
            return(Result.Succeeded);
        }
Esempio n. 13
0
        /// <summary>
        /// This sample shows how to specify a paragraph formatting.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/paragraph-format.php
        public static void ParagraphFormatting()
        {
            string documentPath = @"ParagraphFormatting.docx";

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

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

            dc.Sections.Add(s);

            // Paragraph 1.
            Paragraph p = new Paragraph(dc, "First paragraph!");

            dc.Sections[0].Blocks.Add(p);

            p.ParagraphFormat.Alignment  = HorizontalAlignment.Left;
            p.ParagraphFormat.SpaceAfter = 20.0;
            p.ParagraphFormat.Borders.Add(MultipleBorderTypes.All, BorderStyle.Single, Color.Orange, 2f);

            // Paragraph 2.
            dc.Content.End.Insert("\nThis is a second paragraph.", new CharacterFormat()
            {
                FontName = "Calibri", Size = 16.0, FontColor = Color.Black, Bold = true
            });
            (dc.Sections[0].Blocks[1] as Paragraph).ParagraphFormat.Alignment = HorizontalAlignment.Center;

            // Create multiple paragraphs.
            for (int i = 0; i < 10; i++)
            {
                Paragraph pN = new Paragraph(dc, String.Format("Paragraph {0}. ", i + 1));
                dc.Sections[0].Blocks.Add(pN);

                pN.Content.End.Insert(new SpecialCharacter(dc, SpecialCharacterType.Tab).Content);
                Run run = new Run(dc, "Hello!");
                run.CharacterFormat.FontColor = Color.White;
                pN.Content.End.Insert(run.Content);

                pN.ParagraphFormat.BackgroundColor = new Color((int)(0xFF358CCB * (i + 1)));
                pN.ParagraphFormat.SpaceBefore     = LengthUnitConverter.Convert(1, LengthUnit.Centimeter, LengthUnit.Point);
                pN.ParagraphFormat.SpaceAfter      = LengthUnitConverter.Convert(10, LengthUnit.Millimeter, LengthUnit.Point);
            }

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

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(documentPath)
            {
                UseShellExecute = true
            });
        }
Esempio n. 14
0
        /// <summary>
        /// How apply formatting for table cells.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/tablecell-format.php
        /// </remarks>
        static void TableCellFormatting()
        {
            string filePath = @"TableCellFormatting.docx";

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

            // Add new table.
            Table  table = new Table(dc);
            double width = LengthUnitConverter.Convert(100, LengthUnit.Millimeter, LengthUnit.Point);

            table.TableFormat.PreferredWidth = new TableWidth(width, TableWidthUnit.Point);
            table.TableFormat.Borders.SetBorders(MultipleBorderTypes.Inside | MultipleBorderTypes.Outside,
                                                 BorderStyle.Single, Color.Black, 1);
            dc.Sections.Add(new Section(dc, table));

            TableRow row = new TableRow(dc);

            row.RowFormat.Height = new TableRowHeight(50, HeightRule.Exact);
            table.Rows.Add(row);

            // Create a cells with formatting: borders, background color, vertical alignment and text direction.
            TableCell cell = new TableCell(dc, new Paragraph(dc, "Cell 1"));

            cell.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Blue, 1);
            cell.CellFormat.BackgroundColor = Color.Yellow;
            row.Cells.Add(cell);

            row.Cells.Add(new TableCell(dc, new Paragraph(dc, "Cell 2"))
            {
                CellFormat = new TableCellFormat()
                {
                    VerticalAlignment = VerticalAlignment.Center
                }
            });

            row.Cells.Add(new TableCell(dc, new Paragraph(dc, "Cell 3"))
            {
                CellFormat = new TableCellFormat()
                {
                    TextDirection = TextDirection.BottomToTop
                }
            });

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

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath)
            {
                UseShellExecute = true
            });
        }
Esempio n. 15
0
        public static void ConvertPointsTo()
        {
            foreach (LengthUnit unit in Enum.GetValues(typeof(LengthUnit)))
            {
                string s = string.Format("1 point = {0} {1}",
                                         LengthUnitConverter.Convert(1, LengthUnit.Point, unit),
                                         unit.ToString().ToLowerInvariant());

                Console.WriteLine(s);
            }
            Console.ReadLine();
        }
Esempio n. 16
0
        public async Task OutputValueChanged()
        {
            if (OutputValue == LengthUnitConverter.Convert(InputValue, (LengthUnits)SelectedInputUnit.Id, (LengthUnits)SelectedOutputUnit.Id))
            {
                //do nothing
            }
            else
            {
                InputValue = LengthUnitConverter.Convert(OutputValue, (LengthUnits)SelectedOutputUnit.Id, (LengthUnits)SelectedInputUnit.Id);
            }

            //throw new System.NotImplementedException();
        }
Esempio n. 17
0
        public static Table CreateTable(DocumentCore dc, int rows, int columns, float widthMm)
        {
            // Let's create a plain table: 2x3, 100 mm of width.
            Table  table = new Table(dc);
            double width = LengthUnitConverter.Convert(widthMm, LengthUnit.Millimeter, LengthUnit.Point);

            table.TableFormat.PreferredWidth = new TableWidth(width, TableWidthUnit.Point);
            table.TableFormat.Alignment      = HorizontalAlignment.Center;

            int counter = 0;

            // Add rows.
            for (int r = 0; r < rows; r++)
            {
                TableRow row = new TableRow(dc);

                // Add columns.
                for (int c = 0; c < columns; c++)
                {
                    TableCell cell = new TableCell(dc);

                    // Set cell formatting and width.
                    cell.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Dotted, Color.Black, 1.0);

                    // Set the same width for each column.
                    cell.CellFormat.PreferredWidth = new TableWidth(width / columns, TableWidthUnit.Point);

                    if (counter % 2 == 1)
                    {
                        cell.CellFormat.BackgroundColor = new Color("#358CCB");
                    }

                    row.Cells.Add(cell);

                    // Let's add a paragraph with text into the each column.
                    Paragraph p = new Paragraph(dc);
                    p.ParagraphFormat.Alignment   = HorizontalAlignment.Center;
                    p.ParagraphFormat.SpaceBefore = LengthUnitConverter.Convert(3, LengthUnit.Millimeter, LengthUnit.Point);
                    p.ParagraphFormat.SpaceAfter  = LengthUnitConverter.Convert(3, LengthUnit.Millimeter, LengthUnit.Point);

                    p.Content.Start.Insert(String.Format("{0}", (char)(counter + 'A')), new CharacterFormat()
                    {
                        FontName = "Arial", FontColor = new Color("#3399FF"), Size = 12.0
                    });
                    cell.Blocks.Add(p);
                    counter++;
                }
                table.Rows.Add(row);
            }
            return(table);
        }
Esempio n. 18
0
        public static void UsingUnitConversion()
        {
            DocumentCore dc = new DocumentCore();
            // Add new section.
            Section sectFirst = new Section(dc);

            sectFirst.PageSetup.PageMargins = new PageMargins()
            {
                Top    = LengthUnitConverter.Convert(50, LengthUnit.Millimeter, LengthUnit.Point),
                Right  = LengthUnitConverter.Convert(1, LengthUnit.Inch, LengthUnit.Point),
                Bottom = LengthUnitConverter.Convert(10, LengthUnit.Millimeter, LengthUnit.Point),
                Left   = LengthUnitConverter.Convert(2, LengthUnit.Centimeter, LengthUnit.Point)
            };
        }
Esempio n. 19
0
        /// <summary>
        /// Working with text columns.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/text-columns.php
        /// </remarks>
        public static void TextColumns()
        {
            string documentPath = @"TextColumns.docx";

            // Let's create a document with 4 columns.
            DocumentCore dc = new DocumentCore();

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

            dc.Sections.Add(s);

            s.PageSetup.PageMargins = new PageMargins()
            {
                Top    = LengthUnitConverter.Convert(5, LengthUnit.Millimeter, LengthUnit.Point),
                Right  = LengthUnitConverter.Convert(5, LengthUnit.Millimeter, LengthUnit.Point),
                Bottom = LengthUnitConverter.Convert(5, LengthUnit.Millimeter, LengthUnit.Point),
                Left   = LengthUnitConverter.Convert(5, LengthUnit.Millimeter, LengthUnit.Point)
            };

            s.PageSetup.TextColumns = new TextColumnCollection(4);
            s.PageSetup.TextColumns.EvenlySpaced = false;
            s.PageSetup.TextColumns[0].Width     = LengthUnitConverter.Convert(60, LengthUnit.Millimeter, LengthUnit.Point);
            s.PageSetup.TextColumns[1].Width     = LengthUnitConverter.Convert(20, LengthUnit.Millimeter, LengthUnit.Point);
            s.PageSetup.TextColumns[2].Width     = LengthUnitConverter.Convert(60, LengthUnit.Millimeter, LengthUnit.Point);
            s.PageSetup.TextColumns[3].Width     = LengthUnitConverter.Convert(20, LengthUnit.Millimeter, LengthUnit.Point);

            // Fill our columns by any text.
            string text = "Shrek and Donkey arrive at Farquaad's palace in Duloc, where they end up in a tournament. The winner gets the \"privilege\" of rescuing Fiona so that Farquaad may marry her. ";

            for (int i = 0; i < 22; i++)
            {
                s.Content.End.Insert(text, new CharacterFormat()
                {
                    FontName = "Arial", Size = 12
                });
            }

            (s.Blocks[0] as Paragraph).ParagraphFormat.Alignment = HorizontalAlignment.Justify;

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

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(documentPath)
            {
                UseShellExecute = true
            });
        }
Esempio n. 20
0
        private TableCell AddCellToDOCXTable(string text, ref DocumentCore docx, ref TableRow tableRow)
        {
            TableCell tableRowCell = new TableCell(docx);

            tableRowCell.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Black, 1.0);
            tableRow.Cells.Add(tableRowCell);
            Paragraph paragraph = new Paragraph(docx);

            paragraph.ParagraphFormat.Alignment   = HorizontalAlignment.Center;
            paragraph.ParagraphFormat.SpaceBefore = LengthUnitConverter.Convert(3, LengthUnit.Millimeter, LengthUnit.Point);
            paragraph.ParagraphFormat.SpaceAfter  = LengthUnitConverter.Convert(3, LengthUnit.Millimeter, LengthUnit.Point);;
            paragraph.Content.Start.Insert(String.Format("{0}", text));
            tableRowCell.Blocks.Add(paragraph);

            return(tableRowCell);
        }
        private void CREATETXT_Click(object sender, RoutedEventArgs e)
        {
            FileInfo TableFile = new FileInfo("TableFile.rtf");

            DocumentCore    dc = new DocumentCore();
            DocumentBuilder db = new DocumentBuilder(dc);

            db.TableFormat.PreferredWidth = new TableWidth(LengthUnitConverter.Convert(7, LengthUnit.Inch, LengthUnit.Point), TableWidthUnit.Point);
            db.CellFormat.Padding         = new Padding(5, LengthUnit.Point);
            db.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, SautinSoft.Document.Color.Black, 1);


            db.InsertCell();
            db.Write("№ п.п.");
            db.InsertCell();
            db.Write("Ответственный исполнитель\t");
            db.InsertCell();
            db.Write("Количество неисполненных входящих документов\t");
            db.InsertCell();
            db.Write("Количество неисполненных письменных обращений граждан\t");
            db.InsertCell();
            db.Write("Общее количество документов и обращений\t");
            db.EndRow();

            for (int i = 0; i < TableList.Count; i++)
            {
                db.InsertCell();
                db.Write(TableList[i].Id.ToString());
                db.InsertCell();
                db.Write(TableList[i].Name);
                db.InsertCell();
                db.Write(TableList[i].RKK_Count.ToString());
                db.InsertCell();
                db.Write(TableList[i].Appeal_Count.ToString());
                db.InsertCell();
                db.Write(TableList[i].RKK_Plus_Appeal_Count.ToString());
                db.EndRow();
            }
            db.EndTable();
            dc.Save(TableFile.FullName);

            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(TableFile.FullName)
            {
                UseShellExecute = true
            });
        }
Esempio n. 22
0
        /// <summary>
        /// Creates a new document with shape containing a text and picture.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/pictures-and-shapes.php
        /// </remarks>
        static void PictureAndShape()
        {
            string filePath  = @"Shape.docx";
            string imagePath = @"..\..\image.jpg";

            DocumentCore dc = new DocumentCore();

            // 1. Shape with text.
            Shape shapeWithText = new Shape(dc, Layout.Floating(new HorizontalPosition(1, LengthUnit.Inch, HorizontalPositionAnchor.Page),
                                                                new VerticalPosition(2, LengthUnit.Inch, VerticalPositionAnchor.Page),
                                                                new Size(LengthUnitConverter.Convert(6, LengthUnit.Inch, LengthUnit.Point), LengthUnitConverter.Convert(1.5d, LengthUnit.Centimeter, LengthUnit.Point))));

            (shapeWithText.Layout as FloatingLayout).WrappingStyle = WrappingStyle.InFrontOfText;
            shapeWithText.Text.Blocks.Add(new Paragraph(dc, new Run(dc, "This is the text in shape.", new CharacterFormat()
            {
                Size = 30
            })));
            shapeWithText.Outline.Fill.SetEmpty();
            shapeWithText.Fill.SetSolid(Color.Orange);
            dc.Content.End.Insert(shapeWithText.Content);

            // 2. Picture with FloatingLayout:
            // Floating layout means that the Picture (or Shape) is positioned by coordinates.
            Picture pic = new Picture(dc, imagePath);

            pic.Layout = FloatingLayout.Floating(
                new HorizontalPosition(50, LengthUnit.Millimeter, HorizontalPositionAnchor.Page),
                new VerticalPosition(20, LengthUnit.Millimeter, VerticalPositionAnchor.TopMargin),
                new Size(LengthUnitConverter.Convert(10, LengthUnit.Centimeter, LengthUnit.Point),
                         LengthUnitConverter.Convert(10, LengthUnit.Centimeter, LengthUnit.Point))
                );

            // Set the wrapping style.
            (pic.Layout as FloatingLayout).WrappingStyle = WrappingStyle.BehindText;

            // Add our picture into the section.
            dc.Content.End.Insert(pic.Content);

            dc.Save(filePath);

            // Show the result.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath)
            {
                UseShellExecute = true
            });
        }
Esempio n. 23
0
        public static void plotGraph(List <String> coordinateX, List <String> coordinateY)
        {
            // If using Professional version, put your serial key below.
            SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

            var workbook  = new ExcelFile();
            var worksheet = workbook.Worksheets.Add("Chart");

            // Add data which will be used by the Excel chart.
            worksheet.Cells["A1"].Value = "X";
            for (var i = 0; i < coordinateX.Count; i++)
            {
                worksheet.Cells["A2"].Value = int.Parse(coordinateX[0]);
                worksheet.Cells["A3"].Value = int.Parse(coordinateX[1]);
                worksheet.Cells["A4"].Value = int.Parse(coordinateX[2]);
                worksheet.Cells["A5"].Value = int.Parse(coordinateX[3]);
            }

            worksheet.Cells["B1"].Value = "Y";
            for (var i = 0; i < coordinateY.Count; i++)
            {
                worksheet.Cells["B2"].Value = int.Parse(coordinateY[0]);
                worksheet.Cells["B3"].Value = int.Parse(coordinateY[1]);
                worksheet.Cells["B4"].Value = int.Parse(coordinateY[2]);
                worksheet.Cells["B5"].Value = int.Parse(coordinateY[3]);
            }

            // Set header row and formatting.
            worksheet.Rows[0].Style.Font.Weight = ExcelFont.BoldWeight;
            worksheet.Columns[0].Width          = (int)LengthUnitConverter.Convert(3, LengthUnit.Centimeter, LengthUnit.ZeroCharacterWidth256thPart);
            //worksheet.Columns[1].Style.NumberFormat = "\"$\"#,##0";

            // Make entire sheet print on a single page.
            worksheet.PrintOptions.FitWorksheetWidthToPages  = 1;
            worksheet.PrintOptions.FitWorksheetHeightToPages = 1;

            // Create Excel chart and select data for it.
            var chart = worksheet.Charts.Add(ChartType.Line, "D2", "M25");

            chart.SelectData(worksheet.Cells.GetSubrangeAbsolute(0, 0, 4, 1), true);

            workbook.Save("Chart.xlsx");
        }
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        var document  = DocumentModel.Load("Reading.docx");
        var pageSetup = document.Sections[0].PageSetup;

        double widthInPoints  = pageSetup.PageWidth;
        double heightInPoints = pageSetup.PageHeight;

        Console.WriteLine("Document's page size in different units:");

        foreach (LengthUnit unit in Enum.GetValues(typeof(LengthUnit)))
        {
            double convertedWidth  = LengthUnitConverter.Convert(widthInPoints, LengthUnit.Point, unit);
            double convertedHeight = LengthUnitConverter.Convert(heightInPoints, LengthUnit.Point, unit);
            Console.WriteLine($"{convertedWidth} x {convertedHeight} {unit.ToString().ToLowerInvariant()}");
        }
    }
Esempio n. 25
0
        /// <summary>
        /// Get a Picture size, Change it and Save the document back.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/get-and-change-picture-size-in-docx-csharp-vb-net.php
        /// </remarks>
        public static void GetAndChangePictureSize()
        {
            // Path to a document where to extract pictures.
            string inpFile = @"..\..\example.docx";
            string outFile = "Result.docx";


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

            // Get the physical size of the first picture from the document.
            Picture pict = dc.GetChildElements(true, ElementType.Picture).FirstOrDefault() as Picture;
            Size    size = pict.Layout.Size;

            Console.WriteLine("The 1st picture has this size:\r\n");
            Console.WriteLine("W: {0}, H: {1} (In points)", size.Width, size.Height);
            Console.WriteLine("W: {0}, H: {1} (In pixels)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Pixel),
                              LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Pixel));
            Console.WriteLine("W: {0:F2}, H: {1:F2} (In mm)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Millimeter),
                              LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Millimeter));
            Console.WriteLine("W: {0:F2}, H: {1:F2} (In cm)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Centimeter),
                              LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Centimeter));
            Console.WriteLine("W: {0:F2}, H: {1:F2} (In inches)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Inch),
                              LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Inch));

            Console.WriteLine("\r\nNow let\'s increase the picture size in x1.5 times. Press any key ...");
            Console.ReadKey();

            // Note, we don't change the physical picture size  we only scale/stretch the it.
            pict.Layout.Size = new Size(size.Width * 1.5, size.Height * 1.5);

            // Save the document as a new docx file.
            dc.Save(outFile);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile)
            {
                UseShellExecute = true
            });
        }
Esempio n. 26
0
        /// <summary>
        /// Removes the old header/footer and inserts a new one into an existing PDF document.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/remove-header-and-footer-in-pdf-net-csharp-vb.php
        /// </remarks>
        static void ReplaceHeader()
        {
            string       inpFile = @"..\..\somebody.pdf";
            string       outFile = "With new Header.pdf";
            DocumentCore dc      = DocumentCore.Load(inpFile);

            // Create new header with formatted text.
            HeaderFooter header = new HeaderFooter(dc, HeaderFooterType.HeaderDefault);

            header.Content.Start.Insert("Modified : 1 April 2020", new CharacterFormat()
            {
                Size = 14.0, FontColor = Color.DarkGreen
            });
            // Add 10 mm from Top before new header.
            (header.Blocks[0] as Paragraph).ParagraphFormat.SpaceBefore = LengthUnitConverter.Convert(10, LengthUnit.Millimeter, LengthUnit.Point);


            foreach (Section s in dc.Sections)
            {
                // Find the first paragraph (Let's assume that it's the header) and remove it.
                if (s.Blocks.Count > 0)
                {
                    s.Blocks.RemoveAt(0);
                }
                // Insert the new header into the each section.
                s.HeadersFooters.Add(header.Clone(true));
            }

            dc.Save(outFile);

            // Open the results for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(inpFile)
            {
                UseShellExecute = true
            });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile)
            {
                UseShellExecute = true
            });
        }
Esempio n. 27
0
    static void Main()
    {
        // If using Professional version, put your serial key below.
        SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

        var workbook = new ExcelFile();

        int numberOfEmployees = 4;

        var worksheet = workbook.Worksheets.Add("SourceSheet");

        // Add data which is used by the Excel chart.
        var names  = new string[] { "John Doe", "Fred Nurk", "Hans Meier", "Ivan Horvat" };
        var random = new Random();

        for (int i = 0; i < numberOfEmployees; i++)
        {
            worksheet.Cells[i + 1, 0].Value = names[i % names.Length] + (i < names.Length ? string.Empty : ' ' + (i / names.Length + 1).ToString());
            worksheet.Cells[i + 1, 1].SetValue(random.Next(1000, 5000));
        }

        // Set header row and formatting.
        worksheet.Cells[0, 0].Value             = "Name";
        worksheet.Cells[0, 1].Value             = "Salary";
        worksheet.Cells[0, 0].Style.Font.Weight = worksheet.Cells[0, 1].Style.Font.Weight = ExcelFont.BoldWeight;
        worksheet.Columns[0].Width = (int)LengthUnitConverter.Convert(3, LengthUnit.Centimeter, LengthUnit.ZeroCharacterWidth256thPart);
        worksheet.Columns[1].Style.NumberFormat = "\"$\"#,##0";

        // Create Excel chart sheet.
        var chartsheet = workbook.Worksheets.Add(SheetType.Chart, "ChartSheet");

        // Create Excel chart and select data for it.
        // You cannot set the size of the chart area when the chart is located on a chart sheet, it will snap to maximum size on the chart sheet.
        var chart = chartsheet.Charts.Add(ChartType.Bar, 0, 0, 0, 0, LengthUnit.Centimeter);

        chart.SelectData(worksheet.Cells.GetSubrangeAbsolute(0, 0, numberOfEmployees, 1), true);

        workbook.Save("Chart Sheet.xlsx");
    }
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

        ExcelFile      ef = new ExcelFile();
        ExcelWorksheet ws = ef.Worksheets.Add("Chart");

        int numberOfEmployees = 4;

        // Create Excel chart and select data for it.
        var chart = ws.Charts.Add(ChartType.Bar, "D2", "M25");

        chart.SelectData(ws.Cells.GetSubrangeAbsolute(0, 0, numberOfEmployees, 1), true);

        // Add data which is used by the Excel chart.
        var names  = new string[] { "John Doe", "Fred Nurk", "Hans Meier", "Ivan Horvat" };
        var random = new Random();

        for (int i = 0; i < numberOfEmployees; i++)
        {
            ws.Cells[i + 1, 0].Value = names[i % names.Length] + (i < names.Length ? string.Empty : ' ' + (i / names.Length + 1).ToString());
            ws.Cells[i + 1, 1].SetValue(random.Next(1000, 5000));
        }

        // Set header row and formatting.
        ws.Cells[0, 0].Value             = "Name";
        ws.Cells[0, 1].Value             = "Salary";
        ws.Cells[0, 0].Style.Font.Weight = ws.Cells[0, 1].Style.Font.Weight = ExcelFont.BoldWeight;
        ws.Columns[0].Width = (int)LengthUnitConverter.Convert(3, LengthUnit.Centimeter, LengthUnit.ZeroCharacterWidth256thPart);
        ws.Columns[1].Style.NumberFormat = "\"$\"#,##0";

        // Make entire sheet print on a single page.
        ws.PrintOptions.FitWorksheetWidthToPages = ws.PrintOptions.FitWorksheetHeightToPages = 1;

        ef.Save("Chart.xlsx");
    }
Esempio n. 29
0
        /// <summary>
        /// How to add pictures into a document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/add-pictures.php
        /// </remarks>
        public static void AddPictures()
        {
            string documentPath = @"Pictures.docx";
            string pictPath     = @"..\..\image1.jpg";

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

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

            dc.Sections.Add(s);

            // 1. Picture with InlineLayout:

            // Create a new paragraph with picture.
            Paragraph par = new Paragraph(dc);

            s.Blocks.Add(par);
            par.ParagraphFormat.Alignment = HorizontalAlignment.Left;

            // Add some text content.
            par.Content.End.Insert("Shrek and Donkey ", new CharacterFormat()
            {
                FontName = "Calibri", Size = 16.0, FontColor = Color.Black
            });

            // Our picture has InlineLayout - it doesn't have positioning by coordinates
            // and located as flowing content together with text (Run and other Inline elements).
            Picture pict1 = new Picture(dc, InlineLayout.Inline(new Size(100, 100)), pictPath);

            // Add picture to the paragraph.
            par.Inlines.Add(pict1);

            // Add some text content.
            par.Content.End.Insert(" arrive at Farquaad's palace in Duloc, where they end up in a tournament.", new CharacterFormat()
            {
                FontName = "Calibri", Size = 16.0, FontColor = Color.Black
            });

            // 2. Picture with FloatingLayout:
            // Floating layout means that the Picture (or Shape) is positioned by coordinates.
            Picture pict2 = new Picture(dc, pictPath);

            pict2.Layout = FloatingLayout.Floating(
                new HorizontalPosition(50, LengthUnit.Millimeter, HorizontalPositionAnchor.Page),
                new VerticalPosition(70, LengthUnit.Millimeter, VerticalPositionAnchor.TopMargin),
                new Size(LengthUnitConverter.Convert(10, LengthUnit.Centimeter, LengthUnit.Point),
                         LengthUnitConverter.Convert(10, LengthUnit.Centimeter, LengthUnit.Point))
                );

            // Set the wrapping style.
            (pict2.Layout as FloatingLayout).WrappingStyle = WrappingStyle.Square;

            // Add our picture into the section.
            s.Content.End.Insert(pict2.Content);

            // Save our document into DOCX format.
            dc.Save(documentPath, new DocxSaveOptions());

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(documentPath)
            {
                UseShellExecute = true
            });
        }
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

        int numberOfEmployees = 4;
        int numberOfYears     = 4;

        var ef = new ExcelFile();
        var ws = ef.Worksheets.Add("Chart");

        // Create chart and select data for it.
        var chart = (ColumnChart)ws.Charts.Add(ChartType.Column, "B7", "O27");

        chart.SelectData(ws.Cells.GetSubrangeAbsolute(0, 0, numberOfEmployees, numberOfYears));

        // Set chart title.
        chart.Title.Text = "Clustered Column Chart";

        // Set axis titles.
        chart.Axes.Horizontal.Title.Text = "Years";
        chart.Axes.Vertical.Title.Text   = "Salaries";

        // For all charts (except Pie and Bar) value axis is vertical.
        var valueAxis = chart.Axes.VerticalValue;

        // Set value axis scaling, units, gridlines and tick marks.
        valueAxis.Minimum   = 0;
        valueAxis.Maximum   = 6000;
        valueAxis.MajorUnit = 1000;
        valueAxis.MinorUnit = 500;
        valueAxis.MajorGridlines.IsVisible = true;
        valueAxis.MinorGridlines.IsVisible = true;
        valueAxis.MajorTickMarkType        = TickMarkType.Outside;
        valueAxis.MinorTickMarkType        = TickMarkType.Cross;

        // Add data which is used by the chart.
        var names  = new string[] { "John Doe", "Fred Nurk", "Hans Meier", "Ivan Horvat" };
        var random = new Random();

        for (int i = 0; i < numberOfEmployees; ++i)
        {
            ws.Cells[i + 1, 0].Value = names[i % names.Length] + (i < names.Length ? string.Empty : ' ' + (i / names.Length + 1).ToString());

            for (int j = 0; j < numberOfYears; ++j)
            {
                ws.Cells[i + 1, j + 1].SetValue(random.Next(1000, 5000));
            }
        }

        // Set header row and formatting.
        ws.Cells[0, 0].Value             = "Name";
        ws.Cells[0, 0].Style.Font.Weight = ExcelFont.BoldWeight;
        ws.Columns[0].Width = (int)LengthUnitConverter.Convert(3, LengthUnit.Centimeter, LengthUnit.ZeroCharacterWidth256thPart);
        for (int i = 0, startYear = DateTime.Now.Year - numberOfYears; i < numberOfYears; ++i)
        {
            ws.Cells[0, i + 1].SetValue(startYear + i);
            ws.Cells[0, i + 1].Style.Font.Weight  = ExcelFont.BoldWeight;
            ws.Cells[0, i + 1].Style.NumberFormat = "General";
            ws.Columns[i + 1].Style.NumberFormat  = "\"$\"#,##0";
        }

        // Make entire sheet print horizontally centered on a single page with headings and gridlines.
        var printOptions = ws.PrintOptions;

        printOptions.HorizontalCentered       = printOptions.PrintHeadings = printOptions.PrintGridlines = true;
        printOptions.FitWorksheetWidthToPages = printOptions.FitWorksheetHeightToPages = 1;

        ef.Save("Chart Components.xlsx");
    }