public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_PSD();

            //ExStart:AddGradientEffects

            // Gradient overlay effect. Example
            string sourceFileName = dataDir + "GradientOverlay.psd";
            string exportPath     = dataDir + "GradientOverlayChanged.psd";

            var loadOptions = new PsdLoadOptions()
            {
                LoadEffectsResource = true
            };

            using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
            {
                var gradientOverlay = (GradientOverlayEffect)im.Layers[1].BlendingOptions.Effects[0];

                Assert.AreEqual(BlendMode.Normal, gradientOverlay.BlendMode);
                Assert.AreEqual(255, gradientOverlay.Opacity);
                Assert.AreEqual(true, gradientOverlay.IsVisible);

                var settings = gradientOverlay.Settings;
                Assert.AreEqual(Color.Empty, settings.Color);
                Assert.AreEqual(FillType.Gradient, settings.FillType);
                Assert.AreEqual(true, settings.AlignWithLayer);
                Assert.AreEqual(GradientType.Linear, settings.GradientType);
                Assert.IsTrue(Math.Abs(33 - settings.Angle) < 0.001, "Angle is incorrect");
                Assert.AreEqual(false, settings.Dither);
                Assert.IsTrue(Math.Abs(129 - settings.HorizontalOffset) < 0.001, "Horizontal offset is incorrect");
                Assert.IsTrue(Math.Abs(156 - settings.VerticalOffset) < 0.001, "Vertical offset is incorrect");
                Assert.AreEqual(false, settings.Reverse);

                // Color Points
                var colorPoints = settings.ColorPoints;
                Assert.AreEqual(3, colorPoints.Length);

                Assert.AreEqual(Color.FromArgb(9, 0, 178), colorPoints[0].Color);
                Assert.AreEqual(0, colorPoints[0].Location);
                Assert.AreEqual(50, colorPoints[0].MedianPointLocation);

                Assert.AreEqual(Color.Red, colorPoints[1].Color);
                Assert.AreEqual(2048, colorPoints[1].Location);
                Assert.AreEqual(50, colorPoints[1].MedianPointLocation);

                Assert.AreEqual(Color.FromArgb(255, 252, 0), colorPoints[2].Color);
                Assert.AreEqual(4096, colorPoints[2].Location);
                Assert.AreEqual(50, colorPoints[2].MedianPointLocation);

                // Transparency points
                var transparencyPoints = settings.TransparencyPoints;
                Assert.AreEqual(2, transparencyPoints.Length);

                Assert.AreEqual(0, transparencyPoints[0].Location);
                Assert.AreEqual(50, transparencyPoints[0].MedianPointLocation);
                Assert.AreEqual(100, transparencyPoints[0].Opacity);

                Assert.AreEqual(4096, transparencyPoints[1].Location);
                Assert.AreEqual(50, transparencyPoints[1].MedianPointLocation);
                Assert.AreEqual(100, transparencyPoints[1].Opacity);

                // Test editing
                settings.Color = Color.Green;

                gradientOverlay.Opacity   = 193;
                gradientOverlay.BlendMode = BlendMode.Lighten;

                settings.AlignWithLayer   = false;
                settings.GradientType     = GradientType.Radial;
                settings.Angle            = 45;
                settings.Dither           = true;
                settings.HorizontalOffset = 15;
                settings.VerticalOffset   = 11;
                settings.Reverse          = true;

                // Add new color point
                var colorPoint = settings.AddColorPoint();
                colorPoint.Color               = Color.Green;
                colorPoint.Location            = 4096;
                colorPoint.MedianPointLocation = 75;

                // Change location of previous point
                settings.ColorPoints[2].Location = 3000;

                // Add new transparency point
                var transparencyPoint = settings.AddTransparencyPoint();
                transparencyPoint.Opacity             = 25;
                transparencyPoint.MedianPointLocation = 25;
                transparencyPoint.Location            = 4096;

                // Change location of previous transparency point
                settings.TransparencyPoints[1].Location = 2315;
                im.Save(exportPath);
            }

            // Test file after edit
            using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
            {
                var gradientOverlay = (GradientOverlayEffect)im.Layers[1].BlendingOptions.Effects[0];
                try
                {
                    Assert.AreEqual(BlendMode.Lighten, gradientOverlay.BlendMode);
                    Assert.AreEqual(193, gradientOverlay.Opacity);
                    Assert.AreEqual(true, gradientOverlay.IsVisible);

                    var fillSettings = gradientOverlay.Settings;
                    Assert.AreEqual(Color.Empty, fillSettings.Color);
                    Assert.AreEqual(FillType.Gradient, fillSettings.FillType);

                    // Check color points
                    Assert.AreEqual(4, fillSettings.ColorPoints.Length);

                    var point = fillSettings.ColorPoints[0];
                    Assert.AreEqual(50, point.MedianPointLocation);
                    Assert.AreEqual(Color.FromArgb(9, 0, 178), point.Color);
                    Assert.AreEqual(0, point.Location);

                    point = fillSettings.ColorPoints[1];
                    Assert.AreEqual(50, point.MedianPointLocation);
                    Assert.AreEqual(Color.Red, point.Color);
                    Assert.AreEqual(2048, point.Location);

                    point = fillSettings.ColorPoints[2];
                    Assert.AreEqual(50, point.MedianPointLocation);
                    Assert.AreEqual(Color.FromArgb(255, 252, 0), point.Color);
                    Assert.AreEqual(3000, point.Location);

                    point = fillSettings.ColorPoints[3];
                    Assert.AreEqual(75, point.MedianPointLocation);
                    Assert.AreEqual(Color.Green, point.Color);
                    Assert.AreEqual(4096, point.Location);

                    // Check transparent points
                    Assert.AreEqual(3, fillSettings.TransparencyPoints.Length);

                    var transparencyPoint = fillSettings.TransparencyPoints[0];
                    Assert.AreEqual(50, transparencyPoint.MedianPointLocation);
                    Assert.AreEqual(100, transparencyPoint.Opacity);
                    Assert.AreEqual(0, transparencyPoint.Location);

                    transparencyPoint = fillSettings.TransparencyPoints[1];
                    Assert.AreEqual(50, transparencyPoint.MedianPointLocation);
                    Assert.AreEqual(100, transparencyPoint.Opacity);
                    Assert.AreEqual(2315, transparencyPoint.Location);

                    transparencyPoint = fillSettings.TransparencyPoints[2];
                    Assert.AreEqual(25, transparencyPoint.MedianPointLocation);
                    Assert.AreEqual(25, transparencyPoint.Opacity);
                    Assert.AreEqual(4096, transparencyPoint.Location);
                }
                catch (Exception e)
                {
                    String ex = e.StackTrace;
                }
            }
            //ExEnd:AddGradientEffects
        }
Exemplo n.º 2
0
        public static void Run()
        {
            // ExStart:RoundedCornerTable
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_Tables();

            // Instantiate Pdf object
            Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

            // Create the section in the Pdf object
            Aspose.Pdf.Generator.Section sec1 = pdf1.Sections.Add();

            // Instantiate a table object
            Aspose.Pdf.Generator.Table tab1 = new Aspose.Pdf.Generator.Table();

            // Add the table in paragraphs collection of the desired section
            sec1.Paragraphs.Add(tab1);

            // Set with column widths of the table
            tab1.ColumnWidths = "100";

            // Set fixed table row height
            tab1.FixedHeight = 30;

            // Create a blank BorderInfo object
            Aspose.Pdf.Generator.BorderInfo bInfo = new Aspose.Pdf.Generator.BorderInfo();

            // Create a GraphInfo object without any argument to its constructor
            Aspose.Pdf.Generator.GraphInfo gInfo = new Aspose.Pdf.Generator.GraphInfo();

            // Set the corner radius for GraphInfo
            gInfo.CornerRadius = 15F;

            // Specify the line color information
            gInfo.Color = new Aspose.Pdf.Generator.Color("Red");

            // Set the rounded corner table border
            bInfo.Round = gInfo;

            // Specify the Corner style for table border as Round
            tab1.CornerStyle = Aspose.Pdf.Generator.BorderCornerStyle.Round;

            // Set the table border information
            tab1.Border = bInfo;

            // Create rows in the table and then cells in the rows
            Aspose.Pdf.Generator.Row row1 = tab1.Rows.Add();

            // Add sample string to paragraphs collection of table cell
            row1.Cells.Add("Hello World...");

            // Set the vertical alignment of text as center aligned
            row1.Cells[0].DefaultCellTextInfo.Alignment = Aspose.Pdf.Generator.AlignmentType.Center;

            // Set the horizontal alignment of text as center aligned
            row1.Cells[0].VerticalAlignment = Aspose.Pdf.Generator.VerticalAlignmentType.Center;

            // Save the Pdf
            pdf1.Save(dataDir + "Rounded_Corner-Table_out_.pdf");
            // ExEnd:RoundedCornerTable
        }
        public static void Run()
        {
            string dataDir          = RunExamples.GetDataDir_Conversion();
            string presTemplatePath = Path.Combine(dataDir, "PresentationTemplate.pptx");
            string resultPath       = Path.Combine(RunExamples.OutPath, "MailMergeResult");

            // Path to the data.
            // XML data is one of the examples of the possible MailMerge data sources (among RDBMS and other types of data sources).
            string dataPath = Path.Combine(dataDir, "TestData.xml");

            // Check if result path exists
            if (!Directory.Exists(resultPath))
            {
                Directory.CreateDirectory(resultPath);
            }

            // Creating DataSet using XML data
            using (DataSet dataSet = new DataSet())
            {
                dataSet.ReadXml(dataPath);

                DataTableCollection dataTables     = dataSet.Tables;
                DataTable           usersTable     = dataTables["TestTable"];
                DataTable           staffListTable = dataTables["StaffList"];
                DataTable           planFactTable  = dataTables["Plan_Fact"];

                // For all records in main table we will create a separate presentation
                foreach (DataRow userRow in usersTable.Rows)
                {
                    // create result (individual) presentation name
                    string presPath = Path.Combine(resultPath, "PresFor_" + userRow["Name"] + ".pptx");

                    // Load presentation template
                    using (Presentation pres = new Presentation(presTemplatePath))
                    {
                        // Fill text boxes with data from data base main table
                        ((AutoShape)pres.Slides[0].Shapes[0]).TextFrame.Text =
                            "Chief of the department - " + userRow["Name"];
                        ((AutoShape)pres.Slides[0].Shapes[4]).TextFrame.Text = userRow["Department"].ToString();

                        // Get image from data base
                        byte[] bytes = Convert.FromBase64String(userRow["Img"].ToString());

                        // insert image into picture frame of presentation
                        IPPImage      image = pres.Images.AddImage(bytes);
                        IPictureFrame pf    = pres.Slides[0].Shapes[1] as PictureFrame;
                        pf.PictureFormat.Picture.Image.ReplaceImage(image);

                        // Get abd prepare text frame for filling it with datas
                        IAutoShape list      = pres.Slides[0].Shapes[2] as IAutoShape;
                        ITextFrame textFrame = list.TextFrame;

                        textFrame.Paragraphs.Clear();
                        Paragraph para = new Paragraph();
                        para.Text = "Department Staff:";
                        textFrame.Paragraphs.Add(para);

                        // fill staff data
                        FillStaffList(textFrame, userRow, staffListTable);

                        // fill plan fact data
                        FillPlanFact(pres, userRow, planFactTable);

                        pres.Save(presPath, SaveFormat.Pptx);
                    }
                }
            }
        }
        public static void Run()
        {
            //Output directory
            string outputDir = RunExamples.Get_OutputDirectory();

            // Instantiate a new Workbook.
            Workbook workbook = new Workbook();

            // Get the first Worksheet Cells.
            Cells cells = workbook.Worksheets[0].Cells;

            // Fill some sample data into the cells.
            for (int i = 0; i < 50; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    cells[i, j].PutValue(i.ToString() + "," + j.ToString());
                }
            }

            // Create a range (A1:D3).
            Range range = cells.CreateRange("A1", "D3");

            // Create a style object.
            Style style = workbook.CreateStyle();

            // Specify the font attribute.
            style.Font.Name = "Calibri";

            // Specify the shading color.
            style.ForegroundColor = Color.Yellow;
            style.Pattern         = BackgroundType.Solid;

            // Specify the border attributes.
            style.Borders[BorderType.TopBorder].LineStyle    = CellBorderType.Thin;
            style.Borders[BorderType.TopBorder].Color        = Color.Blue;
            style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
            style.Borders[BorderType.BottomBorder].Color     = Color.Blue;
            style.Borders[BorderType.LeftBorder].LineStyle   = CellBorderType.Thin;
            style.Borders[BorderType.LeftBorder].Color       = Color.Blue;
            style.Borders[BorderType.RightBorder].LineStyle  = CellBorderType.Thin;
            style.Borders[BorderType.RightBorder].Color      = Color.Blue;

            // Create the styleflag object.
            StyleFlag flag1 = new StyleFlag();

            // Implement font attribute
            flag1.FontName = true;

            // Implement the shading / fill color.
            flag1.CellShading = true;

            // Implment border attributes.
            flag1.Borders = true;

            // Set the Range style.
            range.ApplyStyle(style, flag1);

            // Create a second range (C10:F12).
            Range range2 = cells.CreateRange("C10", "F12");

            // Copy the range data only.
            range2.CopyData(range);

            // Save the excel file.
            workbook.Save(outputDir + "outputCopyRangeDataOnly.xlsx");

            Console.WriteLine("CopyRangeDataOnly executed successfully.\r\n");
        }
        public static void Run()
        {
            //ExStart:GetSizeOfCADLayout
            // The path to the documents directory.
            string MyDir = RunExamples.GetDataDir_ConvertingCAD();

            string[] sourceFilePaths = new[]
            {
                MyDir + "conic_pyramid.dxf",
                MyDir + "Bottom_plate.dwg"
            };

            foreach (var sourceFilePath in sourceFilePaths)
            {
                string extension = Path.GetExtension(sourceFilePath);
                using (CadImage cadImage = (CadImage)Aspose.CAD.Image.Load(sourceFilePath))
                {
                    List <string> layouts = GetNotEmptyLayouts(cadImage, extension);
                    const double  Epsilon = 0.00001;
                    foreach (string layout in layouts)
                    {
                        System.Console.WriteLine("Layout= " + layout);
                        using (FileStream fs = new FileStream(MyDir + "layout_" + extension + "_" + layout + ".jpg", FileMode.Create))
                        {
                            JpegOptions             jpegOptions = new JpegOptions();
                            CadRasterizationOptions options     = new CadRasterizationOptions();
                            options.Layouts = new string[] { layout };

                            CadLayout l = cadImage.Layouts[layout];

                            if ((Math.Abs(l.MaxExtents.Y) < Epsilon && Math.Abs(l.MaxExtents.X) < Epsilon) ||
                                (Math.Abs(l.MaxExtents.Y + 1E+20) < Epsilon ||
                                 Math.Abs(l.MaxExtents.X + 1E+20) < Epsilon) ||
                                (Math.Abs(l.MinExtents.Y - 1E+20) < Epsilon ||
                                 Math.Abs(l.MinExtents.X - 1E+20) < Epsilon))
                            {
                                // do nothing, we can automatically detect size
                                // we can not rely on PlotPaperUnits here too because it is PlotInInches by default
                            }
                            else
                            {
                                double sizeExtX = l.MaxExtents.X - l.MinExtents.X;
                                double sizeExtY = l.MaxExtents.Y - l.MinExtents.Y;

                                if (l.PlotPaperUnits == CadPlotPaperUnits.PlotInInches)
                                {
                                    options.PageHeight = CommonHelper.INtoPixels(sizeExtY, CommonHelper.DPI);
                                    options.PageWidth  = CommonHelper.INtoPixels(sizeExtX, CommonHelper.DPI);
                                }
                                else
                                {
                                    if (l.PlotPaperUnits == CadPlotPaperUnits.PlotInMillimeters)
                                    {
                                        options.PageHeight = CommonHelper.MMtoPixels(sizeExtY, CommonHelper.DPI);
                                        options.PageWidth  = CommonHelper.MMtoPixels(sizeExtX, CommonHelper.DPI);
                                    }
                                    else
                                    {
                                        options.PageHeight = (float)sizeExtY;
                                        options.PageWidth  = (float)sizeExtX;
                                    }
                                }
                            }


                            jpegOptions.VectorRasterizationOptions = options;

                            cadImage.Save(fs, jpegOptions);
                        }
                    }
                }
            }
        }
Exemplo n.º 6
0
        public static void Run()
        {
            // ExStart:PdfFileEditorFeatures
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles();

            // Create instance of PdfFileEditor class
            PdfFileEditor pdfEditor = new PdfFileEditor();

            // Append pages from input file to the port file and save in output file
            int start = 1;
            int end   = 3;

            pdfEditor.Append(dataDir + "inFile.pdf", dataDir + "portFile.pdf", start, end, dataDir + "outFile.pdf");

            // Concatenate two files and save in the third one
            pdfEditor.Concatenate(dataDir + "inFile1.pdf", dataDir + "inFile2.pdf", dataDir + "outFile.pdf");

            // Delete specified number of pages from the file
            int[] pages = new int[] { 1, 2, 4, 10 };
            pdfEditor.Delete(dataDir + "inFile.pdf", pages, dataDir + "outFile.pdf");

            // Extract any pages from the file
            start = 0;
            end   = 3;
            pdfEditor.OwnerPassword = "******";
            pdfEditor.Extract(dataDir + "inFile.pdf", start, end, dataDir + "outFile.pdf");

            // Insert pages from another file into the output file at a specified position
            start = 2;
            end   = 5;
            pdfEditor.Insert(dataDir + "inFile.pdf", 4, dataDir + "portFile.pdf", start, end, dataDir + "outFile.pdf");

            // Make booklet
            pdfEditor.MakeBooklet(dataDir + "inFile.Pdf", dataDir + "outFile.Pdf");

            // Make N-Ups
            pdfEditor.MakeNUp(dataDir + "inFile.pdf", dataDir + "nupOutFile.pdf", 3, 2);

            // Split the front part of the file
            pdfEditor.SplitFromFirst(dataDir + "inFile.pdf", 3, dataDir + "outFile.pdf");

            // Split the rear part of the file
            pdfEditor.SplitToEnd(dataDir + "inFile.pdf", 3, dataDir + "outFile.pdf");

            // Split to individual pages
            int fileNum = 1;

            MemoryStream[] outBuffer = pdfEditor.SplitToPages(dataDir + "inFile.pdf");
            foreach (MemoryStream aStream in outBuffer)
            {
                FileStream outStream = new FileStream("oneByone" + fileNum.ToString() + ".pdf",
                                                      FileMode.Create);
                aStream.WriteTo(outStream);
                outStream.Close();
                fileNum++;
            }

            // Split to several multi-page pdf documents
            fileNum = 1;
            int[][]        numberofpage = new int[][] { new int[] { 1, 4 } };
            MemoryStream[] outBuffer2   = pdfEditor.SplitToBulks(dataDir + "inFile.pdf", numberofpage);
            foreach (MemoryStream aStream in outBuffer2)
            {
                FileStream outStream = new FileStream("oneByone" + fileNum.ToString() + ".pdf",
                                                      FileMode.Create);
                aStream.WriteTo(outStream);
                outStream.Close();
                fileNum++;
            }
            // ExEnd:PdfFileEditorFeatures
        }
        public static void Run()
        {
#if !NET20
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();

            // Load the XML document.
            XElement orderXml = XElement.Load(dataDir + "PurchaseOrder.xml");

            // Query the purchase order xml file using LINQ to extract the order items
            // into an object of an anonymous type.
            //
            // Make sure you give the properties of the anonymous type the same names as
            // the MERGEFIELD fields in the document.
            //
            // To pass the actual values stored in the XML element or attribute to Aspose.Words,
            // we need to cast them to string. This is to prevent the XML tags being inserted into the final document when
            // the XElement or XAttribute objects are passed to Aspose.Words.
            //ExStart:LINQtoXMLMailMergeorderItems
            var orderItems =
                from order in orderXml.Descendants("Item")
                select new
            {
                PartNumber  = (string)order.Attribute("PartNumber"),
                ProductName = (string)order.Element("ProductName"),
                Quantity    = (string)order.Element("Quantity"),
                USPrice     = (string)order.Element("USPrice"),
                Comment     = (string)order.Element("Comment"),
                ShipDate    = (string)order.Element("ShipDate")
            };
            //ExEnd:LINQtoXMLMailMergeorderItems
            //ExStart:LINQToXMLQueryForDeliveryAddress
            var deliveryAddress =
                from delivery in orderXml.Elements("Address")
                where ((string)delivery.Attribute("Type") == "Shipping")
                select new
            {
                Name    = (string)delivery.Element("Name"),
                Country = (string)delivery.Element("Country"),
                Zip     = (string)delivery.Element("Zip"),
                State   = (string)delivery.Element("State"),
                City    = (string)delivery.Element("City"),
                Street  = (string)delivery.Element("Street")
            };
            //ExEnd:LINQToXMLQueryForDeliveryAddress
            // Create custom Aspose.Words mail merge data sources based on the LINQ queries.
            MyMailMergeDataSource orderItemsDataSource = new MyMailMergeDataSource(orderItems, "Items");
            MyMailMergeDataSource deliveryDataSource   = new MyMailMergeDataSource(deliveryAddress);
            //ExStart:LINQToXMLMailMerge
            string fileName = "TestFile.LINQ.doc";
            // Open the template document.
            Document doc = new Document(dataDir + fileName);

            // Fill the document with data from our data sources.
            // Using mail merge regions for populating the order items table is required
            // because it allows the region to be repeated in the document for each order item.
            doc.MailMerge.ExecuteWithRegions(orderItemsDataSource);

            // The standard mail merge without regions is used for the delivery address.
            doc.MailMerge.Execute(deliveryDataSource);

            dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
            // Save the output document.
            doc.Save(dataDir);
            //ExEnd:LINQToXMLMailMerge
            Console.WriteLine("\nMail merge performed successfully.\nFile saved at " + dataDir);
#else
            throw new InvalidOperationException("This example requires the .NET Framework v3.5 or above to run." +
                                                " Make sure that the target framework of this project is set to 3.5 or above.");
#endif
        }
Exemplo n.º 8
0
        public static void Run()
        {
            // To get proper output please apply a valid Aspose.Imaging License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages();

            List <string> files         = new List <string>(new string[] { dataDir + "TestDemo.tiff", dataDir + "sample.tiff" });
            TiffOptions   createOptions = new TiffOptions(TiffExpectedFormat.Default);

            createOptions.BitsPerSample = new ushort[] { 1 };
            createOptions.Orientation   = TiffOrientations.TopLeft;
            createOptions.Photometric   = TiffPhotometrics.MinIsBlack;
            createOptions.Compression   = TiffCompressions.CcittFax3;
            createOptions.FillOrder     = TiffFillOrders.Lsb2Msb;

            //Create a new image by passing the TiffOptions and size of first frame
            //we will remove the first frame at the end, cause it will be empty
            TiffImage output = null;

            try
            {
                List <TiffImage> images = new List <TiffImage>();
                try
                {
                    foreach (var file in files)
                    {
                        //Create an instance of TiffImage and load the source image
                        TiffImage input = (TiffImage)Image.Load(file);
                        images.Add(input); // Do not dispose before data is fetched. Data is fetched on 'Save' later.
                        foreach (var frame in input.Frames)
                        {
                            if (output == null)
                            {
                                // create a new tiff image with first frame defined.
                                output = new TiffImage(TiffFrame.CopyFrame(frame));
                            }
                            else
                            {
                                // Add copied frame to destination image
                                output.AddFrame(TiffFrame.CopyFrame(frame));
                            }
                        }
                    }

                    if (output != null)
                    {
                        // save the result
                        output.Save(dataDir + "ConcatenateTiffImagesHavingSeveralFrames_out.tif", createOptions);
                    }
                }
                finally
                {
                    foreach (TiffImage image in images)
                    {
                        image.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        public static void Run()
        {
            // Add color overlay layer effect at runtime
            string dataDir = RunExamples.GetDataDir_PSD();

            //ExStart:ImplementBicubicResampler
            string sourceFile = dataDir + "sample_bicubic.psd";
            string destNameCubicConvolution = dataDir + "ResamplerCubicConvolutionStripes_after.psd";

            // Load an existing image into an instance of PsdImage class
            using (PsdImage image = (PsdImage)Image.Load(sourceFile))
            {
                image.Resize(300, 300, ResizeType.CubicConvolution);
                image.Save(destNameCubicConvolution, new PsdOptions(image));
            }


            string destNameCatmullRom = dataDir + "ResamplerCatmullRomStripes_after.psd";

            // Load an existing image into an instance of PsdImage class
            using (PsdImage image = (PsdImage)Image.Load(sourceFile))
            {
                image.Resize(300, 300, ResizeType.CatmullRom);
                image.Save(destNameCatmullRom, new PsdOptions(image));
            }


            string destNameMitchell = "ResamplerMitchellStripes_after.psd";

            // Load an existing image into an instance of PsdImage class
            using (PsdImage image = (PsdImage)Image.Load(sourceFile))
            {
                image.Resize(300, 300, ResizeType.Mitchell);
                image.Save(destNameMitchell, new PsdOptions(image));
            }


            string destNameCubicBSpline = "ResamplerCubicBSplineStripes_after.psd";

            // Load an existing image into an instance of PsdImage class
            using (PsdImage image = (PsdImage)Image.Load(sourceFile))
            {
                image.Resize(300, 300, ResizeType.CubicBSpline);
                image.Save(destNameCubicBSpline, new PsdOptions(image));
            }


            string destNameSinC = "ResamplerSinCStripes_after.psd";

            // Load an existing image into an instance of PsdImage class
            using (PsdImage image = (PsdImage)Image.Load(sourceFile))
            {
                image.Resize(300, 300, ResizeType.SinC);
                image.Save(destNameSinC, new PsdOptions(image));
            }


            string destNameBell = "ResamplerBellStripes_after.psd";

            // Load an existing image into an instance of PsdImage class
            using (PsdImage image = (PsdImage)Image.Load(sourceFile))
            {
                image.Resize(300, 300, ResizeType.Bell);
                image.Save(destNameBell, new PsdOptions(image));
            }


            //ExEnd:ImplementBicubicResampler
        }
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_PSD();

            //ExStart:AddPatternEffects

            // Pattern overlay effect. Example
            string sourceFileName = dataDir + "PatternOverlay.psd";
            string exportPath     = dataDir + "PatternOverlayChanged.psd";

            var newPattern = new int[]
            {
                Color.Aqua.ToArgb(), Color.Red.ToArgb(), Color.Red.ToArgb(), Color.Aqua.ToArgb(),
                Color.Aqua.ToArgb(), Color.White.ToArgb(), Color.White.ToArgb(), Color.Aqua.ToArgb(),
            };

            var newPatternBounds = new Rectangle(0, 0, 4, 2);
            var guid             = Guid.NewGuid();
            var newPatternName   = "$$$/Presets/Patterns/Pattern=Some new pattern name\0";

            var loadOptions = new PsdLoadOptions()
            {
                LoadEffectsResource = true
            };

            using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
            {
                var patternOverlay = (PatternOverlayEffect)im.Layers[1].BlendingOptions.Effects[0];

                Assert.AreEqual(BlendMode.Normal, patternOverlay.BlendMode);
                Assert.AreEqual(127, patternOverlay.Opacity);
                Assert.AreEqual(true, patternOverlay.IsVisible);

                var settings = patternOverlay.Settings;
                Assert.AreEqual(Color.Empty, settings.Color);
                Assert.AreEqual(FillType.Pattern, settings.FillType);
                Assert.AreEqual("85163837-eb9e-5b43-86fb-e6d5963ea29a\0", settings.PatternId);
                Assert.AreEqual("$$$/Presets/Patterns/OpticalSquares=Optical Squares\0", settings.PatternName);
                Assert.AreEqual(null, settings.PointType);
                Assert.AreEqual(100, settings.Scale);

                Assert.AreEqual(false, settings.Linked);
                Assert.IsTrue(Math.Abs(0 - settings.HorizontalOffset) < 0.001, "Horizontal offset is incorrect");
                Assert.IsTrue(Math.Abs(0 - settings.VerticalOffset) < 0.001, "Vertical offset is incorrect");

                // Test editing
                settings.Color = Color.Green;

                patternOverlay.Opacity    = 193;
                patternOverlay.BlendMode  = BlendMode.Difference;
                settings.HorizontalOffset = 15;
                settings.VerticalOffset   = 11;

                PattResource resource;
                foreach (var globalLayerResource in im.GlobalLayerResources)
                {
                    if (globalLayerResource is PattResource)
                    {
                        resource           = (PattResource)globalLayerResource;
                        resource.PatternId = guid.ToString();
                        resource.Name      = newPatternName;
                        resource.SetPattern(newPattern, newPatternBounds);
                    }
                }

                settings.PatternName = newPatternName;

                settings.PatternId = guid.ToString() + "\0";
                im.Save(exportPath);
            }

            // Test file after edit
            using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
            {
                var patternOverlay = (PatternOverlayEffect)im.Layers[1].BlendingOptions.Effects[0];
                try
                {
                    Assert.AreEqual(BlendMode.Difference, patternOverlay.BlendMode);
                    Assert.AreEqual(193, patternOverlay.Opacity);
                    Assert.AreEqual(true, patternOverlay.IsVisible);

                    var fillSettings = patternOverlay.Settings;
                    Assert.AreEqual(Color.Empty, fillSettings.Color);
                    Assert.AreEqual(FillType.Pattern, fillSettings.FillType);

                    PattResource resource = null;
                    foreach (var globalLayerResource in im.GlobalLayerResources)
                    {
                        if (globalLayerResource is PattResource)
                        {
                            resource = (PattResource)globalLayerResource;
                        }
                    }

                    if (resource == null)
                    {
                        throw new Exception("PattResource not found");
                    }

                    // Check the pattern data
                    Assert.AreEqual(newPattern, resource.PatternData);
                    Assert.AreEqual(newPatternBounds, new Rectangle(0, 0, resource.Width, resource.Height));
                    Assert.AreEqual(guid.ToString(), resource.PatternId);
                    Assert.AreEqual(newPatternName, resource.Name);
                }
                catch (Exception e)
                {
                    String ex = e.StackTrace;
                }
            }
            //ExEnd:AddPatternEffects
        }
Exemplo n.º 11
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_Text();

            // Create directory if it is not already present.
            bool IsExists = System.IO.Directory.Exists(dataDir);

            if (!IsExists)
            {
                System.IO.Directory.CreateDirectory(dataDir);
            }

            //Instantiate Pdf instance by calling it empty constructor
            Aspose.Pdf.Generator.Pdf pdf = new Aspose.Pdf.Generator.Pdf();
            //Create a section in the Pdf object
            pdf.Sections.Add();

            pdf.IsTruetypeFontMapCached = true;
            //Specify the location where to save TruetypeFontMap.xml
            pdf.TruetypeFontMapPath = dataDir + "";

            //Create a text object and pass the string object carrying arabic text in it
            Aspose.Pdf.Generator.Text text1 = new Aspose.Pdf.Generator.Text();
            //Create a segment and add it to segments collection of text object
            Aspose.Pdf.Generator.Segment seg0 = text1.Segments.Add();
            //specify contents for segment
            seg0.Content = "أسبوز هو بائع عنصر ال";
            Aspose.Pdf.Generator.Segment seg1 = text1.Segments.Add();
            seg1.Content = ".NET";
            Aspose.Pdf.Generator.Segment seg2 = text1.Segments.Add();
            seg2.Content = "البارز";

            //Enable text alignment from right to left
            seg0.TextInfo.IsRightToLeft = true;
            seg1.TextInfo.IsRightToLeft = false;         //default
            seg2.TextInfo.IsRightToLeft = true;

            //Enable unicode character set for the text segment
            seg0.TextInfo.IsUnicode = true;
            seg1.TextInfo.IsUnicode = true;
            seg2.TextInfo.IsUnicode = true;

            //Set Font Name
            seg0.TextInfo.FontName = "Times New Roman";
            seg1.TextInfo.FontName = "Times New Roman";
            seg2.TextInfo.FontName = "Times New Roman";
            //Set font size
            seg0.TextInfo.FontSize = 14;
            seg1.TextInfo.FontSize = 14;
            seg2.TextInfo.FontSize = 14;

            //Align text to right hand side using AlignmentType enumeration
            //Make the text right aligned(The meaning of Alignment.Left and AlignmentType.Right are //exchanged when processing RTL language).
            text1.TextInfo.Alignment = Aspose.Pdf.Generator.AlignmentType.Left;

            pdf.Sections[0].Paragraphs.Add(text1);
            pdf.IsRtlInSegmentMode = true;         //default

            pdf.Save(dataDir + "AsposeOutput.pdf");
        }
        public static void Run()
        {
            // ExStart:DrawingUsingGraphicsPath
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DrawingAndFormattingImages();

            // Create an instance of BmpOptions and set its various properties
            BmpOptions ImageOptions = new BmpOptions();

            ImageOptions.BitsPerPixel = 24;

            // Create an instance of FileCreateSource and assign it to Source property
            ImageOptions.Source = new FileCreateSource(dataDir + "sample_1.bmp", false);

            // Create an instance of Image
            using (Image image = Image.Create(ImageOptions, 500, 500))
            {
                // Create and initialize an instance of Graphics
                Graphics graphics = new Graphics(image);

                // Clear the image surface with white color
                graphics.Clear(Color.White);

                // Create an instance of GraphicsPath
                GraphicsPath graphicspath = new GraphicsPath();

                // Create an instance of Figure
                Figure figure = new Figure();

                // Add EllipseShape to the figure by defining boundary Rectangle
                figure.AddShape(new EllipseShape(new RectangleF(0, 0, 499, 499)));

                // Add RectangleShape to the figure
                figure.AddShape(new RectangleShape(new RectangleF(0, 0, 499, 499)));

                // Add TextShape to the figure by defining the boundary Rectangle and Font
                figure.AddShape(new TextShape("Aspose.Imaging", new RectangleF(170, 225, 170, 100), new Font("Arial", 20), StringFormat.GenericTypographic));

                // Add figures to the GraphicsPath object
                graphicspath.AddFigures(new[] { figure });

                // Draw Path
                graphics.DrawPath(new Pen(Color.Blue), graphicspath);

                // Create an instance of HatchBrush and set its properties
                HatchBrush hatchbrush = new HatchBrush();
                hatchbrush.BackgroundColor = Color.Brown;
                hatchbrush.ForegroundColor = Color.Blue;
                hatchbrush.HatchStyle      = HatchStyle.Vertical;

                // Fill path by supplying the brush and GraphicsPath objects
                graphics.FillPath(hatchbrush, graphicspath);

                // Save the changes.
                image.Save();

                // Display Status.
                Console.WriteLine("Processing completed successfully.");
            }
            // ExEnd:DrawingUsingGraphicsPath
        }
        public static void Run()
        {
            //Source directory
            string sourceDir = RunExamples.Get_SourceDirectory();

            //Output directory
            string outputDir = RunExamples.Get_OutputDirectory();

            //Create a datatable and add column named TestFormula
            DataTable dt = new DataTable();

            dt.Columns.Add("TestFormula");

            //Create first row with formula (which basically concatenates three strings)
            DataRow dr = dt.NewRow();

            dr["TestFormula"] = "=\"01-This \" & \"is \" & \"concatenation\"";
            dt.Rows.Add(dr);

            //Create second row like above
            dr = dt.NewRow();
            dr["TestFormula"] = "=\"02-This \" & \"is \" & \"concatenation\"";
            dt.Rows.Add(dr);

            //Create third row like above
            dr = dt.NewRow();
            dr["TestFormula"] = "=\"03-This \" & \"is \" & \"concatenation\"";
            dt.Rows.Add(dr);

            //Create fourth row like above
            dr = dt.NewRow();
            dr["TestFormula"] = "=\"04-This \" & \"is \" & \"concatenation\"";
            dt.Rows.Add(dr);

            //Create fifth row like above
            dr = dt.NewRow();
            dr["TestFormula"] = "=\"05-This \" & \"is \" & \"concatenation\"";
            dt.Rows.Add(dr);

            //Set the name of the data table
            dt.TableName = "MyDataSource";

            //Create a workbook
            Workbook wb = new Workbook();

            //Access first worksheet
            Worksheet ws = wb.Worksheets[0];

            //Put the smart marker field with formula parameter in cell A1
            ws.Cells["A1"].PutValue("&=MyDataSource.TestFormula(Formula)");

            //Create workbook designer, set data source and process it
            WorkbookDesigner wd = new WorkbookDesigner(wb);

            wd.SetDataSource(dt);
            wd.Process();

            //Save the workbook in xlsx format
            wb.Save(outputDir + "outputUsingFormulaParameterInSmartMarkerField.xlsx");

            Console.WriteLine("UsingFormulaParameterInSmartMarkerField executed successfully.\r\n");
        }
        public static void Run()
        {
            string baseFolder = RunExamples.GetDataDir_PSD();
            string output     = RunExamples.GetDataDir_Output();

            //ExStart:SupportOfUpdatingLinkedSmartObjects
            //ExSummary:The following code demonstrates the support of updating Linked Smart objects.

            void AssertAreEqual(object actual, object expected)
            {
                var areEqual = object.Equals(actual, expected);

                if (!areEqual && actual is Array && expected is Array)
                {
                    var actualArray   = (Array)actual;
                    var expectedArray = (Array)actual;
                    if (actualArray.Length == expectedArray.Length)
                    {
                        for (int i = 0; i < actualArray.Length; i++)
                        {
                            if (!object.Equals(actualArray.GetValue(i), expectedArray.GetValue(i)))
                            {
                                break;
                            }
                        }

                        areEqual = true;
                    }
                }

                if (!areEqual)
                {
                    throw new FormatException(
                              string.Format("Actual value {0} are not equal to expected {1}.", actual, expected));
                }
            }

            // This example demonstrates how to update the external or embedded smart object layer using these methods:
            // RelinkToFile, UpdateModifiedContent, ExportContents
            ExampleOfUpdatingSmartObjectLayer("rgb8_2x2_linked2.psd", 0x53, 0, 0, 2, 2, FileFormat.Png);
            ExampleOfUpdatingSmartObjectLayer("r-embedded-png.psd", 0x207, 0, 0, 0xb, 0x10, FileFormat.Png);

            void ExampleOfUpdatingSmartObjectLayer(
                string filePath,
                int contentsLength,
                int left,
                int top,
                int right,
                int bottom,
                FileFormat format)
            {
                // This example demonstrates how to change the smart object layer in the PSD file and export / update its contents.
                string fileName = Path.GetFileNameWithoutExtension(filePath);
                string dataDir  = output + "updating_output\\";

                filePath = baseFolder + filePath;
                string pngOutputPath  = dataDir + fileName + "_modified.png";
                string png2OutputPath = dataDir + fileName + "_updated_modified.png";
                string psd2OutputPath = dataDir + fileName + "_updated_modified.psd";
                string exportPath     = dataDir + fileName + "_exported." + GetFormatExt(format);

                using (PsdImage image = (PsdImage)Image.Load(filePath))
                {
                    var smartObjectLayer = (SmartObjectLayer)image.Layers[0];
                    var contentType      = smartObjectLayer.ContentType;
                    AssertAreEqual(contentsLength, smartObjectLayer.Contents.Length);
                    AssertAreEqual(left, smartObjectLayer.ContentsBounds.Left);
                    AssertAreEqual(top, smartObjectLayer.ContentsBounds.Top);
                    AssertAreEqual(right, smartObjectLayer.ContentsBounds.Right);
                    AssertAreEqual(bottom, smartObjectLayer.ContentsBounds.Bottom);

                    if (contentType == SmartObjectType.AvailableLinked)
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(exportPath));
                        // Let's export the external smart object image from the PSD smart object layer to a new location
                        // because we are going to modify it.
                        smartObjectLayer.ExportContents(exportPath);
                        smartObjectLayer.RelinkToFile(exportPath);
                    }

                    // Let's invert the content of the smart object: inner (not cached) image
                    using (var innerImage = (RasterImage)smartObjectLayer.LoadContents(new LoadOptions()))
                    {
                        InvertImage(innerImage);
                        using (var stream = new MemoryStream())
                        {
                            innerImage.Save(stream);
                            smartObjectLayer.Contents = stream.ToArray();
                        }
                    }

                    // Let's check whether the modified content does not affect rendering yet.
                    image.Save(pngOutputPath, new PngOptions()
                    {
                        ColorType = PngColorType.TruecolorWithAlpha
                    });

                    smartObjectLayer.UpdateModifiedContent();

                    // Let's check whether the updated content affects rendering and the psd image is saved correctly
                    image.Save(psd2OutputPath, new PsdOptions(image));
                    image.Save(png2OutputPath, new PngOptions()
                    {
                        ColorType = PngColorType.TruecolorWithAlpha
                    });
                }
            }

            // This example demonstrates how to convert the embedded smart object to external linked contents using the ConvertToLinked method.
            ExampleOfEmbeddedSmartObjectLayerToLinkedConversion("new_panama-papers-4.psd", 0x10caa, 0, 0, 0x280, 0x169, FileFormat.Jpeg);
            ExampleOfEmbeddedSmartObjectLayerToLinkedConversion("r3-embedded.psd", 0x207, 0, 0, 0xb, 0x10, FileFormat.Png);
            ExampleOfEmbeddedSmartObjectLayerToLinkedConversion("r-embedded-tiff.psd", 0xca94, 0, 0, 0xb, 0x10, FileFormat.Tiff);
            ExampleOfEmbeddedSmartObjectLayerToLinkedConversion("r-embedded-bmp.psd", 0x278, 0, 0, 0xb, 0x10, FileFormat.Bmp);
            ExampleOfEmbeddedSmartObjectLayerToLinkedConversion("r-embedded-gif.psd", 0x3ec, 0, 0, 0xb, 0x10, FileFormat.Gif);
            ExampleOfEmbeddedSmartObjectLayerToLinkedConversion("r-embedded-jpeg.psd", 0x327, 0, 0, 0xb, 0x10, FileFormat.Jpeg);
            ExampleOfEmbeddedSmartObjectLayerToLinkedConversion("r-embedded-jpeg2000.psd", 0x519f, 0, 0, 0xb, 0x10, FileFormat.Jpeg2000);
            ExampleOfEmbeddedSmartObjectLayerToLinkedConversion("r-embedded-psd.psd", 0xc074, 0, 0, 0xb, 0x10, FileFormat.Psd);
            ExampleOfEmbeddedSmartObjectLayerToLinkedConversion("r-embedded-png.psd", 0x207, 0, 0, 0xb, 0x10, FileFormat.Png);

            void ExampleOfEmbeddedSmartObjectLayerToLinkedConversion(
                string filePath,
                int contentsLength,
                int left,
                int top,
                int right,
                int bottom,
                FileFormat format)
            {
                // This demonstrates how to convert an embedded smart object layer in the PSD file to external one.
                var    formatExt = GetFormatExt(format);
                string fileName  = Path.GetFileNameWithoutExtension(filePath);
                string dataDir   = output + "to_linked_output\\";

                filePath = baseFolder + filePath;
                string pngOutputPath = dataDir + fileName + "_to_external.png";
                string psdOutputPath = dataDir + fileName + "_to_external.psd";
                string externalPath  = dataDir + fileName + "_external." + formatExt;

                using (PsdImage image = (PsdImage)Image.Load(filePath))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(externalPath));
                    var smartObjectLayer = (SmartObjectLayer)image.Layers[0];
                    smartObjectLayer.ConvertToLinked(externalPath);

                    AssertAreEqual(contentsLength, smartObjectLayer.Contents.Length);
                    AssertAreEqual(left, smartObjectLayer.ContentsBounds.Left);
                    AssertAreEqual(top, smartObjectLayer.ContentsBounds.Top);
                    AssertAreEqual(right, smartObjectLayer.ContentsBounds.Right);
                    AssertAreEqual(bottom, smartObjectLayer.ContentsBounds.Bottom);
                    AssertAreEqual(SmartObjectType.AvailableLinked, smartObjectLayer.ContentType);

                    // Let's check if the converted image is saved correctly
                    image.Save(psdOutputPath, new PsdOptions(image));
                    image.Save(pngOutputPath, new PngOptions()
                    {
                        ColorType = PngColorType.TruecolorWithAlpha
                    });
                }

                using (PsdImage image = (PsdImage)Image.Load(psdOutputPath))
                {
                    var smartObjectLayer = (SmartObjectLayer)image.Layers[0];
                    AssertAreEqual(contentsLength, smartObjectLayer.Contents.Length);
                    AssertAreEqual(left, smartObjectLayer.ContentsBounds.Left);
                    AssertAreEqual(top, smartObjectLayer.ContentsBounds.Top);
                    AssertAreEqual(right, smartObjectLayer.ContentsBounds.Right);
                    AssertAreEqual(bottom, smartObjectLayer.ContentsBounds.Bottom);
                    AssertAreEqual(SmartObjectType.AvailableLinked, smartObjectLayer.ContentType);
                }
            }

            // This example demonstrates how to embed one external smart object layer or all linked layers in the PSD file using the EmbedLinked method.
            ExampleOfLinkedSmartObjectLayerToEmbeddedConversion("rgb8_2x2_linked.psd", 0x53, 0, 0, 2, 2, FileFormat.Png);
            ExampleOfLinkedSmartObjectLayerToEmbeddedConversion("rgb8_2x2_linked2.psd", 0x53, 0, 0, 2, 2, FileFormat.Png);
            void ExampleOfLinkedSmartObjectLayerToEmbeddedConversion(
                string filePath,
                int contentsLength,
                int left,
                int top,
                int right,
                int bottom,
                FileFormat format)
            {
                string fileName = Path.GetFileNameWithoutExtension(filePath);
                string dataDir  = output + "to_embedded_output\\";

                filePath = baseFolder + filePath;
                string pngOutputPath = dataDir + fileName + "_to_embedded.png";
                string psdOutputPath = dataDir + fileName + "_to_embedded.psd";

                using (PsdImage image = (PsdImage)Image.Load(filePath))
                {
                    var smartObjectLayer0 = (SmartObjectLayer)image.Layers[0];
                    smartObjectLayer0.EmbedLinked();
                    AssertAreEqual(contentsLength, smartObjectLayer0.Contents.Length);
                    AssertAreEqual(left, smartObjectLayer0.ContentsBounds.Left);
                    AssertAreEqual(top, smartObjectLayer0.ContentsBounds.Top);
                    AssertAreEqual(right, smartObjectLayer0.ContentsBounds.Right);
                    AssertAreEqual(bottom, smartObjectLayer0.ContentsBounds.Bottom);
                    if (image.Layers.Length >= 2)
                    {
                        var smartObjectLayer1 = (SmartObjectLayer)image.Layers[1];
                        AssertAreEqual(SmartObjectType.Embedded, smartObjectLayer0.ContentType);
                        AssertAreEqual(SmartObjectType.AvailableLinked, smartObjectLayer1.ContentType);

                        image.SmartObjectProvider.EmbedAllLinked();
                        foreach (Layer layer in image.Layers)
                        {
                            var smartLayer = layer as SmartObjectLayer;
                            if (smartLayer != null)
                            {
                                AssertAreEqual(SmartObjectType.Embedded, smartLayer.ContentType);
                            }
                        }
                    }

                    Directory.CreateDirectory(Path.GetDirectoryName(psdOutputPath));
                    // Let's check if the converted image is saved correctly
                    image.Save(psdOutputPath, new PsdOptions(image));
                    image.Save(pngOutputPath, new PngOptions()
                    {
                        ColorType = PngColorType.TruecolorWithAlpha
                    });
                }

                using (PsdImage image = (PsdImage)Image.Load(psdOutputPath))
                {
                    var smartObjectLayer = (SmartObjectLayer)image.Layers[0];
                    AssertAreEqual(contentsLength, smartObjectLayer.Contents.Length);
                    AssertAreEqual(left, smartObjectLayer.ContentsBounds.Left);
                    AssertAreEqual(top, smartObjectLayer.ContentsBounds.Top);
                    AssertAreEqual(right, smartObjectLayer.ContentsBounds.Right);
                    AssertAreEqual(bottom, smartObjectLayer.ContentsBounds.Bottom);
                    AssertAreEqual(SmartObjectType.Embedded, smartObjectLayer.ContentType);
                }
            }

            // This example demonstrates how to change the Adobe® Photoshop® external smart object layer and export / update its contents
            // using the ExportContents and ReplaceContents methods.
            ExampleOfExternalSmartObjectLayerSupport("rgb8_2x2_linked.psd", 0x53, 0, 0, 2, 2, FileFormat.Png);
            ExampleOfExternalSmartObjectLayerSupport("rgb8_2x2_linked2.psd", 0x4aea, 0, 0, 10, 10, FileFormat.Psd);
            void ExampleOfExternalSmartObjectLayerSupport(string filePath, int contentsLength, int left, int top, int right, int bottom, FileFormat format)
            {
                string formatExt = GetFormatExt(format);
                string fileName  = Path.GetFileNameWithoutExtension(filePath);
                string dataDir   = output + "external_support_output\\";

                filePath = baseFolder + filePath;
                string pngOutputPath  = dataDir + fileName + ".png";
                string psdOutputPath  = dataDir + fileName + ".psd";
                string linkOutputPath = dataDir + fileName + "_inverted." + formatExt;
                string png2OutputPath = dataDir + fileName + "_updated.png";
                string psd2OutputPath = dataDir + fileName + "_updated.psd";
                string exportPath     = dataDir + fileName + "_export." + formatExt;

                using (PsdImage image = (PsdImage)Image.Load(filePath))
                {
                    var smartObjectLayer = (SmartObjectLayer)image.Layers[image.Layers.Length - 1];
                    AssertAreEqual(left, smartObjectLayer.ContentsBounds.Left);
                    AssertAreEqual(top, smartObjectLayer.ContentsBounds.Top);
                    AssertAreEqual(right, smartObjectLayer.ContentsBounds.Right);
                    AssertAreEqual(bottom, smartObjectLayer.ContentsBounds.Bottom);
                    AssertAreEqual(contentsLength, smartObjectLayer.Contents.Length);
                    AssertAreEqual(SmartObjectType.AvailableLinked, smartObjectLayer.ContentType);

                    Directory.CreateDirectory(Path.GetDirectoryName(exportPath));
                    // Let's export the linked smart object image from the PSD smart object layer
                    smartObjectLayer.ExportContents(exportPath);

                    // Let's check if the original image isz saved correctly
                    image.Save(psdOutputPath, new PsdOptions(image));
                    image.Save(pngOutputPath, new PngOptions()
                    {
                        ColorType = PngColorType.TruecolorWithAlpha
                    });

                    using (var innerImage = (RasterImage)smartObjectLayer.LoadContents(null))
                    {
                        AssertAreEqual(format, innerImage.FileFormat);

                        // Let's invert the linked smart object image
                        InvertImage(innerImage);
                        innerImage.Save(linkOutputPath);

                        // Let's replace the linked smart object image in the PSD layer
                        smartObjectLayer.ReplaceContents(linkOutputPath);
                    }

                    // Let's check if the updated image is saved correctly
                    image.Save(psd2OutputPath, new PsdOptions(image));
                    image.Save(png2OutputPath, new PngOptions()
                    {
                        ColorType = PngColorType.TruecolorWithAlpha
                    });
                }
            }

            // Inverts the image.
            void InvertImage(RasterImage innerImage)
            {
                var innerPsdImage = innerImage as PsdImage;

                if (innerPsdImage != null)
                {
                    InvertRasterImage(innerPsdImage.Layers[0]);
                }
                else
                {
                    InvertRasterImage(innerImage);
                }
            }

            // Inverts the raster image.
            void InvertRasterImage(RasterImage innerImage)
            {
                var pixels = innerImage.LoadArgb32Pixels(innerImage.Bounds);

                for (int i = 0; i < pixels.Length; i++)
                {
                    var pixel = pixels[i];
                    var alpha = (int)(pixel & 0xff000000);
                    pixels[i] = (~(pixel & 0x00ffffff)) | alpha;
                }

                innerImage.SaveArgb32Pixels(innerImage.Bounds, pixels);
            }

            // Gets the format extension.
            string GetFormatExt(FileFormat format)
            {
                string formatExt = format == FileFormat.Jpeg2000 ? "jpf" : format.ToString().ToLowerInvariant();

                return(formatExt);
            }

            //ExEnd:SupportOfUpdatingLinkedSmartObjects

            Console.WriteLine("SupportOfUpdatingLinkedSmartObjects executed successfully");
        }
Exemplo n.º 15
0
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            // Load source excel file containing sample pivot table
            Workbook wb = new Workbook(dataDir + "sample-pivot-table.xlsx");

            // Access first worksheet that contains pivot table data
            Worksheet dataSheet = wb.Worksheets[0];

            // Access cell A3 and sets its data
            Cells cells = dataSheet.Cells;
            Cell  cell  = cells["A3"];

            cell.PutValue("FooBar");

            // Access cell B3, sets its data. We set B3 a very long string which has more than 255 characters
            string longStr = "Very long text 1. very long text 2. very long text 3. very long text 4. very long text 5. very long text 6. very long text 7. very long text 8. very long text 9. very long text 10. very long text 11. very long text 12. very long text 13. very long text 14. very long text 15. very long text 16. very long text 17. very long text 18. very long text 19. very long text 20. End of text.";

            cell = cells["B3"];
            cell.PutValue(longStr);

            // Print the length of cell B3 string
            Console.WriteLine("Length of original data string: " + cell.StringValue.Length);

            // Access cell C3 and sets its data
            cell = cells["C3"];
            cell.PutValue("closed");

            // Access cell D3 and sets its data
            cell = cells["D3"];
            cell.PutValue("2016/07/21");

            // Access the second worksheet that contains pivot table
            Worksheet pivotSheet = wb.Worksheets[1];

            // Access the pivot table
            PivotTable pivotTable = pivotSheet.PivotTables[0];

            // IsExcel2003Compatible property tells if PivotTable is compatible for Excel2003 while refreshing PivotTable.
            // If it is true, a string must be less than or equal to 255 characters, so if the string is greater than 255 characters,
            // it will be truncated. If false, a string will not have the aforementioned restriction. The default value is true.
            pivotTable.IsExcel2003Compatible = true;
            pivotTable.RefreshData();
            pivotTable.CalculateData();

            // Check the value of cell B5 of pivot sheet.
            // It will be 255 because we have set IsExcel2003Compatible property to true. All the data after 255 characters has been truncated
            Cell b5 = pivotSheet.Cells["B5"];

            Console.WriteLine("Length of cell B5 after setting IsExcel2003Compatible property to True: " + b5.StringValue.Length);

            // Now set IsExcel2003Compatible property to false and again refresh
            pivotTable.IsExcel2003Compatible = false;
            pivotTable.RefreshData();
            pivotTable.CalculateData();

            // Now it will print 383 the original length of cell data. The data has not been truncated now.
            b5 = pivotSheet.Cells["B5"];
            Console.WriteLine("Length of cell B5 after setting IsExcel2003Compatible property to False: " + b5.StringValue.Length);

            // Set the row height and column width of cell B5 and also wrap its text
            pivotSheet.Cells.SetRowHeight(b5.Row, 100);
            pivotSheet.Cells.SetColumnWidth(b5.Column, 65);
            Style st = b5.GetStyle();

            st.IsTextWrapped = true;
            b5.SetStyle(st);

            // Save workbook in xlsx format
            wb.Save(dataDir + "SpecifyCompatibility_out.xlsx", SaveFormat.Xlsx);
            // ExEnd:1
        }
        public static void Run()
        {
            //ExStart:GradientFillLayer

            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_PSD();

            string sourceFileName = dataDir + "ComplexGradientFillLayer.psd";
            string outputFile     = dataDir + "ComplexGradientFillLayer_output.psd";
            var    image          = (PsdImage)Image.Load(sourceFileName);

            using (image)
            {
                foreach (var layer in image.Layers)
                {
                    if (layer is FillLayer)
                    {
                        var fillLayer = (FillLayer)layer;
                        if (fillLayer.FillSettings.FillType != FillType.Gradient)
                        {
                            throw new Exception("Wrong Fill Layer");
                        }
                        var settings = (IGradientFillSettings)fillLayer.FillSettings;

                        if (
                            Math.Abs(settings.Angle - 45) > 0.25 ||
                            settings.Dither != true ||
                            settings.AlignWithLayer != false ||
                            settings.Reverse != false ||
                            Math.Abs(settings.HorizontalOffset - (-39)) > 0.25 ||
                            Math.Abs(settings.VerticalOffset - (-5)) > 0.25 ||
                            settings.TransparencyPoints.Length != 3 ||
                            settings.ColorPoints.Length != 2 ||
                            Math.Abs(100.0 - settings.TransparencyPoints[0].Opacity) > 0.25 ||
                            settings.TransparencyPoints[0].Location != 0 ||
                            settings.TransparencyPoints[0].MedianPointLocation != 50 ||
                            settings.ColorPoints[0].Color != Color.FromArgb(203, 64, 140) ||
                            settings.ColorPoints[0].Location != 0 ||
                            settings.ColorPoints[0].MedianPointLocation != 50)
                        {
                            throw new Exception("Gradient Fill was not read correctly");
                        }

                        settings.Angle            = 0.0;
                        settings.Dither           = false;
                        settings.AlignWithLayer   = true;
                        settings.Reverse          = true;
                        settings.HorizontalOffset = 25;
                        settings.VerticalOffset   = -15;

                        var colorPoints        = new List <IGradientColorPoint>(settings.ColorPoints);
                        var transparencyPoints = new List <IGradientTransparencyPoint>(settings.TransparencyPoints);

                        colorPoints.Add(new GradientColorPoint()
                        {
                            Color               = Color.Violet,
                            Location            = 4096,
                            MedianPointLocation = 75
                        });

                        colorPoints[1].Location = 3000;

                        transparencyPoints.Add(new GradientTransparencyPoint()
                        {
                            Opacity             = 80.0,
                            Location            = 4096,
                            MedianPointLocation = 25
                        });

                        transparencyPoints[2].Location = 3000;
                        settings.ColorPoints           = colorPoints.ToArray();
                        settings.TransparencyPoints    = transparencyPoints.ToArray();
                        fillLayer.Update();
                        image.Save(outputFile, new PsdOptions(image));
                        break;
                    }
                }
            }

            //ExEnd:GradientFillLayer
        }
Exemplo n.º 17
0
        public static void Run()
        {
            // ExStart:DrawXFormOnPage
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Operators();


            string imageFile = dataDir + "aspose-logo.jpg";
            string inFile    = dataDir + "DrawXFormOnPage.pdf";
            string outFile   = dataDir + "blank-sample2_out_.pdf";

            using (Document doc = new Document(inFile))
            {
                OperatorCollection pageContents = doc.Pages[1].Contents;

                // the sample demonstrates
                // GSave/GRestore operators usage
                // ContatenateMatrix operator usage to position xForm
                // Do operator usage to draw xForm on page

                // Wrap existing contents with GSave/GRestore operators pair
                //        this is to get initial graphics state at the and of existing contents
                //        otherwise there might remain some undesirable transformations at the end of existing operators chain
                pageContents.Insert(1, new Operator.GSave());
                pageContents.Add(new Operator.GRestore());

                // Add save graphics state operator to properly clear graphics state after new commands
                pageContents.Add(new Operator.GSave());

                #region create xForm

                // Create xForm
                XForm form = XForm.CreateNewForm(doc.Pages[1], doc);
                doc.Pages[1].Resources.Forms.Add(form);
                form.Contents.Add(new Operator.GSave());
                // Define image width and heigh
                form.Contents.Add(new Operator.ConcatenateMatrix(200, 0, 0, 200, 0, 0));
                // Load image into stream
                Stream imageStream = new FileStream(imageFile, FileMode.Open);
                // Add image to Images collection of the XForm Resources
                form.Resources.Images.Add(imageStream);
                XImage ximage = form.Resources.Images[form.Resources.Images.Count];
                // Using Do operator: this operator draws image
                form.Contents.Add(new Operator.Do(ximage.Name));
                form.Contents.Add(new Operator.GRestore());

                #endregion

                pageContents.Add(new Operator.GSave());
                // Place form to the x=100 y=500 coordinates
                pageContents.Add(new Operator.ConcatenateMatrix(1, 0, 0, 1, 100, 500));
                // Draw form with Do operator
                pageContents.Add(new Operator.Do(form.Name));
                pageContents.Add(new Operator.GRestore());

                pageContents.Add(new Operator.GSave());
                // Place form to the x=100 y=300 coordinates
                pageContents.Add(new Operator.ConcatenateMatrix(1, 0, 0, 1, 100, 300));
                // Draw form with Do operator
                pageContents.Add(new Operator.Do(form.Name));
                pageContents.Add(new Operator.GRestore());

                // Restore grahics state with GRestore after the GSave
                pageContents.Add(new Operator.GRestore());
                doc.Save(outFile);
            }
            // ExEnd:DrawXFormOnPage
        }
Exemplo n.º 18
0
        public static void Run()
        {
            // ExStart:CreateDynamicCharts
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            // Create an instance of Workbook
            var book = new Workbook();
            // Access first worksheet from the collection
            var sheet = book.Worksheets[0];
            // Access cells collection of the first worksheet
            var cells = sheet.Cells;

            // Insert data column wise
            cells["A1"].PutValue("Category");
            cells["A2"].PutValue("Fruit");
            cells["A3"].PutValue("Fruit");
            cells["A4"].PutValue("Fruit");
            cells["A5"].PutValue("Fruit");
            cells["A6"].PutValue("Vegetables");
            cells["A7"].PutValue("Vegetables");
            cells["A8"].PutValue("Vegetables");
            cells["A9"].PutValue("Vegetables");
            cells["A10"].PutValue("Beverages");
            cells["A11"].PutValue("Beverages");
            cells["A12"].PutValue("Beverages");

            cells["B1"].PutValue("Food");
            cells["B2"].PutValue("Apple");
            cells["B3"].PutValue("Banana");
            cells["B4"].PutValue("Apricot");
            cells["B5"].PutValue("Grapes");
            cells["B6"].PutValue("Carrot");
            cells["B7"].PutValue("Onion");
            cells["B8"].PutValue("Cabage");
            cells["B9"].PutValue("Potatoe");
            cells["B10"].PutValue("Coke");
            cells["B11"].PutValue("Coladas");
            cells["B12"].PutValue("Fizz");

            cells["C1"].PutValue("Cost");
            cells["C2"].PutValue(2.2);
            cells["C3"].PutValue(3.1);
            cells["C4"].PutValue(4.1);
            cells["C5"].PutValue(5.1);
            cells["C6"].PutValue(4.4);
            cells["C7"].PutValue(5.4);
            cells["C8"].PutValue(6.5);
            cells["C9"].PutValue(5.3);
            cells["C10"].PutValue(3.2);
            cells["C11"].PutValue(3.6);
            cells["C12"].PutValue(5.2);

            cells["D1"].PutValue("Profit");
            cells["D2"].PutValue(0.1);
            cells["D3"].PutValue(0.4);
            cells["D4"].PutValue(0.5);
            cells["D5"].PutValue(0.6);
            cells["D6"].PutValue(0.7);
            cells["D7"].PutValue(1.3);
            cells["D8"].PutValue(0.8);
            cells["D9"].PutValue(1.3);
            cells["D10"].PutValue(2.2);
            cells["D11"].PutValue(2.4);
            cells["D12"].PutValue(3.3);

            // Create ListObject, Get the List objects collection in the first worksheet
            var listObjects = sheet.ListObjects;

            // Add a List based on the data source range with headers on
            var index = listObjects.Add(0, 0, 11, 3, true);

            sheet.AutoFitColumns();

            // Create chart based on ListObject
            index = sheet.Charts.Add(ChartType.Column, 21, 1, 35, 18);
            var chart = sheet.Charts[index];

            chart.SetChartDataRange("A1:D12", true);
            chart.NSeries.CategoryData = "A2:B12";

            // Save spreadsheet
            book.Save(dataDir + "output_out_.xlsx");
            // ExEnd:CreateDynamicCharts
        }
        public static void Run()
        {
            //ExStart:UpdateProjectAndRescheduleUncompletedWork
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);

            // Create a new project and set start date
            Project project = new Project();

            project.Set(Prj.StartDate, new DateTime(2014, 1, 27, 8, 0, 0));

            // Add new tasks
            Task task1 = project.RootTask.Children.Add("Task 1");
            Task task2 = project.RootTask.Children.Add("Task 2");

            task2.Set(Tsk.Duration, task2.ParentProject.GetDuration(16, TimeUnitType.Hour));
            Task task3 = project.RootTask.Children.Add("Task 3");

            task3.Set(Tsk.Duration, task2.ParentProject.GetDuration(24, TimeUnitType.Hour));
            Task task4 = project.RootTask.Children.Add("Task 4");

            task4.Set(Tsk.Duration, task2.ParentProject.GetDuration(16, TimeUnitType.Hour));
            Task task5 = project.RootTask.Children.Add("Task 5");

            task5.Set(Tsk.Duration, task2.ParentProject.GetDuration(16, TimeUnitType.Hour));

            // Add links between tasks
            TaskLink link12 = project.TaskLinks.Add(task1, task2, TaskLinkType.FinishToStart);
            TaskLink link23 = project.TaskLinks.Add(task2, task3, TaskLinkType.FinishToStart);

            // One day lag
            link23.LinkLag = 4800;
            project.TaskLinks.Add(task3, task4, TaskLinkType.FinishToStart);
            project.TaskLinks.Add(task4, task5, TaskLinkType.FinishToStart);

            // Add new tasks
            Task task6 = project.RootTask.Children.Add("Task 6");
            Task task7 = project.RootTask.Children.Add("Task 7");

            task7.Set(Tsk.Duration, task7.ParentProject.GetDuration(24, TimeUnitType.Hour));
            Task task8 = project.RootTask.Children.Add("Task 8");

            task8.Set(Tsk.Duration, task2.ParentProject.GetDuration(16, TimeUnitType.Hour));
            Task task9 = project.RootTask.Children.Add("Task 9");

            task9.Set(Tsk.Duration, task2.ParentProject.GetDuration(16, TimeUnitType.Hour));
            Task task10 = project.RootTask.Children.Add("Task 10");

            // Add links between tasks
            project.TaskLinks.Add(task6, task7, TaskLinkType.FinishToStart);
            project.TaskLinks.Add(task7, task8, TaskLinkType.FinishToStart);
            project.TaskLinks.Add(task8, task9, TaskLinkType.FinishToStart);
            project.TaskLinks.Add(task9, task10, TaskLinkType.FinishToStart);
            task6.Set(Tsk.IsManual, true);
            task7.Set(Tsk.IsManual, true);
            task8.Set(Tsk.IsManual, true);
            task9.Set(Tsk.IsManual, true);
            task10.Set(Tsk.IsManual, true);

            // Save project before and after updating work as completed
            project.Save(dataDir + "RescheduleUncompletedWork_not updated_out.xml", SaveFileFormat.XML);
            project.UpdateProjectWorkAsComplete(new DateTime(2014, 1, 28, 17, 0, 0), false);
            project.Save(dataDir + "RescheduleUncompletedWork_updated_out.xml", SaveFileFormat.XML);

            // Save project after rescheduling uncompleted work
            project.RescheduleUncompletedWorkToStartAfter(new DateTime(2014, 2, 7, 8, 0, 0));
            project.Save(dataDir + "RescheduleUncompletedWork_rescheduled_out.xml", SaveFileFormat.XML);
            //ExEnd:UpdateProjectAndRescheduleUncompletedWork
        }
Exemplo n.º 20
0
        public static void Run()
        {
            // ExStart:CreationOfDesignerSpreadsheet
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            // Create an instance of Workbook
            var book = new Workbook();

            // Access the first, default Worksheet by passing its index
            var dataSheet = book.Worksheets[0];

            // Name the Worksheet for later reference
            dataSheet.Name = "ChartData";

            // Access the CellsCollection of first Worksheet
            var cells = dataSheet.Cells;

            // Insert static data (headers)
            cells["B1"].PutValue("Item 1");
            cells["C1"].PutValue("Item 2");
            cells["D1"].PutValue("Item 3");
            cells["E1"].PutValue("Item 4");
            cells["F1"].PutValue("Item 5");
            cells["G1"].PutValue("Item 6");
            cells["H1"].PutValue("Item 7");
            cells["I1"].PutValue("Item 8");
            cells["J1"].PutValue("Item 9");
            cells["K1"].PutValue("Item 10");
            cells["L1"].PutValue("Item 11");
            cells["M1"].PutValue("Item 12");


            // Place Smart Markers
            cells["A2"].PutValue("&=Sales.Year");
            cells["B2"].PutValue("&=Sales.Item1");
            cells["C2"].PutValue("&=Sales.Item2");
            cells["D2"].PutValue("&=Sales.Item3");
            cells["E2"].PutValue("&=Sales.Item4");
            cells["F2"].PutValue("&=Sales.Item5");
            cells["G2"].PutValue("&=Sales.Item6");
            cells["H2"].PutValue("&=Sales.Item7");
            cells["I2"].PutValue("&=Sales.Item8");
            cells["J2"].PutValue("&=Sales.Item9");
            cells["K2"].PutValue("&=Sales.Item10");
            cells["L2"].PutValue("&=Sales.Item11");
            cells["M2"].PutValue("&=Sales.Item12");
            // ExEnd:CreationOfDesignerSpreadsheet

            // ExStart:ProcessingDesignerSpreadsheet
            // Create an instance of DataTable and name is according to the Smart Markers
            var table = new DataTable("Sales");

            /*
             * Add columns to the newly created DataTable while specifying the column type
             * It is important that the DataTable should have at least one column for each
             * Smart Marker entry from the designer spreadsheet
             */
            table.Columns.Add("Year", typeof(string));
            table.Columns.Add("Item1", typeof(int));
            table.Columns.Add("Item2", typeof(int));
            table.Columns.Add("Item3", typeof(int));
            table.Columns.Add("Item4", typeof(int));
            table.Columns.Add("Item5", typeof(int));
            table.Columns.Add("Item6", typeof(int));
            table.Columns.Add("Item7", typeof(int));
            table.Columns.Add("Item8", typeof(int));
            table.Columns.Add("Item9", typeof(int));
            table.Columns.Add("Item10", typeof(int));
            table.Columns.Add("Item11", typeof(int));
            table.Columns.Add("Item12", typeof(int));

            // Add some rows with data to the DataTable
            table.Rows.Add("2000", 2310, 0, 110, 15, 20, 25, 30, 1222, 200, 421, 210, 133);
            table.Rows.Add("2005", 1508, 0, 170, 280, 190, 400, 105, 132, 303, 199, 120, 100);
            table.Rows.Add("2010", 0, 210, 230, 140, 150, 160, 170, 110, 1999, 1229, 1120, 2300);
            table.Rows.Add("2015", 3818, 320, 340, 260, 210, 310, 220, 0, 0, 0, 0, 122);
            // ExEnd:ProcessingDesignerSpreadsheet

            // ExStart:ProcessingOfSmartMarkers
            // Create an instance of WorkbookDesigner class
            var designer = new WorkbookDesigner();

            // Assign the Workbook property to the instance of Workbook created in first step
            designer.Workbook = book;

            // Set the data source
            designer.SetDataSource(table);

            // Call Process method to populate data
            designer.Process();
            // ExEnd:ProcessingOfSmartMarkers

            // ExStart:CreationOfChart

            /*
             * Save the number of rows & columns from the source DataTable in seperate variables.
             * These values will be used later to identify the chart's data range from DataSheet
             */
            int chartRows = table.Rows.Count;
            int chartCols = table.Columns.Count;

            // Add a new Worksheet of type Chart to Workbook
            int chartSheetIdx = book.Worksheets.Add(SheetType.Chart);

            // Access the newly added Worksheet via its index
            var chartSheet = book.Worksheets[chartSheetIdx];

            // Name the Worksheet
            chartSheet.Name = "Chart";

            // Add a chart of type ColumnStacked to newly added Worksheet
            int chartIdx = chartSheet.Charts.Add(ChartType.ColumnStacked, 0, 0, chartRows, chartCols);

            // Access the newly added Chart via its index
            var chart = chartSheet.Charts[chartIdx];

            // Set the data range for the chart
            chart.SetChartDataRange(dataSheet.Name + "!A1:" + CellsHelper.ColumnIndexToName(chartCols - 1) + (chartRows + 1).ToString(), false);

            // Set the chart to size with window
            chart.SizeWithWindow = true;

            // Set the format for the tick labels
            chart.ValueAxis.TickLabels.NumberFormat = "$###,### K";

            // Set chart title
            chart.Title.Text = "Sales Summary";

            // Set ChartSheet an active sheet
            book.Worksheets.ActiveSheetIndex = chartSheetIdx;

            // Save the final result
            book.Save(dataDir + "report_out.xlsx");
            // ExEnd:CreationOfChart
        }
Exemplo n.º 21
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_Charts();

            // Create directory if it is not already present.
            bool IsExists = System.IO.Directory.Exists(dataDir);

            if (!IsExists)
            {
                System.IO.Directory.CreateDirectory(dataDir);
            }

            //Instantiate Presentation class that represents PPTX file
            Presentation pres = new Presentation();

            //Access first slide
            ISlide sld = pres.Slides[0];

            // Add chart with default data
            IChart chart = sld.Shapes.AddChart(ChartType.ClusteredColumn, 0, 0, 500, 500);

            //Setting chart Title
            //chart.ChartTitle.TextFrameForOverriding.Text = "Sample Title";
            chart.ChartTitle.AddTextFrameForOverriding("Sample Title");
            chart.ChartTitle.TextFrameForOverriding.TextFrameFormat.CenterText = NullableBool.True;
            chart.ChartTitle.Height = 20;
            chart.HasTitle          = true;

            //Set first series to Show Values
            chart.ChartData.Series[0].Labels.DefaultDataLabelFormat.ShowValue = true;

            //Setting the index of chart data sheet
            int defaultWorksheetIndex = 0;

            //Getting the chart data worksheet
            IChartDataWorkbook fact = chart.ChartData.ChartDataWorkbook;

            //Delete default generated series and categories
            chart.ChartData.Series.Clear();
            chart.ChartData.Categories.Clear();
            int s = chart.ChartData.Series.Count;

            s = chart.ChartData.Categories.Count;

            //Adding new series
            chart.ChartData.Series.Add(fact.GetCell(defaultWorksheetIndex, 0, 1, "Series 1"), chart.Type);
            chart.ChartData.Series.Add(fact.GetCell(defaultWorksheetIndex, 0, 2, "Series 2"), chart.Type);

            //Adding new categories
            chart.ChartData.Categories.Add(fact.GetCell(defaultWorksheetIndex, 1, 0, "Caetegoty 1"));
            chart.ChartData.Categories.Add(fact.GetCell(defaultWorksheetIndex, 2, 0, "Caetegoty 2"));
            chart.ChartData.Categories.Add(fact.GetCell(defaultWorksheetIndex, 3, 0, "Caetegoty 3"));

            //Take first chart series
            IChartSeries series = chart.ChartData.Series[0];

            //Now populating series data

            series.DataPoints.AddDataPointForBarSeries(fact.GetCell(defaultWorksheetIndex, 1, 1, 20));
            series.DataPoints.AddDataPointForBarSeries(fact.GetCell(defaultWorksheetIndex, 2, 1, 50));
            series.DataPoints.AddDataPointForBarSeries(fact.GetCell(defaultWorksheetIndex, 3, 1, 30));

            //Setting fill color for series
            series.Format.Fill.FillType             = FillType.Solid;
            series.Format.Fill.SolidFillColor.Color = Color.Red;


            //Take second chart series
            series = chart.ChartData.Series[1];

            //Now populating series data
            series.DataPoints.AddDataPointForBarSeries(fact.GetCell(defaultWorksheetIndex, 1, 2, 30));
            series.DataPoints.AddDataPointForBarSeries(fact.GetCell(defaultWorksheetIndex, 2, 2, 10));
            series.DataPoints.AddDataPointForBarSeries(fact.GetCell(defaultWorksheetIndex, 3, 2, 60));

            //Setting fill color for series
            series.Format.Fill.FillType             = FillType.Solid;
            series.Format.Fill.SolidFillColor.Color = Color.Green;

            //first label will be show Category name
            IDataLabel lbl = series.DataPoints[0].Label;

            lbl.DataLabelFormat.ShowCategoryName = true;

            lbl = series.DataPoints[1].Label;
            lbl.DataLabelFormat.ShowSeriesName = true;

            //Show value for third label
            lbl = series.DataPoints[2].Label;
            lbl.DataLabelFormat.ShowValue      = true;
            lbl.DataLabelFormat.ShowSeriesName = true;
            lbl.DataLabelFormat.Separator      = "/";

            //Save presentation with chart
            pres.Save(dataDir + "AsposeChart.pptx", SaveFormat.Pptx);
        }
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_WorkingWithTransparency();
            // Create new XPS Document
            XpsDocument doc = new XpsDocument();

            // Just to demonstrate transparency
            doc.AddPath(doc.CreatePathGeometry("M120,0 H400 v1000 H120")).Fill = doc.CreateSolidColorBrush(Color.Gray);
            doc.AddPath(doc.CreatePathGeometry("M300,120 h600 V420 h-600")).Fill = doc.CreateSolidColorBrush(Color.Gray);

            // Create path with closed rectangle geometry
            XpsPath path1 = doc.CreatePath(doc.CreatePathGeometry("M20,20 h200 v200 h-200 z"));
            // Set blue solid brush to fill path1
            path1.Fill = doc.CreateSolidColorBrush(Color.Blue);
            // Add it to the current page
            XpsPath path2 = doc.Add(path1);

            // path1 and path2 are the same as soon as path1 hasn't been placed inside any other element
            // (which means that path1 had no parent element).
            // Because of that rectangle's color on the page effectively turns to green
            path2.Fill = doc.CreateSolidColorBrush(Color.Green);

            // Now add path2 once again. Now path2 has parent. So path3 won't be the same as path2.
            // Thus a new rectangle is painted on the page ...
            XpsPath path3 = doc.Add(path2);
            // ... and we shift it 300 units lower ...
            path3.RenderTransform = doc.CreateMatrix(1, 0, 0, 1, 0, 300);
            // ... and set red solid brush to fill it
            path3.Fill = doc.CreateSolidColorBrush(Color.Red);

            // Create new path4 with path2's geometry ...
            XpsPath path4 = doc.AddPath(path2.Data);
            // ... shift it 300 units to the right ...
            path4.RenderTransform = doc.CreateMatrix(1, 0, 0, 1, 300, 0);
            // ... and set blue solid fill
            path4.Fill = doc.CreateSolidColorBrush(Color.Blue);

            // Add path4 once again.
            XpsPath path5 = doc.Add(path4);
            // path4 and path5 are not the same again ...
            // (move path5 300 units lower)
            path5.RenderTransform = path5.RenderTransform.Clone(); // to disconnect RenderTransform value from path4 (see next comment about Fill property)
            path5.RenderTransform.Translate(0, 300);
            // ... but if we set the opacity of Fill property, it will take effect on both path5 and path4
            // because brush is a complex property value which remains the same for path5 and path4
            path5.Fill.Opacity = 0.8f;

            // Create new path6 with path2's geometry ...
            XpsPath path6 = doc.AddPath(path2.Data);
            // ... shift it 600 units to the right ...
            path6.RenderTransform = doc.CreateMatrix(1, 0, 0, 1, 600, 0);
            // ... and set yellow solid fill
            path6.Fill = doc.CreateSolidColorBrush(Color.Yellow);

            // Now add path6's clone ...
            XpsPath path7 = doc.Add(path6.Clone());
            // (move path5 300 units lower)
            path7.RenderTransform = path7.RenderTransform.Clone();
            path7.RenderTransform.Translate(0, 300);
            // ... and set opacity for path7
            path7.Fill.Opacity = 0.8f;
            // Now opacity effects independantly as soon as property values are cloned along with the element

            // The following code block is equivalent to the previous one.
            // Add path6 itself. path6 and path7 are not the same. Although their Fill property values are the same 
            //XpsPath path7 = doc.Add(path6);
            //path7.RenderTransform = path7.RenderTransform.Clone();
            //path7.RenderTransform.Translate(0, 300);
            // To "disconnect" path7's Fill property from path6's Fill property reassign it to its clone (or path6's Fill clone)
            //path7.Fill = ((XpsSolidColorBrush)path7.Fill).Clone();
            //path7.Fill.Opacity = 0.8f;

            // Save resultant XPS document
            doc.Save(dataDir + "WorkingWithTransparency_out.xps");
            // ExEnd:1
        }
        public static void Run()
        {
            // ExStart:SpecifyHeadingLevel
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_Headings();

            // Instntiate the Pdf object by calling its empty constructor
            Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

            // Create the section in the Pdf object
            Aspose.Pdf.Generator.Section sec1 = pdf1.Sections.Add();

            /*
             * Create 1st heading in the Pdf object's section with level=1. Then create
             * a text segment and add it in the heading. Set its StartNumber=6 to start
             * the numbering from 6 and onwards. And don't forget to set IsAutoSequence=true.
             * If IsAutoSeguence property is set to true then the heading's sequence is
             * controlled automatically by Aspose.Pdf for .NET. After setting all properties, add
             * heading into the paragraphs collection of the section
             */

            Aspose.Pdf.Generator.Heading heading1 = new Aspose.Pdf.Generator.Heading(pdf1, sec1, 1);
            Aspose.Pdf.Generator.Segment segment1 = new Aspose.Pdf.Generator.Segment(heading1);
            heading1.Segments.Add(segment1);
            segment1.Content        = "Level 1";
            heading1.IsAutoSequence = true;
            heading1.StartNumber    = 6;
            sec1.Paragraphs.Add(heading1);

            /*
             * Create 2nd heading in the Pdf object's section with level=2. Then create
             * a text segment and add it in the heading. And don't forget to set
             * IsAutoSequence=true.If IsAutoSeguence property is set to true then the
             * heading's sequence is controlled automatically by Aspose.Pdf for .NET. After setting
             * all properties, add heading into the paragraphs collection of the section
             */

            Aspose.Pdf.Generator.Heading heading2 = new Aspose.Pdf.Generator.Heading(pdf1, sec1, 2);
            Aspose.Pdf.Generator.Segment segment2 = new Aspose.Pdf.Generator.Segment(heading2);
            heading2.Segments.Add(segment2);
            segment2.Content        = "Level 2";
            heading2.IsAutoSequence = true;
            sec1.Paragraphs.Add(heading2);

            /*
             * Create 3rd heading in the Pdf object's section with level=3. Then create
             * a text segment and add it in the heading. And don't forget to set
             * IsAutoSequence=true.If IsAutoSeguence property is set to true then the
             * heading's sequence is controlled automatically by Aspose.Pdf for .NET. After setting
             * all properties, add heading into the paragraphs collection of the section
             */

            Aspose.Pdf.Generator.Heading heading3 = new Aspose.Pdf.Generator.Heading(pdf1, sec1, 3);
            Aspose.Pdf.Generator.Segment segment3 = new Aspose.Pdf.Generator.Segment(heading3);
            heading3.Segments.Add(segment3);
            segment3.Content        = "Level 3";
            heading3.IsAutoSequence = true;
            sec1.Paragraphs.Add(heading3);

            pdf1.Save(dataDir + "SpecifyHeadingLevel_out.pdf");
            // ExEnd:SpecifyHeadingLevel
        }
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            // Create a new Workbook.
            Workbook workbook = new Workbook();

            // Get the first worksheet.
            Worksheet sheet = workbook.Worksheets[0];

            // Set the name of worksheet
            sheet.Name = "Data";

            // Get the cells collection in the sheet.
            Cells cells = workbook.Worksheets[0].Cells;

            // Put some values into a cells of the Data sheet.
            cells["A1"].PutValue("Region");
            cells["A2"].PutValue("France");
            cells["A3"].PutValue("Germany");
            cells["A4"].PutValue("England");
            cells["A5"].PutValue("Sweden");
            cells["A6"].PutValue("Italy");
            cells["A7"].PutValue("Spain");
            cells["A8"].PutValue("Portugal");
            cells["B1"].PutValue("Sale");
            cells["B2"].PutValue(70000);
            cells["B3"].PutValue(55000);
            cells["B4"].PutValue(30000);
            cells["B5"].PutValue(40000);
            cells["B6"].PutValue(35000);
            cells["B7"].PutValue(32000);
            cells["B8"].PutValue(10000);

            // Add a chart sheet.
            int sheetIndex = workbook.Worksheets.Add(SheetType.Chart);

            sheet = workbook.Worksheets[sheetIndex];

            // Set the name of worksheet
            sheet.Name = "Chart";

            // Create chart
            int chartIndex = 0;

            chartIndex = sheet.Charts.Add(Aspose.Cells.Charts.ChartType.Pie, 1, 1, 25, 10);
            Aspose.Cells.Charts.Chart chart = sheet.Charts[chartIndex];

            // Set some properties of chart plot area.
            // To set the fill color and make the border invisible.
            chart.PlotArea.Area.ForegroundColor = Color.Coral;
            chart.PlotArea.Area.FillFormat.SetTwoColorGradient(Color.Yellow, Color.White, Aspose.Cells.Drawing.GradientStyleType.Vertical, 2);
            chart.PlotArea.Border.IsVisible = false;

            // Set properties of chart title
            chart.Title.Text        = "Sales By Region";
            chart.Title.Font.Color  = Color.Blue;
            chart.Title.Font.IsBold = true;
            chart.Title.Font.Size   = 12;

            // Set properties of nseries
            chart.NSeries.Add("Data!B2:B8", true);
            chart.NSeries.CategoryData  = "Data!A2:A8";
            chart.NSeries.IsColorVaried = true;

            // Set the DataLabels in the chart
            Aspose.Cells.Charts.DataLabels datalabels;
            for (int i = 0; i < chart.NSeries.Count; i++)
            {
                datalabels                  = chart.NSeries[i].DataLabels;
                datalabels.Position         = Aspose.Cells.Charts.LabelPositionType.InsideBase;
                datalabels.ShowCategoryName = true;
                datalabels.ShowValue        = true;
                datalabels.ShowPercentage   = false;
                datalabels.ShowLegendKey    = false;
            }

            // Set the ChartArea.
            Aspose.Cells.Charts.ChartArea chartarea = chart.ChartArea;
            chartarea.Area.Formatting         = Aspose.Cells.Charts.FormattingType.Custom;
            chartarea.Area.FillFormat.Texture = Aspose.Cells.Drawing.TextureType.BlueTissuePaper;

            // Set the Legend.
            Aspose.Cells.Charts.Legend legend = chart.Legend;
            legend.Position        = Aspose.Cells.Charts.LegendPositionType.Left;
            legend.Height          = 100;
            legend.Width           = 130;
            legend.Y               = 1500;
            legend.Font.IsBold     = true;
            legend.Border.Color    = Color.Blue;
            legend.Area.Formatting = Aspose.Cells.Charts.FormattingType.Custom;

            // Set FillFormat.
            Aspose.Cells.Drawing.FillFormat fillformat = legend.Area.FillFormat;
            fillformat.Texture = Aspose.Cells.Drawing.TextureType.Bouquet;

            // Save the excel file
            workbook.Save(dataDir + "output.xls");

            // ExEnd:1
        }
        public static void Run()
        {
            // The path to the documents directory.
            string SourceDir = RunExamples.GetDataDir_PSD();
            string OutputDir = RunExamples.GetDataDir_Output();

            //ExStart
            //ExSummary:The following example demonstrates how to create/edit the GradientOverlayEffect effect object in layer.

            string sourceFilePath = Path.Combine(SourceDir, "psdnet256.psd");
            string outputFilePath = Path.Combine(OutputDir, "psdnet256.psd_output.psd");

            // Creates/Gets and edits the gradient overlay effect in a layer.
            using (var psdImage = (PsdImage)Image.Load(sourceFilePath, new PsdLoadOptions()
            {
                LoadEffectsResource = true
            }))
            {
                BlendingOptions       layerBlendOptions     = psdImage.Layers[1].BlendingOptions;
                GradientOverlayEffect gradientOverlayEffect = null;

                // Search GradientOverlayEffect in a layer.
                foreach (ILayerEffect effect in layerBlendOptions.Effects)
                {
                    gradientOverlayEffect = effect as GradientOverlayEffect;
                    if (gradientOverlayEffect != null)
                    {
                        break;
                    }
                }

                if (gradientOverlayEffect == null)
                {
                    // You can create a new GradientOverlayEffect if it not exists.
                    gradientOverlayEffect = layerBlendOptions.AddGradientOverlay();
                }

                // Add a bit of transparency to the effect.
                gradientOverlayEffect.Opacity = 200;

                // Change the blend mode of gradient effect.
                gradientOverlayEffect.BlendMode = BlendMode.Hue;

                // Gets GradientFillSettings object to configure gradient overlay settings.
                GradientFillSettings settings = gradientOverlayEffect.Settings;

                // Setting a new gradient with two colors.
                settings.ColorPoints = new IGradientColorPoint[]
                {
                    new GradientColorPoint(Color.GreenYellow, 0, 50),
                    new GradientColorPoint(Color.BlueViolet, 4096, 50),
                };

                // Sets an inclination of the gradient at an angle of 80 degrees.
                settings.Angle = 80;

                // Scale gradient effect up to 150%.
                settings.Scale = 150;

                // Sets type of gradient.
                settings.GradientType = GradientType.Linear;

                // Make the gradient opaque by setting the opacity to 100% at each transparency point.
                settings.TransparencyPoints[0].Opacity = 100;
                settings.TransparencyPoints[1].Opacity = 100;

                psdImage.Save(outputFilePath);
            }

            //ExEnd

            Console.WriteLine("SupportOfGradientOverlayEffect executed successfully");
        }
 public static void Run()
 {
     // The path to the documents directory.
     string dataDir = RunExamples.GetDataDir_Projects();
 }
Exemplo n.º 27
0
        public static void Run()
        {
            // ExStart:UseImageSaveOptions
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_LoadSaveConvert();

            // Call the diagram constructor to a VSDX diagram
            Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx");

            ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.JPEG);

            // Specify the quality level to use during compositing.
            options.CompositingQuality = Aspose.Diagram.Saving.CompositingQuality.HighQuality;

            // Sets the brightness for the the generated images.
            // This property has effect only when saving to raster image formats.
            // The default value is 0.5. The value must be in the range between 0 and 1.
            options.ImageBrightness = 1f;

            // Summary:
            //     value or the font is not installed locally, they may appear as a block,
            //     set the DefaultFont such as MingLiu or MS Gothic to show these
            //     characters.
            options.DefaultFont = "MS Gothic";
            // Sets the number of pages to render in image.
            options.PageCount = 2;
            // Sets the 0-based index of the first page to render. Default is 0.
            options.PageIndex = 0;

            // Set page size
            PageSize pgSize = new PageSize(PaperSizeFormat.A1);

            options.PageSize = pgSize;
            // Discard saving background pages of the Visio diagram
            options.SaveForegroundPagesOnly = true;

            // Sets the color mode for the generated images.
            options.ImageColorMode = ImageColorMode.BlackAndWhite;

            // Sets the contrast for the generated images.
            // This property has effect only when saving to raster image formats.
            // The default value is 0.5. The value must be in the range between 0 and 1.
            options.ImageContrast = 1f;

            // Specify the algorithm that is used when images are scaled or rotated.
            // This property has effect only when saving to raster image formats.
            options.InterpolationMode = Aspose.Diagram.Saving.InterpolationMode.NearestNeighbor;

            // The value may vary from 0 to 100 where 0 means worst quality,
            // But maximum compression and 100 means best quality but minimum compression.
            // The default value is 95.
            options.JpegQuality = 100;

            // Set a value specifying how pixels are offset during rendering.
            options.PixelOffsetMode = Aspose.Diagram.Saving.PixelOffsetMode.HighSpeed;

            // Sets the resolution for the generated images, in dots per inch. The default value is 96.
            options.Resolution = 2f;

            // Sets the zoom factor for the generated images.
            // The default value is 1.0. The value must be greater than 0.
            options.Scale = 1f;

            // Specify whether smoothing (antialiasing) is applied to lines
            // And curves and the edges of filled areas.
            options.SmoothingMode = Aspose.Diagram.Saving.SmoothingMode.HighQuality;
            // Sets the type of compression to apply when saving generated images to the TIFF format.
            options.TiffCompression = TiffCompression.Ccitt3;

            // Save in any supported file format
            diagram.Save(dataDir + "UseImageSaveOptions_out.jpeg", options);
            // ExEnd:UseImageSaveOptions
        }
        public static void Run()
        {
            // ExStart:ConsequentExportOperations
            // ExFor:Document
            // ExFor:Document.AutomaticLayoutChangesDetectionEnabled
            // ExFor:Document.DetectLayoutChanges
            // ExFor:Page
            // ExFor:Page.Title
            // ExFor:Title
            // ExFor:Title.TitleText
            // ExFor:Title.TitleDate
            // ExFor:Title.TitleTime
            // ExSummary:Shows how to save a document in different formats.

            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_LoadingAndSaving();

            // Initialize the new Document
            Document doc = new Document()
            {
                AutomaticLayoutChangesDetectionEnabled = false
            };

            // Initialize the new Page
            Aspose.Note.Page page = new Aspose.Note.Page(doc);

            // Default style for all text in the document.
            ParagraphStyle textStyle = new ParagraphStyle {
                FontColor = Color.Black, FontName = "Arial", FontSize = 10
            };

            page.Title = new Title(doc)
            {
                TitleText = new RichText(doc)
                {
                    Text = "Title text.", ParagraphStyle = textStyle
                },
                TitleDate = new RichText(doc)
                {
                    Text = new DateTime(2011, 11, 11).ToString("D", CultureInfo.InvariantCulture), ParagraphStyle = textStyle
                },
                TitleTime = new RichText(doc)
                {
                    Text = "12:34", ParagraphStyle = textStyle
                }
            };

            // Append page node
            doc.AppendChildLast(page);

            // Save OneNote document in different formats, set text font size and detect layout changes manually.
            doc.Save(dataDir + "ConsequentExportOperations_out.html");
            doc.Save(dataDir + "ConsequentExportOperations_out.pdf");
            doc.Save(dataDir + "ConsequentExportOperations_out.jpg");
            textStyle.FontSize = 11;
            doc.DetectLayoutChanges();
            doc.Save(dataDir + "ConsequentExportOperations_out.bmp");

            // ExEnd:ConsequentExportOperations

            Console.WriteLine("\nConsequent export operations performed successfully.");
        }
Exemplo n.º 29
0
        public static void Run()
        {
            // ExStart:ApplyVisualEffects
            // The path to the documents directory.
            string MyDir = RunExamples.GetDataDir();

            // Load an existing 3D scene
            Scene scene = new Scene(MyDir + "scene.obj");
            // Create an instance of the camera
            Camera camera = new Camera();

            scene.RootNode.CreateChildNode("camera", camera).Transform.Translation = new Vector3(2, 44, 66);
            // Set the target
            camera.LookAt = new Vector3(50, 12, 0);
            // Create a light
            scene.RootNode.CreateChildNode("light", new Light()
            {
                Color = new Vector3(Color.White), LightType = LightType.Point
            }).Transform.Translation = new Vector3(26, 57, 43);

            // The CreateRenderer will create a hardware OpenGL-backend renderer, more renderer will be added in the future
            // And some internal initializations will be done.
            // When the renderer left using the scope, the unmanaged hardware resources will also be disposed
            using (var renderer = Renderer.CreateRenderer())
            {
                renderer.EnableShadows = false;

                // Create a new render target that renders the scene to texture(s)
                // Use default render parameters
                // And one output targets
                // Size is 1024 x 1024
                // This render target can have multiple render output textures, but here we only need one output.
                // The other textures and depth textures are mainly used by deferred shading in the future.
                // But you can also access the depth texture through IRenderTexture.DepthTeture
                using (IRenderTexture rt = renderer.RenderFactory.CreateRenderTexture(new RenderParameters(), 1, 1024, 1024))
                {
                    // This render target has one viewport to render, the viewport occupies the 100% width and 100% height
                    Viewport vp = rt.CreateViewport(camera, new RelativeRectangle()
                    {
                        ScaleWidth = 1, ScaleHeight = 1
                    });
                    // Render the target and save the target texture to external file
                    renderer.Render(rt);
                    rt.Targets[0].Save(MyDir + "Original_viewport_out.png", ImageFormat.Png);

                    // Create a post-processing effect
                    PostProcessing pixelation = renderer.GetPostProcessing("pixelation");
                    renderer.PostProcessings.Add(pixelation);
                    renderer.Render(rt);
                    rt.Targets[0].Save(MyDir + "VisualEffect_pixelation_out.png", ImageFormat.Png);

                    // Clear previous post-processing effects and try another one
                    PostProcessing grayscale = renderer.GetPostProcessing("grayscale");
                    renderer.PostProcessings.Clear();
                    renderer.PostProcessings.Add(grayscale);
                    renderer.Render(rt);
                    rt.Targets[0].Save(MyDir + "VisualEffect_grayscale_out.png", ImageFormat.Png);

                    // We can also combine post-processing effects
                    renderer.PostProcessings.Clear();
                    renderer.PostProcessings.Add(grayscale);
                    renderer.PostProcessings.Add(pixelation);
                    renderer.Render(rt);
                    rt.Targets[0].Save(MyDir + "VisualEffect_grayscale+pixelation_out.png", ImageFormat.Png);

                    // Clear previous post-processing effects and try another one
                    PostProcessing edgedetection = renderer.GetPostProcessing("edge-detection");
                    renderer.PostProcessings.Clear();
                    renderer.PostProcessings.Add(edgedetection);
                    renderer.Render(rt);
                    rt.Targets[0].Save(MyDir + "VisualEffect_edgedetection_out.png", ImageFormat.Png);

                    // Clear previous post-processing effects and try another one
                    PostProcessing blur = renderer.GetPostProcessing("blur");
                    renderer.PostProcessings.Clear();
                    renderer.PostProcessings.Add(blur);
                    renderer.Render(rt);
                    rt.Targets[0].Save(MyDir + "VisualEffect_blur_out.png", ImageFormat.Png);
                }
            }
            // ExEnd:ApplyVisualEffects
        }
        public static void Run()
        {
            //ExStart:RenderingExportOfChannelMixerAdjusmentLyer
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_PSD();

            // Rgb Channel Mixer
            string sourceFileName     = dataDir + "ChannelMixerAdjustmentLayerRgb.psd";
            string psdPathAfterChange = dataDir + "ChannelMixerAdjustmentLayerRgbChanged.psd";
            string pngExportPath      = dataDir + "ChannelMixerAdjustmentLayerRgbChanged.png";

            using (var im = (PsdImage)Image.Load(sourceFileName))
            {
                foreach (var layer in im.Layers)
                {
                    if (layer is RgbChannelMixerLayer)
                    {
                        var rgbLayer = (RgbChannelMixerLayer)layer;
                        rgbLayer.RedChannel.Blue       = 100;
                        rgbLayer.BlueChannel.Green     = -100;
                        rgbLayer.GreenChannel.Constant = 50;
                    }
                }

                // Save PSD
                im.Save(psdPathAfterChange);

                // Save PNG
                var saveOptions = new PngOptions();
                saveOptions.ColorType = PngColorType.TruecolorWithAlpha;
                im.Save(pngExportPath, saveOptions);
            }

            // Cmyk Channel Mixer
            sourceFileName     = dataDir + "ChannelMixerAdjustmentLayerCmyk.psd";
            psdPathAfterChange = dataDir + "ChannelMixerAdjustmentLayerCmykChanged.psd";
            pngExportPath      = dataDir + "ChannelMixerAdjustmentLayerCmykChanged.png";

            using (var im = (PsdImage)Image.Load(sourceFileName))
            {
                foreach (var layer in im.Layers)
                {
                    if (layer is CmykChannelMixerLayer)
                    {
                        var cmykLayer = (CmykChannelMixerLayer)layer;
                        cmykLayer.CyanChannel.Black     = 20;
                        cmykLayer.MagentaChannel.Yellow = 50;
                        cmykLayer.YellowChannel.Cyan    = -25;
                        cmykLayer.BlackChannel.Yellow   = 25;
                    }
                }

                // Save PSD
                im.Save(psdPathAfterChange);

                // Save PNG
                var saveOptions = new PngOptions();
                saveOptions.ColorType = PngColorType.TruecolorWithAlpha;
                im.Save(pngExportPath, saveOptions);
            }
            //ExEnd:RenderingExportOfChannelMixerAdjusmentLyer
        }