protected override void OnAttached() { if (!(Element is Page)) { return; } OnceInitializeAction = Initialize; _formsLayout = Floating.GetContent(Element); _formsLayout.Parent = Element; _page = Element as Page; _page.SizeChanged += PageSizeChanged; _page.LayoutChanged += PageLayoutChanged; void BindingContextChanged(object sender, EventArgs e) { // When the target is a Page, since OnDetached method isn't automatically called, // manually make it call at this timing. if (_page.BindingContext != null && !IsAttached) { return; } _page.BindingContextChanged -= BindingContextChanged; var toRemove = Element.Effects.OfType <AiRoutingEffectBase>().FirstOrDefault(x => x.EffectId == ResolveId); Element.Effects.Remove(toRemove); } _page.BindingContextChanged += BindingContextChanged; }
/// <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 }); }
/// <summary> /// This sample shows how to work with shape groups. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/shape-groups.php /// </remarks> public static void ShapeGroups() { string pictPath = @"..\..\image1.jpg"; string documentPath = @"ShapeGroups.docx"; // Let's create a document. DocumentCore dc = new DocumentCore(); // Create floating layout. HorizontalPosition hp = new HorizontalPosition(HorizontalPositionType.Center, HorizontalPositionAnchor.Page); VerticalPosition vp = new VerticalPosition(5f, LengthUnit.Centimeter, VerticalPositionAnchor.TopMargin); FloatingLayout fl = new FloatingLayout(hp, vp, new Size(300, 300)); // Create group. ShapeGroup group = new ShapeGroup(dc, fl); // Specify the size dimensions of the child extents rectangle. group.ChildSize = new Size(100, 100); // Create a child shape#1 (inside group) with preset geometry. // Specify shape's size and offset relative to group's ChildSize (100x100). Shape shape1 = new Shape(dc, new GroupLayout(new Point(0, 0), new Size(50, 50))); // Specify outline and fill. shape1.Outline.Fill.SetSolid(new Color("#358CCB")); shape1.Outline.Width = 2; shape1.Fill.SetSolid(Color.Orange); // Shape will be rectangle. shape1.Geometry.SetPreset(Figure.Rectangle); // Create picture and add it into the group. Picture picture = new Picture(dc, Layout.Group(new Point(50, 50), new Size(50, 50)), pictPath); // Specify picture fill mode. picture.ImageData.FillMode = PictureFillMode.Stretch; // Add shape and picture into our group. group.ChildShapes.Add(shape1); group.ChildShapes.Add(picture); // Add our group into the document. dc.Content.End.Insert(group.Content); // 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 }); }
/// <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 }); }
protected override void OnDetached() { _page.SizeChanged -= PageSizeChanged; _page.LayoutChanged -= PageLayoutChanged; _formsLayout.Parent = null; foreach (var child in _formsLayout) { PlatformUtility.DisposeModelAndChildrenRenderers(child); } _formsLayout = null; _nativePage = null; _page = null; System.Diagnostics.Debug.WriteLine($"Detached {GetType().Name} from {Element.GetType().FullName}"); }
static void Main() { // If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); var document = new DocumentModel(); var section = new Section(document); document.Sections.Add(section); var paragraph = new Paragraph(document); section.Blocks.Add(paragraph); // Create and add an inline picture with GIF image. Picture picture1 = new Picture(document, "Zahnrad.gif", 61, 53, LengthUnit.Pixel); paragraph.Inlines.Add(picture1); // Create and add a floating picture with PNG image. Picture picture2 = new Picture(document, "Dices.png"); FloatingLayout layout2 = new FloatingLayout( new HorizontalPosition(HorizontalPositionType.Left, HorizontalPositionAnchor.Page), new VerticalPosition(2, LengthUnit.Inch, VerticalPositionAnchor.Page), picture2.Layout.Size); layout2.WrappingStyle = TextWrappingStyle.InFrontOfText; picture2.Layout = layout2; paragraph.Inlines.Add(picture2); // Create and add a floating picture with SVG image. Picture picture3 = new Picture(document, "Graphics1.svg", 400, 200, LengthUnit.Pixel); FloatingLayout layout3 = new FloatingLayout( new HorizontalPosition(3.5, LengthUnit.Inch, HorizontalPositionAnchor.Page), new VerticalPosition(2, LengthUnit.Inch, VerticalPositionAnchor.Page), picture3.Layout.Size); layout3.WrappingStyle = TextWrappingStyle.BehindText; picture3.Layout = layout3; paragraph.Inlines.Add(picture3); document.Save("Pictures.docx"); }
/// <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 }); }
/// <summary> /// This method creates a pie chart. /// </summary> /// <param name="dc">Document</param> /// <param name="chartLayout">Chart layout</param> /// <param name="data">Chart data</param> /// <param name="addLabels">Add labels or not</param> /// <param name="labelSign">Label sign</param> /// <param name="addLegend">Add legend</param> /// <remarks> /// This method is made specially with open source code. You may change anything you want:<br /> /// Chart colors, size, position, font name and font size, position of labels (inside or outside the chart), legend position.<br /> /// If you need any assistance, feel free to email us: [email protected].<br /> /// </remarks> public static void AddPieChart(DocumentCore dc, FloatingLayout chartLayout, Dictionary <string, double> data, bool addLabels = true, string labelSign = null, bool addLegend = true) { // Assume that our chart can have 10 pies maximally. // And we'll use these colors order by order. // You may change the colors and their quantity. List <string> colors = new List <string>() { "#70AD47", // light green "#4472C4", // blue "#FFC000", // yellow "#A5A5A5", // grey "#ED7D31", // orange "#5B9BD5", // light blue "#44546A", // blue and grey "#C00000", // red "#00B050", // green "#9933FF" // purple }; // 1. To create a circle chart, assume that the sum of all values are 100% // and calculate the percent for the each value. // Translate all data to perce double amount = data.Values.Sum(); List <double> percentages = new List <double>(); foreach (double v in data.Values) { percentages.Add(v * 100 / amount); } // 2. Translate the percentage value of the each pie into degrees. // The whole circle is 360 degrees. int pies = data.Values.Count; List <double> pieDegrees = new List <double>(); foreach (double p in percentages) { pieDegrees.Add(p * 360 / 100); } // 3. Translate degrees to the "Pie" measurement. List <double> pieMeasure = new List <double>(); // Add the start position. pieMeasure.Add(0); double currentAngle = 0; foreach (double pd in pieDegrees) { currentAngle += pd; pieMeasure.Add(480 * currentAngle / 360); } // 4. Create the pies. Shape originalShape = new Shape(dc, chartLayout); for (int i = 0; i < pies; i++) { Shape shpPie = originalShape.Clone(true); shpPie.Outline.Fill.SetSolid(Color.White); shpPie.Outline.Width = 0.5; shpPie.Fill.SetSolid(new Color(colors[i])); shpPie.Geometry.SetPreset(Figure.Pie); shpPie.Geometry.AdjustValues["adj1"] = 45000 * pieMeasure[i]; shpPie.Geometry.AdjustValues["adj2"] = 45000 * pieMeasure[i + 1]; dc.Content.End.Insert(shpPie.Content); } // 5. Add labels if (addLabels) { // 0.5 ... 1.2 (inside/outside the circle). double multiplier = 0.8; double radius = chartLayout.Size.Width / 2 * multiplier; currentAngle = 0; double labelW = 35; double labelH = 20; for (int i = 0; i < pieDegrees.Count; i++) { currentAngle += pieDegrees[i]; double middleAngleDegrees = 360 - (currentAngle - pieDegrees[i] / 2); double middleAngleRad = middleAngleDegrees * (Math.PI / 180); // Calculate the (x, y) on the circle. double x = radius * Math.Cos(middleAngleRad); double y = radius * Math.Sin(middleAngleRad); // Correct the position depending of the label size; x -= labelW / 2; y += labelH / 2; HorizontalPosition centerH = new HorizontalPosition(chartLayout.HorizontalPosition.Value + chartLayout.Size.Width / 2, LengthUnit.Point, HorizontalPositionAnchor.LeftMargin); VerticalPosition centerV = new VerticalPosition(chartLayout.VerticalPosition.Value + chartLayout.Size.Height / 2, LengthUnit.Point, VerticalPositionAnchor.TopMargin); HorizontalPosition labelX = new HorizontalPosition(centerH.Value + x, LengthUnit.Point, HorizontalPositionAnchor.LeftMargin); VerticalPosition labelY = new VerticalPosition(centerV.Value - y, LengthUnit.Point, VerticalPositionAnchor.TopMargin); FloatingLayout labelLayout = new FloatingLayout(labelX, labelY, new Size(labelW, labelH)); Shape shpLabel = new Shape(dc, labelLayout); shpLabel.Outline.Fill.SetEmpty(); shpLabel.Text.Blocks.Content.Start.Insert($"{data.Values.ElementAt(i)}{labelSign}", new CharacterFormat() { FontName = "Arial", Size = 10, //FontColor = new Color("#333333") FontColor = new Color("#FFFFFF") }); (shpLabel.Text.Blocks[0] as Paragraph).ParagraphFormat.Alignment = HorizontalAlignment.Center; dc.Content.End.Insert(shpLabel.Content); } // 6. Add Legend if (addLegend) { double legendTopMargin = LengthUnitConverter.Convert(5, LengthUnit.Millimeter, LengthUnit.Point); double legendLeftMargin = LengthUnitConverter.Convert(-10, LengthUnit.Millimeter, LengthUnit.Point); HorizontalPosition legendX = new HorizontalPosition(chartLayout.HorizontalPosition.Value + legendLeftMargin, LengthUnit.Point, HorizontalPositionAnchor.LeftMargin); VerticalPosition legendY = new VerticalPosition(chartLayout.VerticalPosition.Value + chartLayout.Size.Height + legendTopMargin, LengthUnit.Point, VerticalPositionAnchor.TopMargin); double legendW = chartLayout.Size.Width * 2; double legendH = 20; FloatingLayout legendLayout = new FloatingLayout(legendX, legendY, new Size(legendW, legendH)); Shape shpLegend = new Shape(dc, legendLayout); shpLegend.Outline.Fill.SetEmpty(); Paragraph pLegend = new Paragraph(dc); pLegend.ParagraphFormat.Alignment = HorizontalAlignment.Left; for (int i = 0; i < data.Count; i++) { string legendItem = data.Keys.ElementAt(i); // 183 - circle, "Symbol" // 167 - square, "Wingdings" Run marker = new Run(dc, (char)167, new CharacterFormat() { FontColor = new Color(colors[i]), FontName = "Wingdings" }); pLegend.Content.End.Insert(marker.Content); pLegend.Content.End.Insert($" {legendItem} ", new CharacterFormat()); } shpLegend.Text.Blocks.Add(pLegend); dc.Content.End.Insert(shpLegend.Content); } } }
/// <summary> /// How to add picture into an existing DOCX document using MemoryStream. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/add-picture-in-docx-document-in-memory-net-csharp-vb.php /// </remarks> public static void AddPictureToDocxInMemory() { // We're using files here only to retrieve the data from them and show the results. // The whole process will be done completely in memory using MemoryStream. string inputFile = @"..\..\example.docx"; string outputDocxFile = @"Result.docx"; string outputPdfFile = @"Result.pdf"; string pictPath = @"..\..\picture.jpg"; // 1. Load the input data into memory (from DOCX document and the picture). byte[] inputDocxBytes = File.ReadAllBytes(inputFile); byte[] pictBytes = File.ReadAllBytes(pictPath); // 2. Create new MemoryStream with DOCX and load it into DocumentCore. DocumentCore dc = null; using (MemoryStream msDocx = new MemoryStream(inputDocxBytes)) { dc = DocumentCore.Load(msDocx, new DocxLoadOptions()); } // 3. Create new Memory Stream, and Picture object for the picture. Picture pict = null; // Set the picture size in mm. int width = 40; int height = 40; Size size = new Size(LengthUnitConverter.Convert(width, LengthUnit.Millimeter, LengthUnit.Point), LengthUnitConverter.Convert(height, LengthUnit.Millimeter, LengthUnit.Point)); // Set the picture layout from the (left, top) page corner. int fromLeftMm = 140; int fromTopMm = 180; // Floating layout means that the Picture (or Shape) is positioned by coordinates. FloatingLayout fl = new FloatingLayout(new HorizontalPosition(fromLeftMm, LengthUnit.Millimeter, HorizontalPositionAnchor.Page), new VerticalPosition(fromTopMm, LengthUnit.Millimeter, VerticalPositionAnchor.TopMargin), size); // Load the picture using (MemoryStream msPict = new MemoryStream(pictBytes)) { pict = new Picture(dc, fl, msPict, PictureFormat.Jpeg); } // Set the wrapping style. (pict.Layout as FloatingLayout).WrappingStyle = WrappingStyle.Tight; // Add our picture into the 1st section. Section sect = dc.Sections[0]; sect.Content.End.Insert(pict.Content); // Save our document into DOCX format using MemoryStream. using (MemoryStream msDocxResult = new MemoryStream()) { dc.Save(msDocxResult, new DocxSaveOptions()); // To show the result save our msDocxResult into file. File.WriteAllBytes(outputDocxFile, msDocxResult.ToArray()); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outputDocxFile) { UseShellExecute = true }); } // Save our document into PDF format using MemoryStream. using (MemoryStream msPdfResult = new MemoryStream()) { dc.Save(msPdfResult, new PdfSaveOptions()); // To show the result save our msPdfResult into file. File.WriteAllBytes(outputPdfFile, msPdfResult.ToArray()); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outputPdfFile) { UseShellExecute = true }); } }
/// <summary> /// Insert images on each page of the PDF file. /// </summary> /// <remarks> /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/from-customers-insert-images-on-each-document-page-csharp-vb-net.php /// </remarks> static void InsertImagesOnEachPage() { string inpfFile = @"..\..\example.pdf"; string pctFile = @"..\..\signature.png"; string outFile = @"Result.pdf"; // This example is acceptable for PDF documents. // Because when we're loading PDF documents using DocumentCore the each PDF-page // we'll be stored in own Section object. // In other words, the each Section represents the separate PDF-page. DocumentCore dc = DocumentCore.Load(inpfFile); // Load the Picture from a file. Picture pict = new Picture(dc, pctFile); // In this example we'll place the image in three (3) // different places to the each document page. // Let's create three layouts List <Layout> layouts = new List <Layout>() { // Layout 1. // Horizontal: 10mm from page left. // Vertical: 260mm from top margin. // Size: 2cm * 1 cm. FloatingLayout.Floating( new HorizontalPosition(10, LengthUnit.Millimeter, HorizontalPositionAnchor.Page), new VerticalPosition(260, LengthUnit.Millimeter, VerticalPositionAnchor.TopMargin), new Size(LengthUnitConverter.Convert(2, LengthUnit.Centimeter, LengthUnit.Point), LengthUnitConverter.Convert(1, LengthUnit.Centimeter, LengthUnit.Point)) ), // Layout 2. // Horizontal: 180mm from page left. // Vertical: 10mm from top margin. // Size: 3cm * 2cm. FloatingLayout.Floating( new HorizontalPosition(180, LengthUnit.Millimeter, HorizontalPositionAnchor.Page), new VerticalPosition(10, LengthUnit.Millimeter, VerticalPositionAnchor.TopMargin), new Size(LengthUnitConverter.Convert(3, LengthUnit.Centimeter, LengthUnit.Point), LengthUnitConverter.Convert(2, LengthUnit.Centimeter, LengthUnit.Point)) ), // Layout 3. // Horizontal: 150mm from page left. // Vertical: 150mm from page top. // Size: 3cm * 3cm. FloatingLayout.Floating( new HorizontalPosition(150, LengthUnit.Millimeter, HorizontalPositionAnchor.Page), new VerticalPosition(150, LengthUnit.Millimeter, VerticalPositionAnchor.Page), new Size(LengthUnitConverter.Convert(3, LengthUnit.Centimeter, LengthUnit.Point), LengthUnitConverter.Convert(3, LengthUnit.Centimeter, LengthUnit.Point)) ) }; // Iterate by Sections (PDF pages in our case). foreach (Section s in dc.Sections) { // Insert our pictures in different places. foreach (FloatingLayout fl in layouts) { pict.Layout = new FloatingLayout(fl.HorizontalPosition, fl.VerticalPosition, fl.Size); // Place the picture behind the text. (pict.Layout as FloatingLayout).WrappingStyle = WrappingStyle.BehindText; // Here we insert the Picture content at the 1st Block element (Paragraph or Table). s.Blocks[0].Content.Start.Insert(pict.Content); } } dc.Save(outFile, new PdfSaveOptions()); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true }); }
/// <summary> /// Insert a picture to custom pages into existing DOCX document. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/insert-picture-jpg-image-to-custom-docx-page-net-csharp-vb.php /// </remarks> static void InsertPictureToCustomPages() { // In this example we'll insert the picture to 1st and 3rd pages // of DOCX document into specific positions. string inpFile = @"..\..\example.docx"; string outFile = @"Result.docx"; string pictFile = @"..\..\picture.jpg"; DocumentCore dc = DocumentCore.Load(inpFile); DocumentPaginator dp = dc.GetPaginator(); // Step 1: Put the picture to 1st page. // Create the Picture object from Jpeg file. Picture pict = new Picture(dc, pictFile); // Specify the picture size and position. pict.Layout = FloatingLayout.Floating( new HorizontalPosition(70, LengthUnit.Millimeter, HorizontalPositionAnchor.Margin), new VerticalPosition(23, LengthUnit.Millimeter, VerticalPositionAnchor.Margin), new Size(LengthUnitConverter.Convert(1, LengthUnit.Inch, LengthUnit.Point), pict.Layout.Size.Height * LengthUnitConverter.Convert(1, LengthUnit.Inch, LengthUnit.Point) / pict.Layout.Size.Width)); // Put the picture behind the text (pict.Layout as FloatingLayout).WrappingStyle = WrappingStyle.BehindText; // Find the 1st Element in the 1st page. Element e1 = dp.Pages[0].ElementsOnPage.FirstOrDefault(e => e is Run); // Insert the picture at this Element. e1.Content.End.Insert(pict.Content); // Step 2: Put the picture to 3rd page. if (dp.Pages.Count >= 3) { // Find the 1st Element on the 3rd page. Element e2 = dp.Pages[2].ElementsOnPage.FirstOrDefault(e => e is Run); // Create another picture Picture pict2 = new Picture(dc, pictFile); pict2.Layout = FloatingLayout.Floating( new HorizontalPosition(10, LengthUnit.Millimeter, HorizontalPositionAnchor.Margin), new VerticalPosition(20, LengthUnit.Millimeter, VerticalPositionAnchor.Margin), new Size(LengthUnitConverter.Convert(1, LengthUnit.Inch, LengthUnit.Point), pict2.Layout.Size.Height * LengthUnitConverter.Convert(1, LengthUnit.Inch, LengthUnit.Point) / pict2.Layout.Size.Width) ); (pict2.Layout as FloatingLayout).WrappingStyle = WrappingStyle.BehindText; // Insert the picture at this Element. e2.Content.End.Insert(pict2.Content); } // Save the document as new DOCX and open it. dc.Save(outFile); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true }); }
public void CreatePieChartsPage(DocumentCore dc) { // 1. Add new Section (for the charts) at the beginning of the report. Section sectCharts = new Section(dc); sectCharts.PageSetup = dc.Sections[0].PageSetup.Clone(); sectCharts.PageSetup.PageMargins = new PageMargins() { Left = LengthUnitConverter.Convert(5, LengthUnit.Millimeter, LengthUnit.Point), Right = LengthUnitConverter.Convert(5, LengthUnit.Millimeter, LengthUnit.Point), Top = LengthUnitConverter.Convert(5, LengthUnit.Millimeter, LengthUnit.Point) }; dc.Sections.Insert(0, sectCharts); Paragraph pageHeading = new Paragraph(dc, new Run(dc, "Statistics", new CharacterFormat() { FontName = "Calibri", Size = 42, Bold = true, UnderlineStyle = UnderlineType.Single, Italic = true, FontColor = new Color(244, 176, 131), AllCaps = true })); pageHeading.ParagraphFormat.Alignment = SautinSoft.Document.HorizontalAlignment.Center; sectCharts.Blocks.Add(pageHeading); CharacterFormat cf = new CharacterFormat() { FontName = "Calibri", Size = 20, UnderlineStyle = UnderlineType.Single, FontColor = new Color(244, 176, 131), }; Paragraph recipentHeading = new Paragraph(dc, new Run(dc, "Income from the customers in percentages:", cf.Clone())); sectCharts.Blocks.Add(recipentHeading); Paragraph itemHeading = new Paragraph(dc, new Run(dc, "Sales overview - see the best selling product:", cf.Clone())); Shape shpItem = new Shape(dc, new FloatingLayout(new HorizontalPosition(5f, LengthUnit.Millimeter, HorizontalPositionAnchor.LeftMargin), new VerticalPosition(130f, LengthUnit.Millimeter, VerticalPositionAnchor.TopMargin), new SautinSoft.Document.Drawing.Size(200, 20, LengthUnit.Millimeter))); shpItem.Outline.Fill.SetEmpty(); shpItem.Text.Blocks.Add(itemHeading); sectCharts.Content.Start.Insert(shpItem.Content); // 2. Add Chart - Recipients // Create dictionary for the chart <Recipient Name, Total Percentage>. Dictionary <string, double> recipients = new Dictionary <string, double>(); double totalAmount = Orders.Sum(o => o.OrderTotal); foreach (Order o in Orders) { if (recipients.Keys.Contains(o.Recipient)) { recipients[o.Recipient] += o.OrderTotal * 100 / totalAmount; } else { recipients.Add(o.Recipient, o.OrderTotal * 100 / totalAmount); } recipients[o.Recipient] = Math.Round(recipients[o.Recipient]); } FloatingLayout flR = new FloatingLayout(new HorizontalPosition(20f, LengthUnit.Millimeter, HorizontalPositionAnchor.LeftMargin), new VerticalPosition(40f, LengthUnit.Millimeter, VerticalPositionAnchor.TopMargin), new SautinSoft.Document.Drawing.Size(200, 200)); AddPieChart(sectCharts, flR, recipients, true, "%", true, true); // 3. Add Chart - Best selling item // Create dictionary for the chart <Product Name, Total>. Dictionary <string, double> productSales = new Dictionary <string, double>(); foreach (Order o in Orders) { foreach (Product p in o.Products) { if (productSales.Keys.Contains(p.Name)) { productSales[p.Name] += p.TotalPrice; } else { productSales.Add(p.Name, p.TotalPrice); } } } FloatingLayout flP = new FloatingLayout(new HorizontalPosition(20f, LengthUnit.Millimeter, HorizontalPositionAnchor.LeftMargin), new VerticalPosition(150f, LengthUnit.Millimeter, VerticalPositionAnchor.TopMargin), new SautinSoft.Document.Drawing.Size(200, 200)); AddPieChart(sectCharts, flP, productSales, true, "£", true, false); }