diff --git a/Examples/ApiExamples/ApiExamples/ApiExamples.csproj b/Examples/ApiExamples/ApiExamples/ApiExamples.csproj index c1bf6e97e..1ccca3b6e 100644 --- a/Examples/ApiExamples/ApiExamples/ApiExamples.csproj +++ b/Examples/ApiExamples/ApiExamples/ApiExamples.csproj @@ -1,154 +1,155 @@ - - - - net48;net7.0 - AnyCPU - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers - - - - - - - - - ..\..\Data\Dlls\Interop.ADODB.dll - - - - - + + + + net48;net7.0 + AnyCPU + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + + + + + + + + ..\..\Data\Dlls\Interop.ADODB.dll + + + + + \ No newline at end of file diff --git a/Examples/ApiExamples/ApiExamples/CustomBarcodeGenerator.cs b/Examples/ApiExamples/ApiExamples/CustomBarcodeGenerator.cs index 091dbaf9b..fe96e9898 100644 --- a/Examples/ApiExamples/ApiExamples/CustomBarcodeGenerator.cs +++ b/Examples/ApiExamples/ApiExamples/CustomBarcodeGenerator.cs @@ -5,240 +5,311 @@ // "as is", without warranty of any kind, either expressed or implied. ////////////////////////////////////////////////////////////////////////// -using System; -using System.Drawing; -using System.Globalization; -using Aspose.BarCode.Generation; -using Aspose.Words.Fields; -using BarcodeParameters = Aspose.Words.Fields.BarcodeParameters; -#if NET5_0_OR_GREATER || __MOBILE__ -using Image = SkiaSharp.SKBitmap; -using Color = Aspose.Drawing.Color; +using System; +using System.IO; +using Aspose.Words.Fields; +using Aspose.BarCode.Generation; +#if NET5_0_OR_GREATER +using SkiaSharp; +using Aspose.Drawing; +using Aspose.Drawing.Imaging; +#else +using System.Drawing; +using System.Drawing.Imaging; #endif namespace ApiExamples { - /// - /// Sample of custom barcode generator implementation (with underlying Aspose.BarCode module) - /// - public class CustomBarcodeGenerator : ApiExampleBase, IBarcodeGenerator - { - /// - /// Converts barcode image height from Word units to Aspose.BarCode units. - /// - /// - /// - private static float ConvertSymbolHeight(string heightInTwipsString) - { - // Input value is in 1/1440 inches (twips) - int heightInTwips = TryParseInt(heightInTwipsString); - - if (heightInTwips == int.MinValue) - throw new Exception("Error! Incorrect height - " + heightInTwipsString + "."); - - // Convert to mm - return (float) (heightInTwips * 25.4 / 1440); - } - - /// - /// Converts barcode image color from Word to Aspose.BarCode. - /// - /// - /// - private static Color ConvertColor(string inputColor) - { - // Input should be from "0x000000" to "0xFFFFFF" - int color = TryParseHex(inputColor.Replace("0x", "")); - - if (color == int.MinValue) - throw new Exception("Error! Incorrect color - " + inputColor + "."); - - return Color.FromArgb(color >> 16, (color & 0xFF00) >> 8, color & 0xFF); - - // Backward conversion - - //return string.Format("0x{0,6:X6}", mControl.ForeColor.ToArgb() & 0xFFFFFF); - } - - /// - /// Converts bar code scaling factor from percent to float. - /// - /// - /// - private static float ConvertScalingFactor(string scalingFactor) - { - bool isParsed = false; - int percent = TryParseInt(scalingFactor); - - if (percent != int.MinValue && percent >= 10 && percent <= 10000) - isParsed = true; - - if (!isParsed) - throw new Exception("Error! Incorrect scaling factor - " + scalingFactor + "."); - - return percent / 100.0f; - } - - /// - /// Implementation of the GetBarCodeImage() method for IBarCodeGenerator interface. - /// - /// - /// - public Image GetBarcodeImage(BarcodeParameters parameters) - { - if (parameters.BarcodeType == null || parameters.BarcodeValue == null) - return null; - - BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR); - - string type = parameters.BarcodeType.ToUpper(); - - switch (type) - { - case "QR": - generator = new BarcodeGenerator(EncodeTypes.QR); - break; - case "CODE128": - generator = new BarcodeGenerator(EncodeTypes.Code128); - break; - case "CODE39": - generator = new BarcodeGenerator(EncodeTypes.Code39Standard); - break; - case "EAN8": - generator = new BarcodeGenerator(EncodeTypes.EAN8); - break; - case "EAN13": - generator = new BarcodeGenerator(EncodeTypes.EAN13); - break; - case "UPCA": - generator = new BarcodeGenerator(EncodeTypes.UPCA); - break; - case "UPCE": - generator = new BarcodeGenerator(EncodeTypes.UPCE); - break; - case "ITF14": - generator = new BarcodeGenerator(EncodeTypes.ITF14); - break; - case "CASE": - generator = new BarcodeGenerator(EncodeTypes.None); - break; - } - - if (generator.BarcodeType.Equals(EncodeTypes.None)) - return null; - - generator.CodeText = parameters.BarcodeValue; - - if (generator.BarcodeType.Equals(EncodeTypes.QR)) - generator.Parameters.Barcode.CodeTextParameters.TwoDDisplayText = parameters.BarcodeValue; - - if (parameters.ForegroundColor != null) - generator.Parameters.Barcode.BarColor = ConvertColor(parameters.ForegroundColor); - - if (parameters.BackgroundColor != null) - generator.Parameters.BackColor = ConvertColor(parameters.BackgroundColor); - - if (parameters.SymbolHeight != null) - { - generator.Parameters.ImageHeight.Pixels = ConvertSymbolHeight(parameters.SymbolHeight); - generator.Parameters.AutoSizeMode = AutoSizeMode.None; - } - - generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.None; - - if (parameters.DisplayText) - generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below; - - generator.Parameters.CaptionAbove.Text = ""; - - const float scale = 2.4f; // Empiric scaling factor for converting Word barcode to Aspose.BarCode - float xdim = 1.0f; - - if (generator.BarcodeType.Equals(EncodeTypes.QR)) - { - generator.Parameters.AutoSizeMode = AutoSizeMode.Nearest; - generator.Parameters.ImageWidth.Inches *= scale; - generator.Parameters.ImageHeight.Inches = generator.Parameters.ImageWidth.Inches; - xdim = generator.Parameters.ImageHeight.Inches / 25; - generator.Parameters.Barcode.XDimension.Inches = generator.Parameters.Barcode.BarHeight.Inches = xdim; - } - - if (parameters.ScalingFactor != null) - { - float scalingFactor = ConvertScalingFactor(parameters.ScalingFactor); - generator.Parameters.ImageHeight.Inches *= scalingFactor; - - if (generator.BarcodeType.Equals(EncodeTypes.QR)) - { - generator.Parameters.ImageWidth.Inches = generator.Parameters.ImageHeight.Inches; - generator.Parameters.Barcode.XDimension.Inches = generator.Parameters.Barcode.BarHeight.Inches = xdim * scalingFactor; - } - - generator.Parameters.AutoSizeMode = AutoSizeMode.None; - } - -#if NET461_OR_GREATER || JAVA - return generator.GenerateBarCodeImage(); -#elif NET5_0_OR_GREATER - generator.GenerateBarCodeImage().Save(ArtifactsDir + "GetBarcodeImage.png"); - return Image.Decode(ArtifactsDir + "GetBarcodeImage.png"); -#endif - } - - /// - /// Implementation of the GetOldBarcodeImage() method for IBarCodeGenerator interface. - /// - /// - /// - public Image GetOldBarcodeImage(BarcodeParameters parameters) - { - if (parameters.PostalAddress == null) - return null; - - BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Postnet) - { - CodeText = parameters.PostalAddress - }; - - // Hardcode type for old-fashioned Barcode -#if NET461_OR_GREATER || JAVA - return generator.GenerateBarCodeImage(); -#elif NET5_0_OR_GREATER - generator.GenerateBarCodeImage().Save(ArtifactsDir + "OldBarcodeImage.png"); - return Image.Decode(ArtifactsDir + "OldBarcodeImage.png"); -#endif - } - - /// - /// Parses an integer using the invariant culture. Returns Int.MinValue if cannot parse. - /// - /// Allows leading sign. - /// Allows leading and trailing spaces. - /// - public static int TryParseInt(string s) - { - return double.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out double temp) - ? CastDoubleToInt(temp) - : int.MinValue; - } - - /// - /// Casts a double to int32 in a way that uint32 are "correctly" casted too (they become negative numbers). - /// - public static int CastDoubleToInt(double value) - { - long temp = (long) value; - return (int) temp; - } - - /// - /// Try parses a hex String into an integer value. - /// on error return int.MinValue - /// - public static int TryParseHex(string s) - { - return int.TryParse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int result) - ? result - : int.MinValue; - } + internal class CustomBarcodeGeneratorUtils + { + /// + /// Converts a height value in twips to pixels using a default DPI of 96. + /// + /// The height value in twips. + /// The default value to return if the conversion fails. + /// The height value in pixels. + public static double TwipsToPixels(string heightInTwips, double defVal) + { + return TwipsToPixels(heightInTwips, 96, defVal); + } + + /// + /// Converts a height value in twips to pixels based on the given resolution. + /// + /// The height value in twips to be converted. + /// The resolution in pixels per inch. + /// The default value to be returned if the conversion fails. + /// The converted height value in pixels. + public static double TwipsToPixels(string heightInTwips, double resolution, double defVal) + { + try + { + int lVal = int.Parse(heightInTwips); + return (lVal / 1440.0) * resolution; + } + catch + { + return defVal; + } + } + + /// + /// Gets the rotation angle in degrees based on the given rotation angle string. + /// + /// The rotation angle string. + /// The default value to return if the rotation angle is not recognized. + /// The rotation angle in degrees. + public static float GetRotationAngle(string rotationAngle, float defVal) + { + switch (rotationAngle) + { + case "0": + return 0; + case "1": + return 270; + case "2": + return 180; + case "3": + return 90; + default: + return defVal; + } + } + + /// + /// Converts a string representation of an error correction level to a QRErrorLevel enum value. + /// + /// The string representation of the error correction level. + /// The default error correction level to return if the input is invalid. + /// The corresponding QRErrorLevel enum value. + public static QRErrorLevel GetQRCorrectionLevel(string errorCorrectionLevel, QRErrorLevel def) + { + switch (errorCorrectionLevel) + { + case "0": + return QRErrorLevel.LevelL; + case "1": + return QRErrorLevel.LevelM; + case "2": + return QRErrorLevel.LevelQ; + case "3": + return QRErrorLevel.LevelH; + default: + return def; + } + } + + /// + /// Gets the barcode encode type based on the given encode type from Word. + /// + /// The encode type from Word. + /// The barcode encode type. + public static SymbologyEncodeType GetBarcodeEncodeType(string encodeTypeFromWord) + { + // https://support.microsoft.com/en-au/office/field-codes-displaybarcode-6d81eade-762d-4b44-ae81-f9d3d9e07be3 + switch (encodeTypeFromWord) + { + case "QR": + return EncodeTypes.QR; + case "CODE128": + return EncodeTypes.Code128; + case "CODE39": + return EncodeTypes.Code39; + case "JPPOST": + return EncodeTypes.RM4SCC; + case "EAN8": + case "JAN8": + return EncodeTypes.EAN8; + case "EAN13": + case "JAN13": + return EncodeTypes.EAN13; + case "UPCA": + return EncodeTypes.UPCA; + case "UPCE": + return EncodeTypes.UPCE; + case "CASE": + case "ITF14": + return EncodeTypes.ITF14; + case "NW7": + return EncodeTypes.Codabar; + default: + return EncodeTypes.None; + } + } + + /// + /// Converts a hexadecimal color string to a Color object. + /// + /// The hexadecimal color string to convert. + /// The default Color value to return if the conversion fails. + /// The Color object representing the converted color, or the default value if the conversion fails. + public static Color ConvertColor(string inputColor, Color defVal) + { + if (string.IsNullOrEmpty(inputColor)) return defVal; + try + { + int color = Convert.ToInt32(inputColor, 16); + // Return Color.FromArgb((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF); + return Color.FromArgb(color & 0xFF, (color >> 8) & 0xFF, (color >> 16) & 0xFF); + } + catch + { + return defVal; + } + } + + /// + /// Calculates the scale factor based on the provided string representation. + /// + /// The string representation of the scale factor. + /// The default value to return if the scale factor cannot be parsed. + /// + /// The scale factor as a decimal value between 0 and 1, or the default value if the scale factor cannot be parsed. + /// + public static double ScaleFactor(string scaleFactor, double defVal) + { + try + { + int scale = int.Parse(scaleFactor); + return scale / 100.0; + } + catch + { + return defVal; + } + } + + /// + /// Sets the position code style for a barcode generator. + /// + /// The barcode generator. + /// The position code style to set. + /// The barcode value. + public static void SetPosCodeStyle(BarcodeGenerator gen, string posCodeStyle, string barcodeValue) + { + switch (posCodeStyle) + { + // STD default and without changes. + case "SUP2": + gen.CodeText = barcodeValue.Substring(0, barcodeValue.Length - 2); + gen.Parameters.Barcode.Supplement.SupplementData = barcodeValue.Substring(barcodeValue.Length - 2, 2); + break; + case "SUP5": + gen.CodeText = barcodeValue.Substring(0, barcodeValue.Length - 5); + gen.Parameters.Barcode.Supplement.SupplementData = barcodeValue.Substring(barcodeValue.Length - 5, 5); + break; + case "CASE": + gen.Parameters.Border.Visible = true; + gen.Parameters.Border.Color = gen.Parameters.Barcode.BarColor; + gen.Parameters.Border.DashStyle = BorderDashStyle.Solid; + gen.Parameters.Border.Width.Pixels = gen.Parameters.Barcode.XDimension.Pixels * 5; + break; + } + } + + public const double DefaultQRXDimensionInPixels = 4.0; + public const double Default1DXDimensionInPixels = 1.0; + + /// + /// Draws an error image with the specified exception message. + /// + /// The exception containing the error message. + /// A Bitmap object representing the error image. + public static Bitmap DrawErrorImage(Exception error) + { + Bitmap bmp = new Bitmap(100, 100); + + using (Graphics grf = Graphics.FromImage(bmp)) +#if NET5_0_OR_GREATER + grf.DrawString(error.Message, new Aspose.Drawing.Font("Microsoft Sans Serif", 8f, FontStyle.Regular), Brushes.Red, new Rectangle(0, 0, bmp.Width, bmp.Height)); +#else + grf.DrawString(error.Message, new System.Drawing.Font("Microsoft Sans Serif", 8f, FontStyle.Regular), Brushes.Red, new Rectangle(0,0, bmp.Width, bmp.Height)); +#endif + return bmp; + } + +#if NET5_0_OR_GREATER + public static SKBitmap ConvertImageToWord(Bitmap bmp) + { + MemoryStream ms = new MemoryStream(); + bmp.Save(ms, ImageFormat.Png); + ms.Position = 0; + + return SKBitmap.Decode(ms); + } +#else + public static Image ConvertImageToWord(Bitmap bmp) + { + return bmp; + } +#endif + } + + internal class CustomBarcodeGenerator : IBarcodeGenerator + { +#if NET5_0_OR_GREATER + public SKBitmap GetBarcodeImage(Aspose.Words.Fields.BarcodeParameters parameters) +#else + public Image GetBarcodeImage(Aspose.Words.Fields.BarcodeParameters parameters) +#endif + { + try + { + BarcodeGenerator gen = new BarcodeGenerator(CustomBarcodeGeneratorUtils.GetBarcodeEncodeType(parameters.BarcodeType), parameters.BarcodeValue); + + // Set color. + gen.Parameters.Barcode.BarColor = CustomBarcodeGeneratorUtils.ConvertColor(parameters.ForegroundColor, gen.Parameters.Barcode.BarColor); + gen.Parameters.BackColor = CustomBarcodeGeneratorUtils.ConvertColor(parameters.BackgroundColor, gen.Parameters.BackColor); + + // Set display or hide text. + if (!parameters.DisplayText) + gen.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.None; + else + gen.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below; + + // Set QR Code error correction level.s + gen.Parameters.Barcode.QR.QrErrorLevel = QRErrorLevel.LevelH; + if (!string.IsNullOrEmpty(parameters.ErrorCorrectionLevel)) + gen.Parameters.Barcode.QR.QrErrorLevel = CustomBarcodeGeneratorUtils.GetQRCorrectionLevel(parameters.ErrorCorrectionLevel, gen.Parameters.Barcode.QR.QrErrorLevel); + + // Set rotation angle. + if (!string.IsNullOrEmpty(parameters.SymbolRotation)) + gen.Parameters.RotationAngle = CustomBarcodeGeneratorUtils.GetRotationAngle(parameters.SymbolRotation, gen.Parameters.RotationAngle); + + // Set scaling factor. + double scalingFactor = 1; + if (!string.IsNullOrEmpty(parameters.ScalingFactor)) + scalingFactor = CustomBarcodeGeneratorUtils.ScaleFactor(parameters.ScalingFactor, scalingFactor); + + // Set size. + if (gen.BarcodeType == EncodeTypes.QR) + gen.Parameters.Barcode.XDimension.Pixels = (float)Math.Max(1.0, Math.Round(CustomBarcodeGeneratorUtils.DefaultQRXDimensionInPixels * scalingFactor)); + else + gen.Parameters.Barcode.XDimension.Pixels = (float)Math.Max(1.0, Math.Round(CustomBarcodeGeneratorUtils.Default1DXDimensionInPixels * scalingFactor)); + + //Set height. + if (!string.IsNullOrEmpty(parameters.SymbolHeight)) + gen.Parameters.Barcode.BarHeight.Pixels = (float)Math.Max(5.0, Math.Round(CustomBarcodeGeneratorUtils.TwipsToPixels(parameters.SymbolHeight, gen.Parameters.Barcode.BarHeight.Pixels) * scalingFactor)); + + // Set style of a Point-of-Sale barcode. + if (!string.IsNullOrEmpty(parameters.PosCodeStyle)) + CustomBarcodeGeneratorUtils.SetPosCodeStyle(gen, parameters.PosCodeStyle, parameters.BarcodeValue); + + return CustomBarcodeGeneratorUtils.ConvertImageToWord(gen.GenerateBarCodeImage()); + } + catch (Exception e) + { + return CustomBarcodeGeneratorUtils.ConvertImageToWord(CustomBarcodeGeneratorUtils.DrawErrorImage(e)); + } + } + +#if NET5_0_OR_GREATER + public SKBitmap GetOldBarcodeImage(Aspose.Words.Fields.BarcodeParameters parameters) +#else + public Image GetOldBarcodeImage(Aspose.Words.Fields.BarcodeParameters parameters) +#endif + { + throw new NotImplementedException(); + } } } diff --git a/Examples/ApiExamples/ApiExamples/ExAbsolutePositionTab.cs b/Examples/ApiExamples/ApiExamples/ExAbsolutePositionTab.cs index 4bc63b846..35f85b693 100644 --- a/Examples/ApiExamples/ApiExamples/ExAbsolutePositionTab.cs +++ b/Examples/ApiExamples/ApiExamples/ExAbsolutePositionTab.cs @@ -18,6 +18,10 @@ public class ExAbsolutePositionTab : ApiExampleBase //ExFor:AbsolutePositionTab //ExFor:AbsolutePositionTab.Accept(DocumentVisitor) //ExFor:DocumentVisitor.VisitAbsolutePositionTab + //ExFor:Body.Accept(DocumentVisitor) + //ExFor:Body.AcceptStart(DocumentVisitor) + //ExFor:Body.AcceptEnd(DocumentVisitor) + //ExFor:VisitorAction //ExSummary:Shows how to process absolute position tab characters with a document visitor. [Test] //ExSkip public void DocumentToTxt() @@ -26,7 +30,12 @@ public void DocumentToTxt() // Extract the text contents of our document by accepting this custom document visitor. DocTextExtractor myDocTextExtractor = new DocTextExtractor(); - doc.FirstSection.Body.Accept(myDocTextExtractor); + Section fisrtSection = doc.FirstSection; + fisrtSection.Body.Accept(myDocTextExtractor); + // Visit only start of the document body. + fisrtSection.Body.AcceptStart(myDocTextExtractor); + // Visit only end of the document body. + fisrtSection.Body.AcceptEnd(myDocTextExtractor); // The absolute position tab, which has no equivalent in string form, has been explicitly converted to a tab character. Assert.AreEqual("Before AbsolutePositionTab\tAfter AbsolutePositionTab", myDocTextExtractor.GetText()); diff --git a/Examples/ApiExamples/ApiExamples/ExBuildingBlocks.cs b/Examples/ApiExamples/ApiExamples/ExBuildingBlocks.cs index 816dfdac9..2776854b7 100644 --- a/Examples/ApiExamples/ApiExamples/ExBuildingBlocks.cs +++ b/Examples/ApiExamples/ApiExamples/ExBuildingBlocks.cs @@ -16,25 +16,27 @@ namespace ApiExamples { [TestFixture] public class ExBuildingBlocks : ApiExampleBase - { - //ExStart - //ExFor:Document.GlossaryDocument - //ExFor:BuildingBlock - //ExFor:BuildingBlock.#ctor(GlossaryDocument) - //ExFor:BuildingBlock.Accept(DocumentVisitor) - //ExFor:BuildingBlock.Behavior - //ExFor:BuildingBlock.Category - //ExFor:BuildingBlock.Description - //ExFor:BuildingBlock.FirstSection - //ExFor:BuildingBlock.Gallery - //ExFor:BuildingBlock.Guid - //ExFor:BuildingBlock.LastSection - //ExFor:BuildingBlock.Name - //ExFor:BuildingBlock.Sections - //ExFor:BuildingBlock.Type - //ExFor:BuildingBlockBehavior - //ExFor:BuildingBlockType - //ExSummary:Shows how to add a custom building block to a document. + { + //ExStart + //ExFor:Document.GlossaryDocument + //ExFor:BuildingBlock + //ExFor:BuildingBlock.#ctor(GlossaryDocument) + //ExFor:BuildingBlock.Accept(DocumentVisitor) + //ExFor:BuildingBlock.AcceptStart(DocumentVisitor) + //ExFor:BuildingBlock.AcceptEnd(DocumentVisitor) + //ExFor:BuildingBlock.Behavior + //ExFor:BuildingBlock.Category + //ExFor:BuildingBlock.Description + //ExFor:BuildingBlock.FirstSection + //ExFor:BuildingBlock.Gallery + //ExFor:BuildingBlock.Guid + //ExFor:BuildingBlock.LastSection + //ExFor:BuildingBlock.Name + //ExFor:BuildingBlock.Sections + //ExFor:BuildingBlock.Type + //ExFor:BuildingBlockBehavior + //ExFor:BuildingBlockType + //ExSummary:Shows how to add a custom building block to a document. [Test] //ExSkip public void CreateAndInsert() { @@ -66,6 +68,7 @@ public void CreateAndInsert() // Before we can add this building block to our document, we will need to give it some contents, // which we will do using a document visitor. This visitor will also set a category, gallery, and behavior. BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc); + // Visit start/end of the BuildingBlock. block.Accept(visitor); // We can access the block that we just made from the glossary document. @@ -134,6 +137,8 @@ public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block) //ExStart //ExFor:GlossaryDocument //ExFor:GlossaryDocument.Accept(DocumentVisitor) + //ExFor:GlossaryDocument.AcceptStart(DocumentVisitor) + //ExFor:GlossaryDocument.AcceptEnd(DocumentVisitor) //ExFor:GlossaryDocument.BuildingBlocks //ExFor:GlossaryDocument.FirstBuildingBlock //ExFor:GlossaryDocument.GetBuildingBlock(BuildingBlockGallery,String,String) @@ -184,7 +189,12 @@ public void GlossaryDocument() // We will do that using a custom visitor, // which will give every BuildingBlock in the GlossaryDocument a unique GUID GlossaryDocVisitor visitor = new GlossaryDocVisitor(); + // Visit start/end of the Glossary document. glossaryDoc.Accept(visitor); + // Visit only start of the Glossary document. + glossaryDoc.AcceptStart(visitor); + // Visit only end of the Glossary document. + glossaryDoc.AcceptEnd(visitor); Assert.AreEqual(5, visitor.GetDictionary().Count); //ExSkip Console.WriteLine(visitor.GetText()); diff --git a/Examples/ApiExamples/ApiExamples/ExCharts.cs b/Examples/ApiExamples/ApiExamples/ExCharts.cs index f1e8000de..ff3a94378 100644 --- a/Examples/ApiExamples/ApiExamples/ExCharts.cs +++ b/Examples/ApiExamples/ApiExamples/ExCharts.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; using System.Drawing; +using System.Globalization; using System.Linq; namespace ApiExamples @@ -122,9 +123,13 @@ public void AxisProperties() //ExFor:ChartAxis.MinorTickMark //ExFor:ChartAxis.MajorUnit //ExFor:ChartAxis.MinorUnit + //ExFor:AxisTickLabels //ExFor:AxisTickLabels.Offset //ExFor:AxisTickLabels.Position //ExFor:AxisTickLabels.IsAutoSpacing + //ExFor:AxisTickLabels.Alignment + //ExFor:AxisTickLabels.Font + //ExFor:AxisTickLabels.Spacing //ExFor:ChartAxis.TickMarkSpacing //ExFor:AxisCategoryType //ExFor:AxisCrosses @@ -170,6 +175,9 @@ public void AxisProperties() yAxis.MajorUnit = 100.0d; yAxis.MinorUnit = 20.0d; yAxis.TickLabels.Position = AxisTickLabelPosition.NextToAxis; + yAxis.TickLabels.Alignment = ParagraphAlignment.Center; + yAxis.TickLabels.Font.Color = Color.Red; + yAxis.TickLabels.Spacing = 1; // Column charts do not have a Z-axis. Assert.Null(chart.AxisZ); @@ -200,6 +208,9 @@ public void AxisProperties() Assert.AreEqual(100.0d, chart.AxisY.MajorUnit); Assert.AreEqual(20.0d, chart.AxisY.MinorUnit); Assert.AreEqual(AxisTickLabelPosition.NextToAxis, chart.AxisY.TickLabels.Position); + Assert.AreEqual(ParagraphAlignment.Center, chart.AxisY.TickLabels.Alignment); + Assert.AreEqual(Color.Red.ToArgb(), chart.AxisY.TickLabels.Font.Color.ToArgb()); + Assert.AreEqual(1, chart.AxisY.TickLabels.Spacing); } [Test] @@ -1222,6 +1233,7 @@ public void MarkerFormatting() //ExFor:Stroke.BackColor //ExFor:Stroke.Visible //ExFor:Stroke.Transparency + //ExFor:PresetTexture //ExFor:Fill.PresetTextured(PresetTexture) //ExSummary:Show how to set marker formatting. Document doc = new Document(); @@ -1356,6 +1368,7 @@ public void LegendFont() { //ExStart:LegendFont //GistId:470c0da51e4317baae82ad9495747fed + //ExFor:ChartLegendEntry //ExFor:ChartLegendEntry.Font //ExFor:ChartLegend.Font //ExSummary:Shows how to work with a legend font. @@ -1403,6 +1416,7 @@ public void RemoveSpecificChartSeries() public void PopulateChartWithData() { //ExStart + //ExFor:ChartXValue //ExFor:ChartXValue.FromDouble(Double) //ExFor:ChartYValue.FromDouble(Double) //ExFor:ChartSeries.Add(ChartXValue, ChartYValue) @@ -1680,6 +1694,7 @@ public void DataTable() { //ExStart:DataTable //GistId:a775441ecb396eea917a2717cb9e8f8f + //ExFor:Chart.DataTable //ExFor:ChartDataTable //ExFor:ChartDataTable.Show //ExSummary:Shows how to show data table with chart series data. @@ -1717,10 +1732,12 @@ public void ChartFormat() { //ExStart:ChartFormat //GistId:5f20ac02cb42c6b08481aa1c5b0cd3db + //ExFor:ChartFormat //ExFor:Chart.Format //ExFor:ChartTitle.Format //ExFor:ChartAxisTitle.Format //ExFor:ChartLegend.Format + //ExFor:Fill.Solid(Color) //ExSummary:Shows how to use chart formating. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); @@ -1766,5 +1783,467 @@ public void ChartFormat() Assert.AreEqual(Color.LightGoldenrodYellow.ToArgb(), chart.AxisX.Title.Format.Fill.Color.ToArgb()); Assert.AreEqual(Color.LightGoldenrodYellow.ToArgb(), chart.Legend.Format.Fill.Color.ToArgb()); } + + [Test] + public void SecondaryAxis() + { + //ExStart:SecondaryAxis + //GistId:6e4482e7434754c31c6f2f6e4bf48bb1 + //ExFor:ChartSeriesGroup + //ExFor:ChartSeriesGroup.AxisGroup + //ExFor:ChartSeriesGroup.AxisX + //ExFor:ChartSeriesGroup.AxisY + //ExFor:ChartSeriesGroup.Series + //ExFor:ChartSeriesGroupCollection + //ExFor:ChartSeriesGroupCollection.Add(ChartSeriesType) + //ExFor:AxisGroup + //ExSummary:Shows how to work with the secondary axis of chart. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + Shape shape = builder.InsertChart(ChartType.Line, 450, 250); + Chart chart = shape.Chart; + ChartSeriesCollection series = chart.Series; + + // Delete default generated series. + series.Clear(); + + string[] categories = new string[] { "Category 1", "Category 2", "Category 3" }; + series.Add("Series 1 of primary series group", categories, new double[] { 2, 3, 4 }); + series.Add("Series 2 of primary series group", categories, new double[] { 5, 2, 3 }); + + // Create an additional series group, also of the line type. + ChartSeriesGroup newSeriesGroup = chart.SeriesGroups.Add(ChartSeriesType.Line); + // Specify the use of secondary axes for the new series group. + newSeriesGroup.AxisGroup = AxisGroup.Secondary; + // Hide the secondary X axis. + newSeriesGroup.AxisX.Hidden = true; + // Define title of the secondary Y axis. + newSeriesGroup.AxisY.Title.Show = true; + newSeriesGroup.AxisY.Title.Text = "Secondary Y axis"; + + // Add a series to the new series group. + ChartSeries series3 = + newSeriesGroup.Series.Add("Series of secondary series group", categories, new double[] { 13, 11, 16 }); + series3.Format.Stroke.Weight = 3.5; + + doc.Save(ArtifactsDir + "Charts.SecondaryAxis.docx"); + //ExEnd:SecondaryAxis + } + + [Test] + public void ConfigureGapOverlap() + { + //ExStart:ConfigureGapOverlap + //GistId:6e4482e7434754c31c6f2f6e4bf48bb1 + //ExFor:Chart.SeriesGroups + //ExFor:ChartSeriesGroup.GapWidth + //ExFor:ChartSeriesGroup.Overlap + //ExSummary:Show how to configure gap width and overlap. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + Shape shape = builder.InsertChart(ChartType.Column, 450, 250); + ChartSeriesGroup seriesGroup = shape.Chart.SeriesGroups[0]; + + // Set column gap width and overlap. + seriesGroup.GapWidth = 450; + seriesGroup.Overlap = -75; + + doc.Save(ArtifactsDir + "Charts.ConfigureGapOverlap.docx"); + //ExEnd:ConfigureGapOverlap + } + + [Test] + public void BubbleScale() + { + //ExStart:BubbleScale + //GistId:6e4482e7434754c31c6f2f6e4bf48bb1 + //ExFor:ChartSeriesGroup.BubbleScale + //ExSummary:Show how to set size of the bubbles. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a bubble 3D chart. + Shape shape = builder.InsertChart(ChartType.Bubble3D, 450, 250); + ChartSeriesGroup seriesGroup = shape.Chart.SeriesGroups[0]; + + // Set bubble scale to 200%. + seriesGroup.BubbleScale = 200; + + doc.Save(ArtifactsDir + "Charts.BubbleScale.docx"); + //ExEnd:BubbleScale + } + + [Test] + public void RemoveSecondaryAxis() + { + //ExStart:RemoveSecondaryAxis + //GistId:6e4482e7434754c31c6f2f6e4bf48bb1 + //ExFor:ChartSeriesGroupCollection.Count + //ExFor:ChartSeriesGroupCollection.Item(Int32) + //ExFor:ChartSeriesGroupCollection.RemoveAt(Int32) + //ExSummary:Show how to remove secondary axis. + Document doc = new Document(MyDir + "Combo chart.docx"); + + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + Chart chart = shape.Chart; + ChartSeriesGroupCollection seriesGroups = chart.SeriesGroups; + + // Find secondary axis and remove from the collection. + for (int i = 0; i < seriesGroups.Count; i++) + if (seriesGroups[i].AxisGroup == AxisGroup.Secondary) + seriesGroups.RemoveAt(i); + //ExEnd:RemoveSecondaryAxis + } + + [Test] + public void TreemapChart() + { + //ExStart:TreemapChart + //GistId:65919861586e42e24f61a3ccb65f8f4e + //ExFor:ChartSeriesCollection.Add(String, ChartMultilevelValue[], double[]) + //ExFor:ChartMultilevelValue + //ExFor:ChartMultilevelValue.#ctor(String, String, String) + //ExFor:ChartMultilevelValue.#ctor(String, String) + //ExFor:ChartMultilevelValue.#ctor(String) + //ExSummary:Shows how to create treemap chart. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a Treemap chart. + Shape shape = builder.InsertChart(ChartType.Treemap, 450, 280); + Chart chart = shape.Chart; + chart.Title.Text = "World Population"; + + // Delete default generated series. + chart.Series.Clear(); + + // Add a series. + ChartSeries series = chart.Series.Add( + "Population by Region", + new ChartMultilevelValue[] + { + new ChartMultilevelValue("Asia", "China"), + new ChartMultilevelValue("Asia", "India"), + new ChartMultilevelValue("Asia", "Indonesia"), + new ChartMultilevelValue("Asia", "Pakistan"), + new ChartMultilevelValue("Asia", "Bangladesh"), + new ChartMultilevelValue("Asia", "Japan"), + new ChartMultilevelValue("Asia", "Philippines"), + new ChartMultilevelValue("Asia", "Other"), + new ChartMultilevelValue("Africa", "Nigeria"), + new ChartMultilevelValue("Africa", "Ethiopia"), + new ChartMultilevelValue("Africa", "Egypt"), + new ChartMultilevelValue("Africa", "Other"), + new ChartMultilevelValue("Europe", "Russia"), + new ChartMultilevelValue("Europe", "Germany"), + new ChartMultilevelValue("Europe", "Other"), + new ChartMultilevelValue("Latin America", "Brazil"), + new ChartMultilevelValue("Latin America", "Mexico"), + new ChartMultilevelValue("Latin America", "Other"), + new ChartMultilevelValue("Northern America", "United States", "Other"), + new ChartMultilevelValue("Northern America", "Other"), + new ChartMultilevelValue("Oceania") + }, + new double[] + { + 1409670000, 1400744000, 279118866, 241499431, 169828911, 123930000, 112892781, 764000000, + 223800000, 107334000, 105914499, 903000000, + 146150789, 84607016, 516000000, + 203080756, 129713690, 310000000, + 335893238, 35000000, + 42000000 + }); + + // Show data labels. + series.HasDataLabels = true; + series.DataLabels.ShowValue = true; + series.DataLabels.ShowCategoryName = true; + string thousandSeparator = CultureInfo.CurrentCulture.NumberFormat.CurrencyGroupSeparator; + series.DataLabels.NumberFormat.FormatCode = $"#{thousandSeparator}0"; + + doc.Save(ArtifactsDir + "Charts.Treemap.docx"); + //ExEnd:TreemapChart + } + + [Test] + public void SunburstChart() + { + //ExStart:SunburstChart + //GistId:65919861586e42e24f61a3ccb65f8f4e + //ExFor:ChartSeriesCollection.Add(String, ChartMultilevelValue[], double[]) + //ExSummary:Shows how to create sunburst chart. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a Sunburst chart. + Shape shape = builder.InsertChart(ChartType.Sunburst, 450, 450); + Chart chart = shape.Chart; + chart.Title.Text = "Sales"; + + // Delete default generated series. + chart.Series.Clear(); + + // Add a series. + ChartSeries series = chart.Series.Add( + "Sales", + new ChartMultilevelValue[] + { + new ChartMultilevelValue("Sales - Europe", "UK", "London Dep."), + new ChartMultilevelValue("Sales - Europe", "UK", "Liverpool Dep."), + new ChartMultilevelValue("Sales - Europe", "UK", "Manchester Dep."), + new ChartMultilevelValue("Sales - Europe", "France", "Paris Dep."), + new ChartMultilevelValue("Sales - Europe", "France", "Lyon Dep."), + new ChartMultilevelValue("Sales - NA", "USA", "Denver Dep."), + new ChartMultilevelValue("Sales - NA", "USA", "Seattle Dep."), + new ChartMultilevelValue("Sales - NA", "USA", "Detroit Dep."), + new ChartMultilevelValue("Sales - NA", "USA", "Houston Dep."), + new ChartMultilevelValue("Sales - NA", "Canada", "Toronto Dep."), + new ChartMultilevelValue("Sales - NA", "Canada", "Montreal Dep."), + new ChartMultilevelValue("Sales - Oceania", "Australia", "Sydney Dep."), + new ChartMultilevelValue("Sales - Oceania", "New Zealand", "Auckland Dep.") + }, + new double[] { 1236, 851, 536, 468, 179, 527, 799, 1148, 921, 457, 482, 761, 694 }); + + // Show data labels. + series.HasDataLabels = true; + series.DataLabels.ShowValue = false; + series.DataLabels.ShowCategoryName = true; + + doc.Save(ArtifactsDir + "Charts.Sunburst.docx"); + //ExEnd:SunburstChart + } + + [Test] + public void HistogramChart() + { + //ExStart:HistogramChart + //GistId:65919861586e42e24f61a3ccb65f8f4e + //ExFor:ChartSeriesCollection.Add(String, double[]) + //ExSummary:Shows how to create histogram chart. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a Histogram chart. + Shape shape = builder.InsertChart(ChartType.Histogram, 450, 450); + Chart chart = shape.Chart; + chart.Title.Text = "Avg Temperature since 1991"; + + // Delete default generated series. + chart.Series.Clear(); + + // Add a series. + chart.Series.Add( + "Avg Temperature", + new double[] + { + 51.8, 53.6, 50.3, 54.7, 53.9, 54.3, 53.4, 52.9, 53.3, 53.7, 53.8, 52.0, 55.0, 52.1, 53.4, + 53.8, 53.8, 51.9, 52.1, 52.7, 51.8, 56.6, 53.3, 55.6, 56.3, 56.2, 56.1, 56.2, 53.6, 55.7, + 56.3, 55.9, 55.6 + }); + + doc.Save(ArtifactsDir + "Charts.Histogram.docx"); + //ExEnd:HistogramChart + } + + [Test] + public void ParetoChart() + { + //ExStart:ParetoChart + //GistId:65919861586e42e24f61a3ccb65f8f4e + //ExFor:ChartSeriesCollection.Add(String, String[], double[]) + //ExSummary:Shows how to create pareto chart. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a Pareto chart. + Shape shape = builder.InsertChart(ChartType.Pareto, 450, 450); + Chart chart = shape.Chart; + chart.Title.Text = "Best-Selling Car"; + + // Delete default generated series. + chart.Series.Clear(); + + // Add a series. + chart.Series.Add( + "Best-Selling Car", + new string[] { "Tesla Model Y", "Toyota Corolla", "Toyota RAV4", "Ford F-Series", "Honda CR-V" }, + new double[] { 1.43, 0.91, 1.17, 0.98, 0.85 }); + + doc.Save(ArtifactsDir + "Charts.Pareto.docx"); + //ExEnd:ParetoChart + } + + [Test] + public void BoxAndWhiskerChart() + { + //ExStart:BoxAndWhiskerChart + //GistId:65919861586e42e24f61a3ccb65f8f4e + //ExFor:ChartSeriesCollection.Add(String, String[], double[]) + //ExSummary:Shows how to create box and whisker chart. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a Box & Whisker chart. + Shape shape = builder.InsertChart(ChartType.BoxAndWhisker, 450, 450); + Chart chart = shape.Chart; + chart.Title.Text = "Points by Years"; + + // Delete default generated series. + chart.Series.Clear(); + + // Add a series. + ChartSeries series = chart.Series.Add( + "Points by Years", + new string[] + { + "WC", "WC", "WC", "WC", "WC", "WC", "WC", "WC", "WC", "WC", + "NR", "NR", "NR", "NR", "NR", "NR", "NR", "NR", "NR", "NR", + "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA" + }, + new double[] + { + 91, 80, 100, 77, 90, 104, 105, 118, 120, 101, + 114, 107, 110, 60, 79, 78, 77, 102, 101, 113, + 94, 93, 84, 71, 80, 103, 80, 94, 100, 101 + }); + + // Show data labels. + series.HasDataLabels = true; + + doc.Save(ArtifactsDir + "Charts.BoxAndWhisker.docx"); + //ExEnd:BoxAndWhiskerChart + } + + [Test] + public void WaterfallChart() + { + //ExStart:WaterfallChart + //GistId:65919861586e42e24f61a3ccb65f8f4e + //ExFor:ChartSeriesCollection.Add(String, String[], double[], bool[]) + //ExSummary:Shows how to create waterfall chart. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a Waterfall chart. + Shape shape = builder.InsertChart(ChartType.Waterfall, 450, 450); + Chart chart = shape.Chart; + chart.Title.Text = "New Zealand GDP"; + + // Delete default generated series. + chart.Series.Clear(); + + // Add a series. + ChartSeries series = chart.Series.Add( + "New Zealand GDP", + new string[] { "2018", "2019 growth", "2020 growth", "2020", "2021 growth", "2022 growth", "2022" }, + new double[] { 100, 0.57, -0.25, 100.32, 20.22, -2.92, 117.62 }, + new bool[] { true, false, false, true, false, false, true }); + + // Show data labels. + series.HasDataLabels = true; + + doc.Save(ArtifactsDir + "Charts.Waterfall.docx"); + //ExEnd:WaterfallChart + } + + [Test] + public void FunnelChart() + { + //ExStart:FunnelChart + //GistId:65919861586e42e24f61a3ccb65f8f4e + //ExFor:ChartSeriesCollection.Add(String, String[], double[]) + //ExSummary:Shows how to create funnel chart. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a Funnel chart. + Shape shape = builder.InsertChart(ChartType.Funnel, 450, 450); + Chart chart = shape.Chart; + chart.Title.Text = "Population by Age Group"; + + // Delete default generated series. + chart.Series.Clear(); + + // Add a series. + ChartSeries series = chart.Series.Add( + "Population by Age Group", + new string[] { "0-9", "10-19", "20-29", "30-39", "40-49", "50-59", "60-69", "70-79", "80-89", "90-" }, + new double[] { 0.121, 0.128, 0.132, 0.146, 0.124, 0.124, 0.111, 0.075, 0.032, 0.007 }); + + // Show data labels. + series.HasDataLabels = true; + string decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator; + series.DataLabels.NumberFormat.FormatCode = $"0{decimalSeparator}0%"; + + doc.Save(ArtifactsDir + "Charts.Funnel.docx"); + //ExEnd:FunnelChart + } + + [Test] + public void LabelOrientationRotation() + { + //ExStart:LabelOrientationRotation + //GistId:ac8ba4eb35f3fbb8066b48c999da63b0 + //ExFor:ChartDataLabelCollection.Orientation + //ExFor:ChartDataLabelCollection.Rotation + //ExFor:ChartDataLabel.Rotation + //ExFor:ChartDataLabel.Orientation + //ExFor:ShapeTextOrientation + //ExSummary:Shows how to change orientation and rotation for data labels. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + Shape shape = builder.InsertChart(ChartType.Column, 432, 252); + ChartSeries series = shape.Chart.Series[0]; + ChartDataLabelCollection dataLabels = series.DataLabels; + + // Show data labels. + series.HasDataLabels = true; + dataLabels.ShowValue = true; + dataLabels.ShowCategoryName = true; + + // Define data label shape. + dataLabels.Format.ShapeType = ChartShapeType.UpArrow; + dataLabels.Format.Stroke.Fill.Solid(Color.DarkBlue); + + // Set data label orientation and rotation for the entire series. + dataLabels.Orientation = ShapeTextOrientation.VerticalFarEast; + dataLabels.Rotation = -45; + + // Change orientation and rotation of the first data label. + dataLabels[0].Orientation = ShapeTextOrientation.Horizontal; + dataLabels[0].Rotation = 45; + + doc.Save(ArtifactsDir + "Charts.LabelOrientationRotation.docx"); + //ExEnd:LabelOrientationRotation + } + + [Test] + public void TickLabelsOrientationRotation() + { + //ExStart:TickLabelsOrientationRotation + //GistId:708ce40a68fac5003d46f6b4acfd5ff1 + //ExFor:AxisTickLabels.Rotation + //ExFor:AxisTickLabels.Orientation + //ExSummary:Shows how to change orientation and rotation for axis tick labels. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a column chart. + Shape shape = builder.InsertChart(ChartType.Column, 432, 252); + AxisTickLabels xTickLabels = shape.Chart.AxisX.TickLabels; + AxisTickLabels yTickLabels = shape.Chart.AxisY.TickLabels; + + // Set axis tick label orientation and rotation. + xTickLabels.Orientation = ShapeTextOrientation.VerticalFarEast; + xTickLabels.Rotation = -30; + yTickLabels.Orientation = ShapeTextOrientation.Horizontal; + yTickLabels.Rotation = 45; + + doc.Save(ArtifactsDir + "Charts.TickLabelsOrientationRotation.docx"); + //ExEnd:TickLabelsOrientationRotation + } } } diff --git a/Examples/ApiExamples/ApiExamples/ExChmLoadOptions.cs b/Examples/ApiExamples/ApiExamples/ExChmLoadOptions.cs index 7834c2a27..01221e474 100644 --- a/Examples/ApiExamples/ApiExamples/ExChmLoadOptions.cs +++ b/Examples/ApiExamples/ApiExamples/ExChmLoadOptions.cs @@ -19,6 +19,8 @@ public class ExChmLoadOptions : ApiExampleBase public void OriginalFileName() { //ExStart + //ExFor:ChmLoadOptions + //ExFor:ChmLoadOptions.#ctor //ExFor:ChmLoadOptions.OriginalFileName //ExSummary:Shows how to resolve URLs like "ms-its:myfile.chm::/index.htm". // Our document contains URLs like "ms-its:amhelp.chm::....htm", but it has a different name, diff --git a/Examples/ApiExamples/ApiExamples/ExComment.cs b/Examples/ApiExamples/ApiExamples/ExComment.cs index 665fd0631..d1941a8f0 100644 --- a/Examples/ApiExamples/ApiExamples/ExComment.cs +++ b/Examples/ApiExamples/ApiExamples/ExComment.cs @@ -67,6 +67,7 @@ public void PrintAllComments() //ExFor:Comment.Ancestor //ExFor:Comment.Author //ExFor:Comment.Replies + //ExFor:CompositeNode.GetEnumerator //ExFor:CompositeNode.GetChildNodes(NodeType, Boolean) //ExSummary:Shows how to print all of a document's comments and their replies. Document doc = new Document(MyDir + "Comments.docx"); @@ -162,24 +163,26 @@ public void Done() Assert.True(comment.Done); Assert.AreEqual("\u0005Fix the spelling error!", comment.GetText().Trim()); Assert.AreEqual("Hello world!", doc.FirstSection.Body.FirstParagraph.Runs[0].Text); - } - - //ExStart - //ExFor:Comment.Done - //ExFor:Comment.#ctor(DocumentBase) - //ExFor:Comment.Accept(DocumentVisitor) - //ExFor:Comment.DateTime - //ExFor:Comment.Id - //ExFor:Comment.Initial - //ExFor:CommentRangeEnd - //ExFor:CommentRangeEnd.#ctor(DocumentBase,Int32) - //ExFor:CommentRangeEnd.Accept(DocumentVisitor) - //ExFor:CommentRangeEnd.Id - //ExFor:CommentRangeStart - //ExFor:CommentRangeStart.#ctor(DocumentBase,Int32) - //ExFor:CommentRangeStart.Accept(DocumentVisitor) - //ExFor:CommentRangeStart.Id - //ExSummary:Shows how print the contents of all comments and their comment ranges using a document visitor. + } + + //ExStart + //ExFor:Comment.Done + //ExFor:Comment.#ctor(DocumentBase) + //ExFor:Comment.Accept(DocumentVisitor) + //ExFor:Comment.AcceptStart(DocumentVisitor) + //ExFor:Comment.AcceptEnd(DocumentVisitor) + //ExFor:Comment.DateTime + //ExFor:Comment.Id + //ExFor:Comment.Initial + //ExFor:CommentRangeEnd + //ExFor:CommentRangeEnd.#ctor(DocumentBase,Int32) + //ExFor:CommentRangeEnd.Accept(DocumentVisitor) + //ExFor:CommentRangeEnd.Id + //ExFor:CommentRangeStart + //ExFor:CommentRangeStart.#ctor(DocumentBase,Int32) + //ExFor:CommentRangeStart.Accept(DocumentVisitor) + //ExFor:CommentRangeStart.Id + //ExSummary:Shows how print the contents of all comments and their comment ranges using a document visitor. [Test] //ExSkip public void CreateCommentsAndPrintAllInfo() { @@ -224,6 +227,10 @@ private static void PrintAllCommentInfo(NodeCollection comments) // Then, visit the comment, and any replies that it may have. comment.Accept(commentVisitor); + // Visit only start of the comment. + comment.AcceptStart(commentVisitor); + // Visit only end of the comment. + comment.AcceptEnd(commentVisitor); foreach (Comment reply in comment.Replies) reply.Accept(commentVisitor); @@ -334,5 +341,30 @@ private void IndentAndAppendLine(string text) private readonly StringBuilder mBuilder; } //ExEnd + + [Test] + public void UtcDateTime() + { + //ExStart:UtcDateTime + //GistId:65919861586e42e24f61a3ccb65f8f4e + //ExFor:Comment.DateTimeUtc + //ExSummary:Shows how to get UTC date and time. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + DateTime dateTime = DateTime.Now; + Comment comment = new Comment(doc, "John Doe", "J.D.", dateTime); + comment.SetText("My comment."); + + builder.CurrentParagraph.AppendChild(comment); + + doc.Save(ArtifactsDir + "Comment.UtcDateTime.docx"); + doc = new Document(ArtifactsDir + "Comment.UtcDateTime.docx"); + + comment = (Comment)doc.GetChild(NodeType.Comment, 0, true); + // DateTimeUtc return data without milliseconds. + Assert.AreEqual(dateTime.ToUniversalTime().ToString("yyyy-MM-dd hh:mm:ss"), comment.DateTimeUtc.ToString("yyyy-MM-dd hh:mm:ss")); + //ExEnd:UtcDateTime + } } } \ No newline at end of file diff --git a/Examples/ApiExamples/ApiExamples/ExCompatibilityOptions.cs b/Examples/ApiExamples/ApiExamples/ExCompatibilityOptions.cs index b44596ec9..e02f43caf 100644 --- a/Examples/ApiExamples/ApiExamples/ExCompatibilityOptions.cs +++ b/Examples/ApiExamples/ApiExamples/ExCompatibilityOptions.cs @@ -15,14 +15,85 @@ namespace ApiExamples { [TestFixture] public class ExCompatibilityOptions : ApiExampleBase - { - //ExStart - //ExFor:Compatibility - //ExFor:CompatibilityOptions - //ExFor:CompatibilityOptions.OptimizeFor(MsWordVersion) - //ExFor:Document.CompatibilityOptions - //ExFor:MsWordVersion - //ExSummary:Shows how to optimize the document for different versions of Microsoft Word. + { + //ExStart + //ExFor:Compatibility + //ExFor:CompatibilityOptions + //ExFor:CompatibilityOptions.OptimizeFor(MsWordVersion) + //ExFor:Document.CompatibilityOptions + //ExFor:MsWordVersion + //ExFor:CompatibilityOptions.AdjustLineHeightInTable + //ExFor:CompatibilityOptions.AlignTablesRowByRow + //ExFor:CompatibilityOptions.AllowSpaceOfSameStyleInTable + //ExFor:CompatibilityOptions.ApplyBreakingRules + //ExFor:CompatibilityOptions.AutofitToFirstFixedWidthCell + //ExFor:CompatibilityOptions.AutoSpaceLikeWord95 + //ExFor:CompatibilityOptions.BalanceSingleByteDoubleByteWidth + //ExFor:CompatibilityOptions.CachedColBalance + //ExFor:CompatibilityOptions.ConvMailMergeEsc + //ExFor:CompatibilityOptions.DisableOpenTypeFontFormattingFeatures + //ExFor:CompatibilityOptions.DisplayHangulFixedWidth + //ExFor:CompatibilityOptions.DoNotAutofitConstrainedTables + //ExFor:CompatibilityOptions.DoNotBreakConstrainedForcedTable + //ExFor:CompatibilityOptions.DoNotBreakWrappedTables + //ExFor:CompatibilityOptions.DoNotExpandShiftReturn + //ExFor:CompatibilityOptions.DoNotLeaveBackslashAlone + //ExFor:CompatibilityOptions.DoNotSnapToGridInCell + //ExFor:CompatibilityOptions.DoNotSuppressIndentation + //ExFor:CompatibilityOptions.DoNotSuppressParagraphBorders + //ExFor:CompatibilityOptions.DoNotUseEastAsianBreakRules + //ExFor:CompatibilityOptions.DoNotUseHTMLParagraphAutoSpacing + //ExFor:CompatibilityOptions.DoNotUseIndentAsNumberingTabStop + //ExFor:CompatibilityOptions.DoNotVertAlignCellWithSp + //ExFor:CompatibilityOptions.DoNotVertAlignInTxbx + //ExFor:CompatibilityOptions.DoNotWrapTextWithPunct + //ExFor:CompatibilityOptions.FootnoteLayoutLikeWW8 + //ExFor:CompatibilityOptions.ForgetLastTabAlignment + //ExFor:CompatibilityOptions.GrowAutofit + //ExFor:CompatibilityOptions.LayoutRawTableWidth + //ExFor:CompatibilityOptions.LayoutTableRowsApart + //ExFor:CompatibilityOptions.LineWrapLikeWord6 + //ExFor:CompatibilityOptions.MWSmallCaps + //ExFor:CompatibilityOptions.NoColumnBalance + //ExFor:CompatibilityOptions.NoExtraLineSpacing + //ExFor:CompatibilityOptions.NoLeading + //ExFor:CompatibilityOptions.NoSpaceRaiseLower + //ExFor:CompatibilityOptions.NoTabHangInd + //ExFor:CompatibilityOptions.OverrideTableStyleFontSizeAndJustification + //ExFor:CompatibilityOptions.PrintBodyTextBeforeHeader + //ExFor:CompatibilityOptions.PrintColBlack + //ExFor:CompatibilityOptions.SelectFldWithFirstOrLastChar + //ExFor:CompatibilityOptions.ShapeLayoutLikeWW8 + //ExFor:CompatibilityOptions.ShowBreaksInFrames + //ExFor:CompatibilityOptions.SpaceForUL + //ExFor:CompatibilityOptions.SpacingInWholePoints + //ExFor:CompatibilityOptions.SplitPgBreakAndParaMark + //ExFor:CompatibilityOptions.SubFontBySize + //ExFor:CompatibilityOptions.SuppressBottomSpacing + //ExFor:CompatibilityOptions.SuppressSpacingAtTopOfPage + //ExFor:CompatibilityOptions.SuppressSpBfAfterPgBrk + //ExFor:CompatibilityOptions.SuppressTopSpacing + //ExFor:CompatibilityOptions.SuppressTopSpacingWP + //ExFor:CompatibilityOptions.SwapBordersFacingPgs + //ExFor:CompatibilityOptions.SwapInsideAndOutsideForMirrorIndentsAndRelativePositioning + //ExFor:CompatibilityOptions.TransparentMetafiles + //ExFor:CompatibilityOptions.TruncateFontHeightsLikeWP6 + //ExFor:CompatibilityOptions.UICompat97To2003 + //ExFor:CompatibilityOptions.UlTrailSpace + //ExFor:CompatibilityOptions.UnderlineTabInNumList + //ExFor:CompatibilityOptions.UseAltKinsokuLineBreakRules + //ExFor:CompatibilityOptions.UseAnsiKerningPairs + //ExFor:CompatibilityOptions.UseFELayout + //ExFor:CompatibilityOptions.UseNormalStyleForList + //ExFor:CompatibilityOptions.UsePrinterMetrics + //ExFor:CompatibilityOptions.UseSingleBorderforContiguousCells + //ExFor:CompatibilityOptions.UseWord2002TableStyleRules + //ExFor:CompatibilityOptions.UseWord2010TableStyleRules + //ExFor:CompatibilityOptions.UseWord97LineBreakRules + //ExFor:CompatibilityOptions.WPJustification + //ExFor:CompatibilityOptions.WPSpaceWidth + //ExFor:CompatibilityOptions.WrapTrailSpaces + //ExSummary:Shows how to optimize the document for different versions of Microsoft Word. [Test] //ExSkip public void OptimizeFor() { diff --git a/Examples/ApiExamples/ApiExamples/ExDigitalSignatureUtil.cs b/Examples/ApiExamples/ApiExamples/ExDigitalSignatureUtil.cs index 3a522abc5..01157d09d 100644 --- a/Examples/ApiExamples/ApiExamples/ExDigitalSignatureUtil.cs +++ b/Examples/ApiExamples/ApiExamples/ExDigitalSignatureUtil.cs @@ -89,6 +89,7 @@ public void SignDocument() //ExFor:CertificateHolder //ExFor:CertificateHolder.Create(String, String) //ExFor:DigitalSignatureUtil.Sign(Stream, Stream, CertificateHolder, SignOptions) + //ExFor:DigitalSignatures.SignOptions //ExFor:SignOptions.Comments //ExFor:SignOptions.SignTime //ExSummary:Shows how to digitally sign documents. diff --git a/Examples/ApiExamples/ApiExamples/ExDocSaveOptions.cs b/Examples/ApiExamples/ApiExamples/ExDocSaveOptions.cs index 413a26d85..91f3d29a9 100644 --- a/Examples/ApiExamples/ApiExamples/ExDocSaveOptions.cs +++ b/Examples/ApiExamples/ApiExamples/ExDocSaveOptions.cs @@ -27,6 +27,7 @@ public void SaveAsDoc() //ExFor:DocSaveOptions.Password //ExFor:DocSaveOptions.SaveFormat //ExFor:DocSaveOptions.SaveRoutingSlip + //ExFor:IncorrectPasswordException //ExSummary:Shows how to set save options for older Microsoft Word formats. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); @@ -133,7 +134,7 @@ public void UpdateLastPrintedProperty(bool isUpdateLastPrintedProperty) public void UpdateCreatedTimeProperty(bool isUpdateCreatedTimeProperty) { //ExStart - //ExFor:SaveOptions.UpdateLastPrintedProperty + //ExFor:SaveOptions.UpdateCreatedTimeProperty //ExSummary:Shows how to update a document's "CreatedTime" property when saving. Document doc = new Document(); doc.BuiltInDocumentProperties.CreatedTime = new DateTime(2019, 12, 20); diff --git a/Examples/ApiExamples/ApiExamples/ExDocument.cs b/Examples/ApiExamples/ApiExamples/ExDocument.cs index de9d2abc3..85fdbb72b 100644 --- a/Examples/ApiExamples/ApiExamples/ExDocument.cs +++ b/Examples/ApiExamples/ApiExamples/ExDocument.cs @@ -16,7 +16,6 @@ using System.Text; using System.Text.RegularExpressions; using Aspose.Words; -using Aspose.Words.Comparing; using Aspose.Words.DigitalSignatures; using Aspose.Words.Drawing; using Aspose.Words.Fields; @@ -40,8 +39,6 @@ using Aspose.Words.Settings; using Aspose.Pdf.Text; using Aspose.Words.Shaping.HarfBuzz; -using System.Net.Http; -using System.Threading.Tasks; #if NET5_0_OR_GREATER || __MOBILE__ using SkiaSharp; #endif @@ -56,6 +53,7 @@ public void CreateSimpleDocument() { //ExStart:CreateSimpleDocument //GistId:3428e84add5beb0d46a8face6e5fc858 + //ExFor:DocumentBase.Document //ExFor:Document.#ctor() //ExSummary:Shows how to create simple document. Document doc = new Document(); @@ -312,11 +310,12 @@ public void PdfRenderer(string docName, string format) break; case "PNG": - options = new PdfFixedOptions() { - PageIndex = 0, - PageCount = 2, - JpegQuality = 50, - ImageFormat = FixedImageFormat.Png + options = new PdfFixedOptions() + { + PageIndex = 0, + PageCount = 2, + JpegQuality = 50, + ImageFormat = FixedImageFormat.Png }; SaveTo(pdfRenderer, docName, options, "png"); AssertResult("png"); @@ -389,7 +388,7 @@ private void AssertResult(string fileExt) .Where(path => reg.IsMatch(path)) .ToList(); - if(fileExt == "png") + if (fileExt == "png") Assert.AreEqual(2, images.Count); else Assert.AreEqual(5, images.Count); @@ -431,6 +430,7 @@ public void OpenFromStreamWithBaseUri() //ExFor:Document.#ctor(Stream,LoadOptions) //ExFor:LoadOptions.#ctor //ExFor:LoadOptions.BaseUri + //ExFor:ShapeBase.IsImage //ExSummary:Shows how to open an HTML document with images from a stream using a base URI. using (Stream stream = File.OpenRead(MyDir + "Document.html")) { @@ -516,10 +516,16 @@ public void LoadEncrypted() [Test] public void NotSupportedWarning() { - WarningInfoCollection warings = new WarningInfoCollection(); - Document doc = new Document(MyDir + "FB2 document.fb2", new LoadOptions { WarningCallback = warings }); + //ExStart + //ExFor:WarningInfoCollection.Count + //ExFor:WarningInfoCollection.Item(Int32) + //ExSummary:Shows how to get warnings about unsupported formats. + WarningInfoCollection warnings = new WarningInfoCollection(); + Document doc = new Document(MyDir + "FB2 document.fb2", new LoadOptions { WarningCallback = warnings }); - Assert.AreEqual("The original file load format is FB2, which is not supported by Aspose.Words. The file is loaded as an XML document.", warings[0].Description); + Assert.AreEqual("The original file load format is FB2, which is not supported by Aspose.Words. The file is loaded as an XML document.", warnings[0].Description); + Assert.AreEqual(1, warnings.Count); + //ExEnd } [Test] @@ -592,6 +598,7 @@ public void SaveToStream() } //ExStart + //ExFor:Range.Fields //ExFor:INodeChangingCallback //ExFor:INodeChangingCallback.NodeInserting //ExFor:INodeChangingCallback.NodeInserted @@ -636,7 +643,7 @@ void INodeChangingCallback.NodeInserted(NodeChangingArgs args) if (args.Node.NodeType == NodeType.Run) { - Aspose.Words.Font font = ((Run) args.Node).Font; + Aspose.Words.Font font = ((Run)args.Node).Font; mLog.Append($"\tFont:\tChanged from \"{font.Name}\" {font.Size}pt"); font.Size = 24; @@ -863,7 +870,7 @@ public void ValidateIndividualDocumentSignatures() foreach (DigitalSignature signature in doc.DigitalSignatures) { Console.WriteLine($"{(signature.IsValid ? "Valid" : "Invalid")} signature: "); - Console.WriteLine($"\tReason:\t{signature.Comments}"); + Console.WriteLine($"\tReason:\t{signature.Comments}"); Console.WriteLine($"\tType:\t{signature.SignatureType}"); Console.WriteLine($"\tSign time:\t{signature.SignTime}"); Console.WriteLine($"\tSubject name:\t{signature.CertificateHolder.Certificate.SubjectName}"); @@ -909,7 +916,7 @@ public void DigitalSignature() // There are two ways of saving a signed copy of a document to the local file system: // 1 - Designate a document by a local system filename and save a signed copy at a location specified by another filename. SignOptions signOptions = new SignOptions { SignTime = DateTime.Now }; - DigitalSignatureUtil.Sign(MyDir + "Document.docx", ArtifactsDir + "Document.DigitalSignature.docx", + DigitalSignatureUtil.Sign(MyDir + "Document.docx", ArtifactsDir + "Document.DigitalSignature.docx", certificateHolder, signOptions); Assert.True(FileFormatUtil.DetectFileFormat(ArtifactsDir + "Document.DigitalSignature.docx").HasDigitalSignature); @@ -1052,7 +1059,7 @@ public void CloneDocument() // but with a unique copy of each of the original document's nodes. Document clone = doc.Clone(); - Assert.AreEqual(doc.FirstSection.Body.FirstParagraph.Runs[0].GetText(), + Assert.AreEqual(doc.FirstSection.Body.FirstParagraph.Runs[0].GetText(), clone.FirstSection.Body.FirstParagraph.Runs[0].Text); Assert.AreNotEqual(doc.FirstSection.Body.FirstParagraph.Runs[0].GetHashCode(), clone.FirstSection.Body.FirstParagraph.Runs[0].GetHashCode()); @@ -1282,9 +1289,9 @@ public void TableStyleToDirectFormatting() doc.Save(ArtifactsDir + "Document.TableStyleToDirectFormatting.docx"); //ExEnd - TestUtil.DocPackageFileContainsString("", + TestUtil.DocPackageFileContainsString("", ArtifactsDir + "Document.TableStyleToDirectFormatting.docx", "document.xml"); - TestUtil.DocPackageFileContainsString("", + TestUtil.DocPackageFileContainsString("", ArtifactsDir + "Document.TableStyleToDirectFormatting.docx", "document.xml"); TestUtil.DocPackageFileContainsString("", ArtifactsDir + "Document.TableStyleToDirectFormatting.docx", "document.xml"); @@ -1324,170 +1331,6 @@ public void FootnoteColumns() Assert.AreEqual(2, doc.FirstSection.PageSetup.FootnoteOptions.Columns); } - [Test] - public void Compare() - { - //ExStart - //ExFor:Document.Compare(Document, String, DateTime) - //ExFor:RevisionCollection.AcceptAll - //ExSummary:Shows how to compare documents. - Document docOriginal = new Document(); - DocumentBuilder builder = new DocumentBuilder(docOriginal); - builder.Writeln("This is the original document."); - - Document docEdited = new Document(); - builder = new DocumentBuilder(docEdited); - builder.Writeln("This is the edited document."); - - // Comparing documents with revisions will throw an exception. - if (docOriginal.Revisions.Count == 0 && docEdited.Revisions.Count == 0) - docOriginal.Compare(docEdited, "authorName", DateTime.Now); - - // After the comparison, the original document will gain a new revision - // for every element that is different in the edited document. - Assert.AreEqual(2, docOriginal.Revisions.Count); //ExSkip - foreach (Revision r in docOriginal.Revisions) - { - Console.WriteLine($"Revision type: {r.RevisionType}, on a node of type \"{r.ParentNode.NodeType}\""); - Console.WriteLine($"\tChanged text: \"{r.ParentNode.GetText()}\""); - } - - // Accepting these revisions will transform the original document into the edited document. - docOriginal.Revisions.AcceptAll(); - - Assert.AreEqual(docOriginal.GetText(), docEdited.GetText()); - //ExEnd - - docOriginal = DocumentHelper.SaveOpen(docOriginal); - Assert.AreEqual(0, docOriginal.Revisions.Count); - } - - [Test] - public void CompareDocumentWithRevisions() - { - Document doc1 = new Document(); - DocumentBuilder builder = new DocumentBuilder(doc1); - builder.Writeln("Hello world! This text is not a revision."); - - Document docWithRevision = new Document(); - builder = new DocumentBuilder(docWithRevision); - - docWithRevision.StartTrackRevisions("John Doe"); - builder.Writeln("This is a revision."); - - Assert.Throws(() => docWithRevision.Compare(doc1, "John Doe", DateTime.Now)); - } - - [Test] - public void CompareOptions() - { - //ExStart - //ExFor:CompareOptions - //ExFor:CompareOptions.IgnoreFormatting - //ExFor:CompareOptions.IgnoreCaseChanges - //ExFor:CompareOptions.IgnoreComments - //ExFor:CompareOptions.IgnoreTables - //ExFor:CompareOptions.IgnoreFields - //ExFor:CompareOptions.IgnoreFootnotes - //ExFor:CompareOptions.IgnoreTextboxes - //ExFor:CompareOptions.IgnoreHeadersAndFooters - //ExFor:CompareOptions.Target - //ExFor:ComparisonTargetType - //ExFor:Document.Compare(Document, String, DateTime, CompareOptions) - //ExSummary:Shows how to filter specific types of document elements when making a comparison. - // Create the original document and populate it with various kinds of elements. - Document docOriginal = new Document(); - DocumentBuilder builder = new DocumentBuilder(docOriginal); - - // Paragraph text referenced with an endnote: - builder.Writeln("Hello world! This is the first paragraph."); - builder.InsertFootnote(FootnoteType.Endnote, "Original endnote text."); - - // Table: - builder.StartTable(); - builder.InsertCell(); - builder.Write("Original cell 1 text"); - builder.InsertCell(); - builder.Write("Original cell 2 text"); - builder.EndTable(); - - // Textbox: - Shape textBox = builder.InsertShape(ShapeType.TextBox, 150, 20); - builder.MoveTo(textBox.FirstParagraph); - builder.Write("Original textbox contents"); - - // DATE field: - builder.MoveTo(docOriginal.FirstSection.Body.AppendParagraph("")); - builder.InsertField(" DATE "); - - // Comment: - Comment newComment = new Comment(docOriginal, "John Doe", "J.D.", DateTime.Now); - newComment.SetText("Original comment."); - builder.CurrentParagraph.AppendChild(newComment); - - // Header: - builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary); - builder.Writeln("Original header contents."); - - // Create a clone of our document and perform a quick edit on each of the cloned document's elements. - Document docEdited = (Document)docOriginal.Clone(true); - Paragraph firstParagraph = docEdited.FirstSection.Body.FirstParagraph; - - firstParagraph.Runs[0].Text = "hello world! this is the first paragraph, after editing."; - firstParagraph.ParagraphFormat.Style = docEdited.Styles[StyleIdentifier.Heading1]; - ((Footnote)docEdited.GetChild(NodeType.Footnote, 0, true)).FirstParagraph.Runs[1].Text = "Edited endnote text."; - ((Table)docEdited.GetChild(NodeType.Table, 0, true)).FirstRow.Cells[1].FirstParagraph.Runs[0].Text = "Edited Cell 2 contents"; - ((Shape)docEdited.GetChild(NodeType.Shape, 0, true)).FirstParagraph.Runs[0].Text = "Edited textbox contents"; - ((FieldDate)docEdited.Range.Fields[0]).UseLunarCalendar = true; - ((Comment)docEdited.GetChild(NodeType.Comment, 0, true)).FirstParagraph.Runs[0].Text = "Edited comment."; - docEdited.FirstSection.HeadersFooters[HeaderFooterType.HeaderPrimary].FirstParagraph.Runs[0].Text = - "Edited header contents."; - - // Comparing documents creates a revision for every edit in the edited document. - // A CompareOptions object has a series of flags that can suppress revisions - // on each respective type of element, effectively ignoring their change. - Aspose.Words.Comparing.CompareOptions compareOptions = new Aspose.Words.Comparing.CompareOptions(); - compareOptions.IgnoreFormatting = false; - compareOptions.IgnoreCaseChanges = false; - compareOptions.IgnoreComments = false; - compareOptions.IgnoreTables = false; - compareOptions.IgnoreFields = false; - compareOptions.IgnoreFootnotes = false; - compareOptions.IgnoreTextboxes = false; - compareOptions.IgnoreHeadersAndFooters = false; - compareOptions.Target = ComparisonTargetType.New; - - docOriginal.Compare(docEdited, "John Doe", DateTime.Now, compareOptions); - docOriginal.Save(ArtifactsDir + "Document.CompareOptions.docx"); - //ExEnd - - docOriginal = new Document(ArtifactsDir + "Document.CompareOptions.docx"); - - TestUtil.VerifyFootnote(FootnoteType.Endnote, true, string.Empty, - "OriginalEdited endnote text.", (Footnote)docOriginal.GetChild(NodeType.Footnote, 0, true)); - } - - [TestCase(false)] - [TestCase(true)] - public void IgnoreDmlUniqueId(bool isIgnoreDmlUniqueId) - { - //ExStart - //ExFor:CompareOptions.IgnoreDmlUniqueId - //ExSummary:Shows how to compare documents ignoring DML unique ID. - Document docA = new Document(MyDir + "DML unique ID original.docx"); - Document docB = new Document(MyDir + "DML unique ID compare.docx"); - - // By default, Aspose.Words do not ignore DML's unique ID, and the revisions count was 2. - // If we are ignoring DML's unique ID, and revisions count were 0. - Aspose.Words.Comparing.CompareOptions compareOptions = new Aspose.Words.Comparing.CompareOptions(); - compareOptions.IgnoreDmlUniqueId = isIgnoreDmlUniqueId; - - docA.Compare(docB, "Aspose.Words", DateTime.Now, compareOptions); - - Assert.AreEqual(isIgnoreDmlUniqueId ? 0 : 2, docA.Revisions.Count); - //ExEnd - } - [Test] public void RemoveExternalSchemaReferences() { @@ -1500,113 +1343,6 @@ public void RemoveExternalSchemaReferences() //ExEnd } - [Test] - public void TrackRevisions() - { - //ExStart - //ExFor:Document.StartTrackRevisions(String) - //ExFor:Document.StartTrackRevisions(String, DateTime) - //ExFor:Document.StopTrackRevisions - //ExSummary:Shows how to track revisions while editing a document. - Document doc = new Document(); - DocumentBuilder builder = new DocumentBuilder(doc); - - // Editing a document usually does not count as a revision until we begin tracking them. - builder.Write("Hello world! "); - - Assert.AreEqual(0, doc.Revisions.Count); - Assert.False(doc.FirstSection.Body.Paragraphs[0].Runs[0].IsInsertRevision); - - doc.StartTrackRevisions("John Doe"); - - builder.Write("Hello again! "); - - Assert.AreEqual(1, doc.Revisions.Count); - Assert.True(doc.FirstSection.Body.Paragraphs[0].Runs[1].IsInsertRevision); - Assert.AreEqual("John Doe", doc.Revisions[0].Author); - Assert.IsTrue((DateTime.Now - doc.Revisions[0].DateTime).Milliseconds <= 10); - - // Stop tracking revisions to not count any future edits as revisions. - doc.StopTrackRevisions(); - builder.Write("Hello again! "); - - Assert.AreEqual(1, doc.Revisions.Count); - Assert.False(doc.FirstSection.Body.Paragraphs[0].Runs[2].IsInsertRevision); - - // Creating revisions gives them a date and time of the operation. - // We can disable this by passing DateTime.MinValue when we start tracking revisions. - doc.StartTrackRevisions("John Doe", DateTime.MinValue); - builder.Write("Hello again! "); - - Assert.AreEqual(2, doc.Revisions.Count); - Assert.AreEqual("John Doe", doc.Revisions[1].Author); - Assert.AreEqual(DateTime.MinValue, doc.Revisions[1].DateTime); - - // We can accept/reject these revisions programmatically - // by calling methods such as Document.AcceptAllRevisions, or each revision's Accept method. - // In Microsoft Word, we can process them manually via "Review" -> "Changes". - doc.Save(ArtifactsDir + "Document.StartTrackRevisions.docx"); - //ExEnd - } - - [Test] - public void AcceptAllRevisions() - { - //ExStart - //ExFor:Document.AcceptAllRevisions - //ExSummary:Shows how to accept all tracking changes in the document. - Document doc = new Document(); - DocumentBuilder builder = new DocumentBuilder(doc); - - // Edit the document while tracking changes to create a few revisions. - doc.StartTrackRevisions("John Doe"); - builder.Write("Hello world! "); - builder.Write("Hello again! "); - builder.Write("This is another revision."); - doc.StopTrackRevisions(); - - Assert.AreEqual(3, doc.Revisions.Count); - - // We can iterate through every revision and accept/reject it as a part of our document. - // If we know we wish to accept every revision, we can do it more straightforwardly so by calling this method. - doc.AcceptAllRevisions(); - - Assert.AreEqual(0, doc.Revisions.Count); - Assert.AreEqual("Hello world! Hello again! This is another revision.", doc.GetText().Trim()); - //ExEnd - } - - [Test] - public void GetRevisedPropertiesOfList() - { - //ExStart - //ExFor:RevisionsView - //ExFor:Document.RevisionsView - //ExSummary:Shows how to switch between the revised and the original view of a document. - Document doc = new Document(MyDir + "Revisions at list levels.docx"); - doc.UpdateListLabels(); - - ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs; - Assert.AreEqual("1.", paragraphs[0].ListLabel.LabelString); - Assert.AreEqual("a.", paragraphs[1].ListLabel.LabelString); - Assert.AreEqual(string.Empty, paragraphs[2].ListLabel.LabelString); - - // View the document object as if all the revisions are accepted. Currently supports list labels. - doc.RevisionsView = RevisionsView.Final; - - Assert.AreEqual(string.Empty, paragraphs[0].ListLabel.LabelString); - Assert.AreEqual("1.", paragraphs[1].ListLabel.LabelString); - Assert.AreEqual("a.", paragraphs[2].ListLabel.LabelString); - //ExEnd - - doc.RevisionsView = RevisionsView.Original; - doc.AcceptAllRevisions(); - - Assert.AreEqual("a.", paragraphs[0].ListLabel.LabelString); - Assert.AreEqual(string.Empty, paragraphs[1].ListLabel.LabelString); - Assert.AreEqual("b.", paragraphs[2].ListLabel.LabelString); - } - [Test] public void UpdateThumbnail() { @@ -1841,6 +1577,7 @@ public void DefaultTemplate() public void UseSubstitutions() { //ExStart + //ExFor:FindReplaceOptions.#ctor //ExFor:FindReplaceOptions.UseSubstitutions //ExFor:FindReplaceOptions.LegacyMode //ExSummary:Shows how to recognize and use substitutions within replacement patterns. @@ -1868,6 +1605,7 @@ public void SetInvalidateFieldTypes() { //ExStart //ExFor:Document.NormalizeFieldTypes + //ExFor:Range.NormalizeFieldTypes //ExSummary:Shows how to get the keep a field's type up to date with its field code. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); @@ -1895,43 +1633,11 @@ public void SetInvalidateFieldTypes() Assert.AreEqual(FieldType.FieldPage, field.Type); Assert.AreEqual(FieldType.FieldPage, field.Start.FieldType); - Assert.AreEqual(FieldType.FieldPage, field.Separator.FieldType); + Assert.AreEqual(FieldType.FieldPage, field.Separator.FieldType); Assert.AreEqual(FieldType.FieldPage, field.End.FieldType); //ExEnd } - [Test] - public void LayoutOptionsRevisions() - { - //ExStart - //ExFor:Document.LayoutOptions - //ExFor:LayoutOptions - //ExFor:LayoutOptions.RevisionOptions - //ExFor:RevisionColor - //ExFor:RevisionOptions - //ExFor:RevisionOptions.InsertedTextColor - //ExFor:RevisionOptions.ShowRevisionBars - //ExSummary:Shows how to alter the appearance of revisions in a rendered output document. - Document doc = new Document(); - DocumentBuilder builder = new DocumentBuilder(doc); - - // Insert a revision, then change the color of all revisions to green. - builder.Writeln("This is not a revision."); - doc.StartTrackRevisions("John Doe", DateTime.Now); - Assert.AreEqual(RevisionColor.ByAuthor, doc.LayoutOptions.RevisionOptions.InsertedTextColor); //ExSkip - Assert.True(doc.LayoutOptions.RevisionOptions.ShowRevisionBars); //ExSkip - builder.Writeln("This is a revision."); - doc.StopTrackRevisions(); - builder.Writeln("This is not a revision."); - - // Remove the bar that appears to the left of every revised line. - doc.LayoutOptions.RevisionOptions.InsertedTextColor = RevisionColor.BrightGreen; - doc.LayoutOptions.RevisionOptions.ShowRevisionBars = false; - - doc.Save(ArtifactsDir + "Document.LayoutOptionsRevisions.pdf"); - //ExEnd - } - [TestCase(false)] [TestCase(true)] public void LayoutOptionsHiddenText(bool showHiddenText) @@ -1966,8 +1672,8 @@ public void UsePdfDocumentForLayoutOptionsHiddenText(bool showHiddenText) TextAbsorber textAbsorber = new TextAbsorber(); textAbsorber.Visit(pdfDoc); - Assert.AreEqual(showHiddenText ? - $"This text is not hidden.{Environment.NewLine}This text is hidden." : + Assert.AreEqual(showHiddenText ? + $"This text is not hidden.{Environment.NewLine}This text is hidden." : "This text is not hidden.", textAbsorber.Text); } @@ -2005,8 +1711,8 @@ public void UsePdfDocumentForLayoutOptionsParagraphMarks(bool showParagraphMarks TextAbsorber textAbsorber = new TextAbsorber(); textAbsorber.Visit(pdfDoc); - Assert.AreEqual(showParagraphMarks ? - $"Hello world!¶{Environment.NewLine}Hello again!¶{Environment.NewLine}¶" : + Assert.AreEqual(showParagraphMarks ? + $"Hello world!¶{Environment.NewLine}Hello again!¶{Environment.NewLine}¶" : $"Hello world!{Environment.NewLine}Hello again!", textAbsorber.Text.Trim()); } @@ -2017,6 +1723,7 @@ public void UpdatePageLayout() //ExFor:StyleCollection.Item(String) //ExFor:SectionCollection.Item(Int32) //ExFor:Document.UpdatePageLayout + //ExFor:Margins //ExFor:PageSetup.Margins //ExSummary:Shows when to recalculate the page layout of the document. Document doc = new Document(MyDir + "Rendering.docx"); @@ -2030,7 +1737,7 @@ public void UpdatePageLayout() doc.Sections[0].PageSetup.Orientation = Aspose.Words.Orientation.Landscape; doc.Sections[0].PageSetup.Margins = Margins.Mirrored; - // In the current version of Aspose.Words, modifying the document does not automatically rebuild + // In the current version of Aspose.Words, modifying the document does not automatically rebuild // the cached page layout. If we wish for the cached layout // to stay up to date, we will need to update it manually. doc.UpdatePageLayout(); @@ -2103,23 +1810,23 @@ private static void TestDocPackageCustomParts(CustomPartCollection parts) { Assert.AreEqual(3, parts.Count); - Assert.AreEqual("/payload/payload_on_package.test", parts[0].Name); - Assert.AreEqual("mytest/somedata", parts[0].ContentType); - Assert.AreEqual("http://mytest.payload.internal", parts[0].RelationshipType); - Assert.AreEqual(false, parts[0].IsExternal); - Assert.AreEqual(18, parts[0].Data.Length); + Assert.AreEqual("/payload/payload_on_package.test", parts[0].Name); + Assert.AreEqual("mytest/somedata", parts[0].ContentType); + Assert.AreEqual("http://mytest.payload.internal", parts[0].RelationshipType); + Assert.AreEqual(false, parts[0].IsExternal); + Assert.AreEqual(18, parts[0].Data.Length); - Assert.AreEqual("http://www.aspose.com/Images/aspose-logo.jpg", parts[1].Name); - Assert.AreEqual("", parts[1].ContentType); - Assert.AreEqual("http://mytest.payload.external", parts[1].RelationshipType); - Assert.AreEqual(true, parts[1].IsExternal); - Assert.AreEqual(0, parts[1].Data.Length); + Assert.AreEqual("http://www.aspose.com/Images/aspose-logo.jpg", parts[1].Name); + Assert.AreEqual("", parts[1].ContentType); + Assert.AreEqual("http://mytest.payload.external", parts[1].RelationshipType); + Assert.AreEqual(true, parts[1].IsExternal); + Assert.AreEqual(0, parts[1].Data.Length); - Assert.AreEqual("http://www.aspose.com/Images/aspose-logo.jpg", parts[2].Name); - Assert.AreEqual("", parts[2].ContentType); - Assert.AreEqual("http://mytest.payload.external", parts[2].RelationshipType); - Assert.AreEqual(true, parts[2].IsExternal); - Assert.AreEqual(0, parts[2].Data.Length); + Assert.AreEqual("http://www.aspose.com/Images/aspose-logo.jpg", parts[2].Name); + Assert.AreEqual("", parts[2].ContentType); + Assert.AreEqual("http://mytest.payload.external", parts[2].RelationshipType); + Assert.AreEqual(true, parts[2].IsExternal); + Assert.AreEqual(0, parts[2].Data.Length); } [TestCase(false)] @@ -2351,7 +2058,7 @@ public void CopyTemplateStylesViaDocumentNew() Assert.AreEqual(21, target.Styles.Count); //ExEnd } - + [Test] public void ReadMacrosFromExistingDocument() { @@ -2359,8 +2066,8 @@ public void ReadMacrosFromExistingDocument() //ExFor:Document.VbaProject //ExFor:VbaModuleCollection //ExFor:VbaModuleCollection.Count - //ExFor:VbaModuleCollection.Item(Int32) - //ExFor:VbaModuleCollection.Item(String) + //ExFor:VbaModuleCollection.Item(System.Int32) + //ExFor:VbaModuleCollection.Item(System.String) //ExFor:VbaModuleCollection.Remove //ExFor:VbaModule //ExFor:VbaModule.Name @@ -2380,7 +2087,7 @@ public void ReadMacrosFromExistingDocument() ? $"Project name: {vbaProject.Name} signed; Project code page: {vbaProject.CodePage}; Modules count: {vbaProject.Modules.Count()}\n" : $"Project name: {vbaProject.Name} not signed; Project code page: {vbaProject.CodePage}; Modules count: {vbaProject.Modules.Count()}\n"); - VbaModuleCollection vbaModules = doc.VbaProject.Modules; + VbaModuleCollection vbaModules = doc.VbaProject.Modules; Assert.AreEqual(vbaModules.Count(), 3); @@ -2455,6 +2162,7 @@ public void CreateWebExtension() //ExStart //ExFor:BaseWebExtensionCollection`1.Add(`0) //ExFor:BaseWebExtensionCollection`1.Clear + //ExFor:Document.WebExtensionTaskPanes //ExFor:TaskPane //ExFor:TaskPane.DockState //ExFor:TaskPane.IsVisible @@ -2467,6 +2175,7 @@ public void CreateWebExtension() //ExFor:WebExtension.Properties //ExFor:WebExtension.Bindings //ExFor:WebExtension.IsFrozen + //ExFor:WebExtensionReference //ExFor:WebExtensionReference.Id //ExFor:WebExtensionReference.Version //ExFor:WebExtensionReference.StoreType @@ -2479,6 +2188,8 @@ public void CreateWebExtension() //ExFor:WebExtensionBindingType //ExFor:TaskPaneDockState //ExFor:TaskPaneCollection + //ExFor:WebExtensionBinding.AppRef + //ExFor:WebExtensionBinding.BindingType //ExSummary:Shows how to add a web extension to a document. Document doc = new Document(); @@ -2515,7 +2226,6 @@ public void CreateWebExtension() doc.WebExtensionTaskPanes.Clear(); Assert.AreEqual(0, doc.WebExtensionTaskPanes.Count); - //ExEnd doc = new Document(ArtifactsDir + "Document.WebExtension.docx"); myScriptTaskPane = doc.WebExtensionTaskPanes[0]; @@ -2540,6 +2250,7 @@ public void CreateWebExtension() Assert.AreEqual("104380646", webExtension.Bindings[0].AppRef); Assert.False(webExtension.IsFrozen); + //ExEnd } [Test] @@ -2596,9 +2307,12 @@ public void EpubCover() public void TextWatermark() { //ExStart + //ExFor:Document.Watermark + //ExFor:Watermark //ExFor:Watermark.SetText(String) //ExFor:Watermark.SetText(String, TextWatermarkOptions) //ExFor:Watermark.Remove + //ExFor:TextWatermarkOptions //ExFor:TextWatermarkOptions.FontFamily //ExFor:TextWatermarkOptions.FontSize //ExFor:TextWatermarkOptions.Color @@ -2606,6 +2320,7 @@ public void TextWatermark() //ExFor:TextWatermarkOptions.IsSemitrasparent //ExFor:WatermarkLayout //ExFor:WatermarkType + //ExFor:Watermark.Type //ExSummary:Shows how to create a text watermark. Document doc = new Document(); @@ -2640,8 +2355,11 @@ public void ImageWatermark() { //ExStart //ExFor:Watermark.SetImage(Image, ImageWatermarkOptions) + //ExFor:ImageWatermarkOptions //ExFor:ImageWatermarkOptions.Scale //ExFor:ImageWatermarkOptions.IsWashout + //ExFor:Watermark.SetImage(Image) + //ExFor:Watermark.SetImage(String, ImageWatermarkOptions) //ExSummary:Shows how to create a watermark from an image in the local file system. Document doc = new Document(); @@ -2652,7 +2370,12 @@ public void ImageWatermark() imageWatermarkOptions.IsWashout = false; #if NET461_OR_GREATER || JAVA + // We have a different options to insert image: doc.Watermark.SetImage(Image.FromFile(ImageDir + "Logo.jpg"), imageWatermarkOptions); + + doc.Watermark.SetImage(Image.FromFile(ImageDir + "Logo.jpg")); + + doc.Watermark.SetImage(ImageDir + "Logo.jpg", imageWatermarkOptions); #elif NET5_0_OR_GREATER using (SKBitmap image = SKBitmap.Decode(ImageDir + "Logo.jpg")) { @@ -2698,70 +2421,6 @@ public void SpellingAndGrammarErrors(bool showErrors) Assert.AreEqual(showErrors, doc.ShowSpellingErrors); } - [TestCase(Granularity.CharLevel)] - [TestCase(Granularity.WordLevel)] - public void GranularityCompareOption(Granularity granularity) - { - //ExStart - //ExFor:CompareOptions.Granularity - //ExFor:Granularity - //ExSummary:Shows to specify a granularity while comparing documents. - Document docA = new Document(); - DocumentBuilder builderA = new DocumentBuilder(docA); - builderA.Writeln("Alpha Lorem ipsum dolor sit amet, consectetur adipiscing elit"); - - Document docB = new Document(); - DocumentBuilder builderB = new DocumentBuilder(docB); - builderB.Writeln("Lorems ipsum dolor sit amet consectetur - \"adipiscing\" elit"); - - // Specify whether changes are tracking - // by character ('Granularity.CharLevel'), or by word ('Granularity.WordLevel'). - Aspose.Words.Comparing.CompareOptions compareOptions = new Aspose.Words.Comparing.CompareOptions(); - compareOptions.Granularity = granularity; - - docA.Compare(docB, "author", DateTime.Now, compareOptions); - - // The first document's collection of revision groups contains all the differences between documents. - RevisionGroupCollection groups = docA.Revisions.Groups; - Assert.AreEqual(5, groups.Count); - //ExEnd - - if (granularity == Granularity.CharLevel) - { - Assert.AreEqual(RevisionType.Deletion, groups[0].RevisionType); - Assert.AreEqual("Alpha ", groups[0].Text); - - Assert.AreEqual(RevisionType.Deletion, groups[1].RevisionType); - Assert.AreEqual(",", groups[1].Text); - - Assert.AreEqual(RevisionType.Insertion, groups[2].RevisionType); - Assert.AreEqual("s", groups[2].Text); - - Assert.AreEqual(RevisionType.Insertion, groups[3].RevisionType); - Assert.AreEqual("- \"", groups[3].Text); - - Assert.AreEqual(RevisionType.Insertion, groups[4].RevisionType); - Assert.AreEqual("\"", groups[4].Text); - } - else - { - Assert.AreEqual(RevisionType.Deletion, groups[0].RevisionType); - Assert.AreEqual("Alpha Lorem", groups[0].Text); - - Assert.AreEqual(RevisionType.Deletion, groups[1].RevisionType); - Assert.AreEqual(",", groups[1].Text); - - Assert.AreEqual(RevisionType.Insertion, groups[2].RevisionType); - Assert.AreEqual("Lorems", groups[2].Text); - - Assert.AreEqual(RevisionType.Insertion, groups[3].RevisionType); - Assert.AreEqual("- \"", groups[3].Text); - - Assert.AreEqual(RevisionType.Insertion, groups[4].RevisionType); - Assert.AreEqual("\"", groups[4].Text); - } - } - [Test] public void IgnorePrinterMetrics() { @@ -2806,7 +2465,7 @@ public void SpellingOrGrammar(bool checkSpellingGrammar) // The string with spelling errors. doc.FirstSection.Body.FirstParagraph.Runs.Add(new Run(doc, "The speeling in this documentz is all broked.")); - // Spelling/Grammar check start if we set properties to false. + // Spelling/Grammar check start if we set properties to false. // We can see all errors in Microsoft Word via Review -> Spelling & Grammar. // Note that Microsoft Word does not start grammar/spell check automatically for DOC and RTF document format. doc.SpellingChecked = checkSpellingGrammar; @@ -2854,10 +2513,14 @@ public void Frameset() //ExFor:Frameset.FrameDefaultUrl //ExFor:Frameset.IsFrameLinkToFile //ExFor:Frameset.ChildFramesets + //ExFor:FramesetCollection + //ExFor:FramesetCollection.Count + //ExFor:FramesetCollection.Item(Int32) //ExSummary:Shows how to access frames on-page. // Document contains several frames with links to other documents. Document doc = new Document(MyDir + "Frameset.docx"); + Assert.AreEqual(3, doc.Frameset.ChildFramesets.Count); // We can check the default URL (a web page URL or local document) or if the frame is an external resource. Assert.AreEqual("https://file-examples-com.github.io/uploads/2017/02/file-sample_100kB.docx", doc.Frameset.ChildFramesets[0].ChildFramesets[0].FrameDefaultUrl); @@ -2989,6 +2652,7 @@ public void PageIsInColor() { //ExStart //ExFor:PageInfo.Colored + //ExFor:Document.GetPageInfo(Int32) //ExSummary:Shows how to check whether the page is in color or not. Document doc = new Document(MyDir + "Document.docx"); @@ -3088,9 +2752,21 @@ public void SaveDocumentToStream(SaveFormat saveFormat) doc.Save(stream, saveOptions); } - else + else doc.Save(stream, saveFormat); } } + + [Test] + public void HasMacros() + { + //ExStart:HasMacros + //GistId:6e4482e7434754c31c6f2f6e4bf48bb1 + //ExFor:FileFormatInfo.HasMacros + //ExSummary:Shows how to check VBA macro presence without loading document. + FileFormatInfo fileFormatInfo = FileFormatUtil.DetectFileFormat(MyDir + "Macro.docm"); + Assert.IsTrue(fileFormatInfo.HasMacros); + //ExEnd:HasMacros + } } } diff --git a/Examples/ApiExamples/ApiExamples/ExDocumentBuilder.cs b/Examples/ApiExamples/ApiExamples/ExDocumentBuilder.cs index 3242de944..0a7f257d5 100644 --- a/Examples/ApiExamples/ApiExamples/ExDocumentBuilder.cs +++ b/Examples/ApiExamples/ApiExamples/ExDocumentBuilder.cs @@ -164,6 +164,7 @@ public void InsertHorizontalRule() //ExFor:DocumentBuilder.InsertHorizontalRule //ExFor:ShapeBase.IsHorizontalRule //ExFor:Shape.HorizontalRuleFormat + //ExFor:HorizontalRuleAlignment //ExFor:HorizontalRuleFormat //ExFor:HorizontalRuleFormat.Alignment //ExFor:HorizontalRuleFormat.WidthPercent @@ -1905,6 +1906,7 @@ public void SignatureLineProviderId() //ExFor:SignatureLine.IsSigned //ExFor:SignatureLine.IsValid //ExFor:SignatureLine.ProviderId + //ExFor:SignatureLineOptions //ExFor:SignatureLineOptions.ShowDate //ExFor:SignatureLineOptions.Email //ExFor:SignatureLineOptions.DefaultInstructions @@ -3011,6 +3013,10 @@ public void SmartStyleBehavior() [Test] public void EmphasesWarningSourceMarkdown() { + //ExStart + //ExFor:WarningInfo.Source + //ExFor:WarningSource + //ExSummary:Shows how to work with the warning source. Document doc = new Document(MyDir + "Emphases markdown warning.docx"); WarningInfoCollection warnings = new WarningInfoCollection(); @@ -3022,6 +3028,7 @@ public void EmphasesWarningSourceMarkdown() if (warningInfo.Source == WarningSource.Markdown) Assert.AreEqual("The (*, 0:11) cannot be properly written into Markdown.", warningInfo.Description); } + //ExEnd } [Test] @@ -3031,8 +3038,12 @@ public void DoNotIgnoreHeaderFooter() //ExFor:ImportFormatOptions.IgnoreHeaderFooter //ExSummary:Shows how to specifies ignoring or not source formatting of headers/footers content. Document dstDoc = new Document(MyDir + "Document.docx"); - Document srcDoc = new Document(MyDir + "Header and footer types.docx"); - + Document srcDoc = new Document(MyDir + "Header and footer types.docx"); + + // If 'IgnoreHeaderFooter' is false then the original formatting for header/footer content + // from "Header and footer types.docx" will be used. + // If 'IgnoreHeaderFooter' is true then the formatting for header/footer content + // from "Document.docx" will be used. ImportFormatOptions importFormatOptions = new ImportFormatOptions(); importFormatOptions.IgnoreHeaderFooter = false; @@ -3546,6 +3557,7 @@ public void PhoneticGuide() //ExStart //ExFor:Run.IsPhoneticGuide //ExFor:Run.PhoneticGuide + //ExFor:PhoneticGuide //ExFor:PhoneticGuide.BaseText //ExFor:PhoneticGuide.RubyText //ExSummary:Shows how to get properties of the phonetic guide. @@ -3554,8 +3566,10 @@ public void PhoneticGuide() RunCollection runs = doc.FirstSection.Body.FirstParagraph.Runs; // Use phonetic guide in the Asian text. Assert.AreEqual(true, runs[0].IsPhoneticGuide); - Assert.AreEqual("base", runs[0].PhoneticGuide.BaseText); - Assert.AreEqual("ruby", runs[0].PhoneticGuide.RubyText); + + PhoneticGuide phoneticGuide = runs[0].PhoneticGuide; + Assert.AreEqual("base", phoneticGuide.BaseText); + Assert.AreEqual("ruby", phoneticGuide.RubyText); //ExEnd } } diff --git a/Examples/ApiExamples/ApiExamples/ExDocumentBuilderImages.cs b/Examples/ApiExamples/ApiExamples/ExDocumentBuilderImages.cs index 91415861f..4afcda490 100644 --- a/Examples/ApiExamples/ApiExamples/ExDocumentBuilderImages.cs +++ b/Examples/ApiExamples/ApiExamples/ExDocumentBuilderImages.cs @@ -289,7 +289,7 @@ public void InsertImageFromByteArray() Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); - byte[] imageByteArray = File.ReadAllBytes(ImageDir + "Logo.jpg"); + byte[] imageByteArray = TestUtil.ImageToByteArray(ImageDir + "Logo.jpg"); // Below are three ways of inserting an image from a byte array. // 1 - Inline shape with a default size based on the image's original dimensions: diff --git a/Examples/ApiExamples/ApiExamples/ExDocumentVisitor.cs b/Examples/ApiExamples/ApiExamples/ExDocumentVisitor.cs index e49fa71de..9f91ccb63 100644 --- a/Examples/ApiExamples/ApiExamples/ExDocumentVisitor.cs +++ b/Examples/ApiExamples/ApiExamples/ExDocumentVisitor.cs @@ -19,11 +19,15 @@ namespace ApiExamples { [TestFixture] public class ExDocumentVisitor : ApiExampleBase - { - //ExStart - //ExFor:Document.Accept(DocumentVisitor) - //ExFor:Body.Accept(DocumentVisitor) - //ExFor:SubDocument.Accept(DocumentVisitor) + { + //ExStart + //ExFor:Document.Accept(DocumentVisitor) + //ExFor:Section.Accept(DocumentVisitor) + //ExFor:SubDocument.Accept(DocumentVisitor) + //ExFor:CompositeNode.AcceptEnd(DocumentVisitor) + //ExFor:CompositeNode.AcceptStart(DocumentVisitor) + //ExFor:Document.AcceptEnd(DocumentVisitor) + //ExFor:Document.AcceptStart(DocumentVisitor) //ExFor:DocumentVisitor //ExFor:DocumentVisitor.VisitRun(Run) //ExFor:DocumentVisitor.VisitDocumentEnd(Document) @@ -35,6 +39,8 @@ public class ExDocumentVisitor : ApiExampleBase //ExFor:DocumentVisitor.VisitParagraphStart(Paragraph) //ExFor:DocumentVisitor.VisitParagraphEnd(Paragraph) //ExFor:DocumentVisitor.VisitSubDocument(SubDocument) + //ExFor:DocumentVisitor.VisitStructuredDocumentTagRangeEnd(StructuredDocumentTagRangeEnd) + //ExFor:DocumentVisitor.VisitStructuredDocumentTagRangeStart(StructuredDocumentTagRangeStart) //ExSummary:Shows how to use a document visitor to print a document's node structure. [Test] //ExSkip public void DocStructureToText() @@ -183,6 +189,26 @@ public override VisitorAction VisitSubDocument(SubDocument subDocument) return VisitorAction.Continue; } + /// + /// Called when a SubDocument node is encountered in the document. + /// + public override VisitorAction VisitStructuredDocumentTagRangeStart(StructuredDocumentTagRangeStart sdtRangeStart) + { + IndentAndAppendLine("[SdtRangeStart]"); + + return VisitorAction.Continue; + } + + /// + /// Called when a SubDocument node is encountered in the document. + /// + public override VisitorAction VisitStructuredDocumentTagRangeEnd(StructuredDocumentTagRangeEnd sdtRangeEnd) + { + IndentAndAppendLine("[SdtRangeEnd]"); + + return VisitorAction.Continue; + } + /// /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree. /// @@ -217,6 +243,8 @@ private static void TestDocStructureToText(DocStructurePrinter visitor) //ExStart //ExFor:Cell.Accept(DocumentVisitor) + //ExFor:Cell.AcceptStart(DocumentVisitor) + //ExFor:Cell.AcceptEnd(DocumentVisitor) //ExFor:Cell.IsFirstCell //ExFor:Cell.IsLastCell //ExFor:DocumentVisitor.VisitTableEnd(Table) @@ -226,6 +254,8 @@ private static void TestDocStructureToText(DocStructurePrinter visitor) //ExFor:DocumentVisitor.VisitCellStart(Cell) //ExFor:DocumentVisitor.VisitCellEnd(Cell) //ExFor:Row.Accept(DocumentVisitor) + //ExFor:Row.AcceptStart(DocumentVisitor) + //ExFor:Row.AcceptEnd(DocumentVisitor) //ExFor:Row.FirstCell //ExFor:Row.GetText //ExFor:Row.IsFirstRow @@ -648,6 +678,8 @@ private static void TestFieldToText(FieldStructurePrinter visitor) //ExFor:DocumentVisitor.VisitHeaderFooterStart(HeaderFooter) //ExFor:DocumentVisitor.VisitHeaderFooterEnd(HeaderFooter) //ExFor:HeaderFooter.Accept(DocumentVisitor) + //ExFor:HeaderFooter.AcceptStart(DocumentVisitor) + //ExFor:HeaderFooter.AcceptEnd(DocumentVisitor) //ExFor:HeaderFooterCollection.ToArray //ExFor:Run.Accept(DocumentVisitor) //ExFor:Run.GetText @@ -858,6 +890,8 @@ private static void TestEditableRangeToText(EditableRangeStructurePrinter visito //ExFor:DocumentVisitor.VisitFootnoteEnd(Footnote) //ExFor:DocumentVisitor.VisitFootnoteStart(Footnote) //ExFor:Footnote.Accept(DocumentVisitor) + //ExFor:Footnote.AcceptStart(DocumentVisitor) + //ExFor:Footnote.AcceptEnd(DocumentVisitor) //ExSummary:Shows how to print the node structure of every footnote in a document. [Test] //ExSkip public void FootnoteToText() @@ -952,15 +986,17 @@ private static void TestFootnoteToText(FootnoteStructurePrinter visitor) Assert.True(visitorText.Contains("[Footnote start] Type: Footnote")); Assert.True(visitorText.Contains("[Footnote end]")); Assert.True(visitorText.Contains("[Run]")); - } - - //ExStart - //ExFor:DocumentVisitor.VisitOfficeMathEnd(OfficeMath) - //ExFor:DocumentVisitor.VisitOfficeMathStart(OfficeMath) - //ExFor:MathObjectType - //ExFor:OfficeMath.Accept(DocumentVisitor) - //ExFor:OfficeMath.MathObjectType - //ExSummary:Shows how to print the node structure of every office math node in a document. + } + + //ExStart + //ExFor:DocumentVisitor.VisitOfficeMathEnd(OfficeMath) + //ExFor:DocumentVisitor.VisitOfficeMathStart(OfficeMath) + //ExFor:MathObjectType + //ExFor:OfficeMath.Accept(DocumentVisitor) + //ExFor:OfficeMath.AcceptStart(DocumentVisitor) + //ExFor:OfficeMath.AcceptEnd(DocumentVisitor) + //ExFor:OfficeMath.MathObjectType + //ExSummary:Shows how to print the node structure of every office math node in a document. [Test] //ExSkip public void OfficeMathToText() { @@ -1171,6 +1207,8 @@ private static void TestSmartTagToText(SmartTagStructurePrinter visitor) //ExStart //ExFor:StructuredDocumentTag.Accept(DocumentVisitor) + //ExFor:StructuredDocumentTag.AcceptStart(DocumentVisitor) + //ExFor:StructuredDocumentTag.AcceptEnd(DocumentVisitor) //ExFor:DocumentVisitor.VisitStructuredDocumentTagEnd(StructuredDocumentTag) //ExFor:DocumentVisitor.VisitStructuredDocumentTagStart(StructuredDocumentTag) //ExSummary:Shows how to print the node structure of every structured document tag in a document. diff --git a/Examples/ApiExamples/ApiExamples/ExDrawing.cs b/Examples/ApiExamples/ApiExamples/ExDrawing.cs index 0dc565f44..754d826c4 100644 --- a/Examples/ApiExamples/ApiExamples/ExDrawing.cs +++ b/Examples/ApiExamples/ApiExamples/ExDrawing.cs @@ -238,7 +238,11 @@ public void FillSolid() { //ExStart //ExFor:Fill.Color() - //ExFor:Fill.Solid(Color) + //ExFor:FillType + //ExFor:Fill.FillType + //ExFor:Fill.Solid + //ExFor:Fill.Transparency + //ExFor:Font.Fill //ExSummary:Shows how to convert any of the fills back to solid fill. Document doc = new Document(MyDir + "Two color gradient.docx"); @@ -251,7 +255,7 @@ public void FillSolid() Console.WriteLine("The fill is transparent at {0}%", fill.Transparency * 100); // Change type of the fill to Solid with uniform green color. - fill.Solid(Color.Green); + fill.Solid(); Console.WriteLine("\nThe fill is changed:"); Console.WriteLine("The type of the fill is: {0}", fill.FillType); Console.WriteLine("The foreground color of the fill is: {0}", fill.ForeColor); @@ -340,6 +344,8 @@ public void StrokePattern() //ExFor:GroupShape //ExFor:GroupShape.#ctor(DocumentBase) //ExFor:GroupShape.Accept(DocumentVisitor) + //ExFor:GroupShape.AcceptStart(DocumentVisitor) + //ExFor:GroupShape.AcceptEnd(DocumentVisitor) //ExFor:ShapeBase.IsGroup //ExFor:ShapeBase.ShapeType //ExSummary:Shows how to create a group of shapes, and print its contents using a document visitor. diff --git a/Examples/ApiExamples/ApiExamples/ExField.cs b/Examples/ApiExamples/ApiExamples/ExField.cs index b70fa643b..2eab86765 100644 --- a/Examples/ApiExamples/ApiExamples/ExField.cs +++ b/Examples/ApiExamples/ApiExamples/ExField.cs @@ -468,6 +468,10 @@ public void FieldDatabase() //ExFor:FieldDatabase.LastRecord //ExFor:FieldDatabase.Query //ExFor:FieldDatabase.TableFormat + //ExFor:FieldDatabaseDataTable + //ExFor:IFieldDatabaseProvider + //ExFor:IFieldDatabaseProvider.GetQueryResult(String,String,String,FieldDatabase) + //ExFor:FieldOptions.FieldDatabaseProvider //ExSummary:Shows how to extract data from a database and insert it as a field into a document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); @@ -2436,6 +2440,8 @@ public void FieldCitation() //ExFor:FieldCitation.VolumeNumber //ExFor:FieldBibliography //ExFor:FieldBibliography.FormatLanguageId + //ExFor:FieldBibliography.FilterLanguageId + //ExFor:FieldBibliography.SourceTag //ExSummary:Shows how to work with CITATION and BIBLIOGRAPHY fields. // Open a document containing bibliographical sources that we can find in // Microsoft Word via References -> Citations & Bibliography -> Manage Sources. @@ -2478,8 +2484,10 @@ public void FieldCitation() builder.InsertBreak(BreakType.PageBreak); FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true); fieldBibliography.FormatLanguageId = "5129"; + fieldBibliography.FilterLanguageId = "5129"; + fieldBibliography.SourceTag = "Book2"; - Assert.AreEqual(" BIBLIOGRAPHY \\l 5129", fieldBibliography.GetFieldCode()); + Assert.AreEqual(" BIBLIOGRAPHY \\l 5129 \\f 5129 \\m Book2", fieldBibliography.GetFieldCode()); doc.UpdateFields(); doc.Save(ArtifactsDir + "Field.CITATION.docx"); @@ -2516,9 +2524,10 @@ public void FieldCitation() fieldBibliography = (FieldBibliography)doc.Range.Fields[2]; - TestUtil.VerifyField(FieldType.FieldBibliography, " BIBLIOGRAPHY \\l 5129", - "Cardholder, A. (2018). My Book, Vol. II. New York: Doe Co. Ltd.\rDoe, J. (2018). My Book, Vol I. London: Doe Co. Ltd.\r", fieldBibliography); + TestUtil.VerifyField(FieldType.FieldBibliography, " BIBLIOGRAPHY \\l 5129 \\f 5129 \\m Book2", + "Cardholder, A. (2018). My Book, Vol. II. New York: Doe Co. Ltd.\r", fieldBibliography); Assert.AreEqual("5129", fieldBibliography.FormatLanguageId); + Assert.AreEqual("5129", fieldBibliography.FilterLanguageId); fieldCitation = (FieldCitation)doc.Range.Fields[3]; @@ -2536,6 +2545,7 @@ public void FieldCitation() //ExStart //ExFor:IBibliographyStylesProvider + //ExFor:IBibliographyStylesProvider.GetStyle(String) //ExFor:FieldOptions.BibliographyStylesProvider //ExSummary:Shows how to override built-in styles or provide custom one. [Test] //ExSkip @@ -4896,6 +4906,7 @@ public void FieldBuilder() //ExFor:FieldBuilder.AddSwitch(String, String) //ExFor:FieldBuilder.BuildAndInsert(Paragraph) //ExFor:FieldArgumentBuilder + //ExFor:FieldArgumentBuilder.#ctor //ExFor:FieldArgumentBuilder.AddField(FieldBuilder) //ExFor:FieldArgumentBuilder.AddText(String) //ExFor:FieldArgumentBuilder.AddNode(Inline) @@ -6878,6 +6889,7 @@ public void FieldEQAsOfficeMath() { //ExStart //ExFor:FieldEQ + //ExFor:FieldEQ.AsOfficeMath //ExSummary:Shows how to replace the EQ field with Office Math. Document doc = new Document(MyDir + "Field sample - EQ.docx"); FieldEQ fieldEQ = doc.Range.Fields.OfType().First(); @@ -7336,6 +7348,7 @@ public void Legacy() public void SetFieldIndexFormat() { //ExStart + //ExFor:FieldIndexFormat //ExFor:FieldOptions.FieldIndexFormat //ExSummary:Shows how to formatting FieldIndex fields. Document doc = new Document(); @@ -7358,11 +7371,15 @@ public void SetFieldIndexFormat() //ExFor:ComparisonEvaluationResult.#ctor(bool) //ExFor:ComparisonEvaluationResult.#ctor(string) //ExFor:ComparisonEvaluationResult + //ExFor:ComparisonEvaluationResult.ErrorMessage + //ExFor:ComparisonEvaluationResult.Result //ExFor:ComparisonExpression //ExFor:ComparisonExpression.LeftExpression //ExFor:ComparisonExpression.ComparisonOperator //ExFor:ComparisonExpression.RightExpression //ExFor:FieldOptions.ComparisonExpressionEvaluator + //ExFor:IComparisonExpressionEvaluator + //ExFor:IComparisonExpressionEvaluator.Evaluate(Field,ComparisonExpression) //ExSummary:Shows how to implement custom evaluation for the IF and COMPARE fields. [TestCase(" IF {0} {1} {2} \"true argument\" \"false argument\" ", 1, null, "true argument")] //ExSkip [TestCase(" IF {0} {1} {2} \"true argument\" \"false argument\" ", 0, null, "false argument")] //ExSkip @@ -7408,6 +7425,11 @@ private class ComparisonExpressionEvaluator : IComparisonExpressionEvaluator public ComparisonExpressionEvaluator(ComparisonEvaluationResult result) { mResult = result; + if (mResult != null) + { + Console.WriteLine(mResult.ErrorMessage); + Console.WriteLine(mResult.Result); + } } public ComparisonEvaluationResult Evaluate(Field field, ComparisonExpression expression) @@ -7536,9 +7558,12 @@ public void ComparisonExpressionEvaluatorHeaderFooterFields() } //ExStart + //ExFor:FieldOptions.FieldUpdatingCallback + //ExFor:FieldOptions.FieldUpdatingProgressCallback //ExFor:IFieldUpdatingCallback //ExFor:IFieldUpdatingProgressCallback //ExFor:IFieldUpdatingProgressCallback.Notify(FieldUpdatingProgressArgs) + //ExFor:FieldUpdatingProgressArgs //ExFor:FieldUpdatingProgressArgs.UpdateCompleted //ExFor:FieldUpdatingProgressArgs.TotalFieldsCount //ExFor:FieldUpdatingProgressArgs.UpdatedFieldsCount @@ -7608,16 +7633,87 @@ void IFieldUpdatingProgressCallback.Notify(FieldUpdatingProgressArgs args) [Test] public void BibliographySources() - { - //ExStart:BibliographySources - //GistId:eeeec1fbf118e95e7df3f346c91ed726 - //ExFor:Bibliography - //ExFor:Bibliography.Sources - //ExFor:Source.Title + { + //ExStart:BibliographySources + //GistId:eeeec1fbf118e95e7df3f346c91ed726 + //ExFor:Document.Bibliography + //ExFor:Bibliography + //ExFor:Bibliography.Sources + //ExFor:Source + //ExFor:Source.Title + //ExFor:Source.AbbreviatedCaseNumber + //ExFor:Source.AlbumTitle + //ExFor:Source.BookTitle + //ExFor:Source.Broadcaster + //ExFor:Source.BroadcastTitle + //ExFor:Source.CaseNumber + //ExFor:Source.ChapterNumber + //ExFor:Source.City + //ExFor:Source.Comments + //ExFor:Source.ConferenceName + //ExFor:Source.CountryOrRegion + //ExFor:Source.Court + //ExFor:Source.Day + //ExFor:Source.DayAccessed + //ExFor:Source.Department + //ExFor:Source.Distributor + //ExFor:Source.Edition + //ExFor:Source.Guid + //ExFor:Source.Institution + //ExFor:Source.InternetSiteTitle + //ExFor:Source.Issue + //ExFor:Source.JournalName + //ExFor:Source.Lcid + //ExFor:Source.Medium + //ExFor:Source.Month + //ExFor:Source.MonthAccessed + //ExFor:Source.NumberVolumes + //ExFor:Source.Pages + //ExFor:Source.PatentNumber + //ExFor:Source.PeriodicalTitle + //ExFor:Source.ProductionCompany + //ExFor:Source.PublicationTitle + //ExFor:Source.Publisher + //ExFor:Source.RecordingNumber + //ExFor:Source.RefOrder + //ExFor:Source.Reporter + //ExFor:Source.ShortTitle + //ExFor:Source.SourceType + //ExFor:Source.StandardNumber + //ExFor:Source.StateOrProvince + //ExFor:Source.Station + //ExFor:Source.Tag + //ExFor:Source.Theater + //ExFor:Source.ThesisType + //ExFor:Source.Type + //ExFor:Source.Url + //ExFor:Source.Version + //ExFor:Source.Volume + //ExFor:Source.Year + //ExFor:Source.YearAccessed //ExFor:Source.Contributors + //ExFor:SourceType + //ExFor:Contributor //ExFor:ContributorCollection //ExFor:ContributorCollection.Author + //ExFor:ContributorCollection.Artist + //ExFor:ContributorCollection.BookAuthor + //ExFor:ContributorCollection.Compiler + //ExFor:ContributorCollection.Composer + //ExFor:ContributorCollection.Conductor + //ExFor:ContributorCollection.Counsel + //ExFor:ContributorCollection.Director + //ExFor:ContributorCollection.Editor + //ExFor:ContributorCollection.Interviewee + //ExFor:ContributorCollection.Interviewer + //ExFor:ContributorCollection.Inventor + //ExFor:ContributorCollection.Performer + //ExFor:ContributorCollection.Producer + //ExFor:ContributorCollection.Translator + //ExFor:ContributorCollection.Writer //ExFor:PersonCollection + //ExFor:PersonCollection.Count + //ExFor:PersonCollection.Item(Int32) //ExFor:Person //ExFor:Person.First //ExFor:Person.Middle @@ -7630,12 +7726,81 @@ public void BibliographySources() Source source = bibliography.Sources.FirstOrDefault(); Assert.AreEqual("Book 0 (No LCID)", source.Title); + Assert.AreEqual(SourceType.Book, source.SourceType); + Assert.AreEqual(3, source.Contributors.Count()); + Assert.IsNull(source.AbbreviatedCaseNumber); + Assert.IsNull(source.AlbumTitle); + Assert.IsNull(source.BookTitle); + Assert.IsNull(source.Broadcaster); + Assert.IsNull(source.BroadcastTitle); + Assert.IsNull(source.CaseNumber); + Assert.IsNull(source.ChapterNumber); + Assert.IsNull(source.Comments); + Assert.IsNull(source.ConferenceName); + Assert.IsNull(source.CountryOrRegion); + Assert.IsNull(source.Court); + Assert.IsNull(source.Day); + Assert.IsNull(source.DayAccessed); + Assert.IsNull(source.Department); + Assert.IsNull(source.Distributor); + Assert.IsNull(source.Edition); + Assert.IsNull(source.Guid); + Assert.IsNull(source.Institution); + Assert.IsNull(source.InternetSiteTitle); + Assert.IsNull(source.Issue); + Assert.IsNull(source.JournalName); + Assert.IsNull(source.Lcid); + Assert.IsNull(source.Medium); + Assert.IsNull(source.Month); + Assert.IsNull(source.MonthAccessed); + Assert.IsNull(source.NumberVolumes); + Assert.IsNull(source.Pages); + Assert.IsNull(source.PatentNumber); + Assert.IsNull(source.PeriodicalTitle); + Assert.IsNull(source.ProductionCompany); + Assert.IsNull(source.PublicationTitle); + Assert.IsNull(source.Publisher); + Assert.IsNull(source.RecordingNumber); + Assert.IsNull(source.RefOrder); + Assert.IsNull(source.Reporter); + Assert.IsNull(source.ShortTitle); + Assert.IsNull(source.StandardNumber); + Assert.IsNull(source.StateOrProvince); + Assert.IsNull(source.Station); + Assert.AreEqual("BookNoLCID", source.Tag); + Assert.IsNull(source.Theater); + Assert.IsNull(source.ThesisType); + Assert.IsNull(source.Type); + Assert.IsNull(source.Url); + Assert.IsNull(source.Version); + Assert.IsNull(source.Volume); + Assert.IsNull(source.Year); + Assert.IsNull(source.YearAccessed); ContributorCollection contributors = source.Contributors; + Assert.IsNull(contributors.Artist); + Assert.IsNull(contributors.BookAuthor); + Assert.IsNull(contributors.Compiler); + Assert.IsNull(contributors.Composer); + Assert.IsNull(contributors.Conductor); + Assert.IsNull(contributors.Counsel); + Assert.IsNull(contributors.Director); + Assert.IsNotNull(contributors.Editor); + Assert.IsNull(contributors.Interviewee); + Assert.IsNull(contributors.Interviewer); + Assert.IsNull(contributors.Inventor); + Assert.IsNull(contributors.Performer); + Assert.IsNull(contributors.Producer); + Assert.IsNotNull(contributors.Translator); + Assert.IsNull(contributors.Writer); + + Contributor editor = contributors.Editor; + Assert.AreEqual(2, ((PersonCollection)editor).Count()); + PersonCollection authors = (PersonCollection)contributors.Author; Assert.AreEqual(2, authors.Count()); - Person person = authors.FirstOrDefault(); + Person person = authors[0]; Assert.AreEqual("Roxanne", person.First); Assert.AreEqual("Brielle", person.Middle); Assert.AreEqual("Tejeda", person.Last); diff --git a/Examples/ApiExamples/ApiExamples/ExFieldOptions.cs b/Examples/ApiExamples/ApiExamples/ExFieldOptions.cs index 42b8d3a43..0debef512 100644 --- a/Examples/ApiExamples/ApiExamples/ExFieldOptions.cs +++ b/Examples/ApiExamples/ApiExamples/ExFieldOptions.cs @@ -298,7 +298,7 @@ public void UseInvariantCultureNumberFormat() // Sometimes, fields may not format their numbers correctly under certain cultures. Assert.IsFalse(doc.FieldOptions.UseInvariantCultureNumberFormat); - Assert.AreEqual("$1234567,89 . ", field.Result); + Assert.AreEqual("$1.234.567,89 , ", field.Result); // To fix this, we could change the culture for the entire thread. // Another way to fix this is to set this flag, @@ -508,10 +508,10 @@ public void BarcodeGenerator() doc.Save(ArtifactsDir + "FieldOptions.BarcodeGenerator.docx"); //ExEnd - TestUtil.VerifyImage(769, 769, ArtifactsDir + "FieldOptions.BarcodeGenerator.QR.jpg"); - TestUtil.VerifyImage(117, 108, ArtifactsDir + "FieldOptions.BarcodeGenerator.EAN13.jpg"); - TestUtil.VerifyImage(395, 70, ArtifactsDir + "FieldOptions.BarcodeGenerator.CODE39.jpg"); - TestUtil.VerifyImage(633, 134, ArtifactsDir + "FieldOptions.BarcodeGenerator.ITF14.jpg"); + TestUtil.VerifyImage(223, 223, ArtifactsDir + "FieldOptions.BarcodeGenerator.QR.jpg"); + TestUtil.VerifyImage(126, 118, ArtifactsDir + "FieldOptions.BarcodeGenerator.EAN13.jpg"); + TestUtil.VerifyImage(204, 70, ArtifactsDir + "FieldOptions.BarcodeGenerator.CODE39.jpg"); + TestUtil.VerifyImage(168, 134, ArtifactsDir + "FieldOptions.BarcodeGenerator.ITF14.jpg"); doc = new Document(ArtifactsDir + "FieldOptions.BarcodeGenerator.docx"); Shape barcode = (Shape)doc.GetChild(NodeType.Shape, 0, true); diff --git a/Examples/ApiExamples/ApiExamples/ExFont.cs b/Examples/ApiExamples/ApiExamples/ExFont.cs index 258a3cac8..72373808a 100644 --- a/Examples/ApiExamples/ApiExamples/ExFont.cs +++ b/Examples/ApiExamples/ApiExamples/ExFont.cs @@ -626,6 +626,7 @@ public void ComplexScript() public void SparklingText() { //ExStart + //ExFor:TextEffect //ExFor:Font.TextEffect //ExSummary:Shows how to apply a visual effect to a run. Document doc = new Document(); @@ -781,7 +782,6 @@ public void Bidi() Assert.AreEqual(1033, run.Font.LocaleId); Assert.AreEqual(16, run.Font.Size); - Assert.AreEqual("Courier New", run.Font.Name); Assert.False(run.Font.Italic); Assert.False(run.Font.Bold); Assert.AreEqual(1025, run.Font.LocaleIdBi); @@ -1065,7 +1065,9 @@ public void SetFontAutoColor() //ExStart //ExFor:Font.Hidden - //ExFor:Paragraph.Accept + //ExFor:Paragraph.Accept(DocumentVisitor) + //ExFor:Paragraph.AcceptStart(DocumentVisitor) + //ExFor:Paragraph.AcceptEnd(DocumentVisitor) //ExFor:DocumentVisitor.VisitParagraphStart(Paragraph) //ExFor:DocumentVisitor.VisitFormField(FormField) //ExFor:DocumentVisitor.VisitTableEnd(Table) @@ -1077,9 +1079,13 @@ public void SetFontAutoColor() //ExFor:DocumentVisitor.VisitCommentStart(Comment) //ExFor:DocumentVisitor.VisitFootnoteStart(Footnote) //ExFor:SpecialChar - //ExFor:Node.Accept + //ExFor:SpecialChar.Accept(DocumentVisitor) + //ExFor:SpecialChar.GetText + //ExFor:Node.Accept(DocumentVisitor) //ExFor:Paragraph.ParagraphBreakFont - //ExFor:Table.Accept + //ExFor:Table.Accept(DocumentVisitor) + //ExFor:Table.AcceptStart(DocumentVisitor) + //ExFor:Table.AcceptEnd(DocumentVisitor) //ExSummary:Shows how to use a DocumentVisitor implementation to remove all hidden content from a document. [Test] //ExSkip public void RemoveHiddenContentFromDocument() @@ -1227,6 +1233,8 @@ public override VisitorAction VisitFootnoteStart(Footnote footnote) /// public override VisitorAction VisitSpecialChar(SpecialChar specialChar) { + Console.WriteLine(specialChar.GetText()); + if (specialChar.Font.Hidden) specialChar.Remove(); @@ -1446,6 +1454,7 @@ public void HasDmlEffect() { //ExStart //ExFor:Font.HasDmlEffect(TextDmlEffect) + //ExFor:TextDmlEffect //ExSummary:Shows how to check if a run displays a DrawingML text effect. Document doc = new Document(MyDir + "DrawingML text effects.docx"); @@ -1639,5 +1648,56 @@ public void CreateThemedStyle() Assert.AreEqual(ThemeColor.Accent5, run.Font.ThemeColor); Assert.AreEqual(Color.Empty, run.Font.Color); } + + [Test] + public void FontInfoEmbeddingLicensingRights() + { + //ExStart:FontInfoEmbeddingLicensingRights + //GistId:708ce40a68fac5003d46f6b4acfd5ff1 + //ExFor:FontInfo.EmbeddingLicensingRights + //ExFor:FontEmbeddingUsagePermissions + //ExFor:FontEmbeddingLicensingRights.EmbeddingUsagePermissions + //ExFor:FontEmbeddingLicensingRights.BitmapEmbeddingOnly + //ExFor:FontEmbeddingLicensingRights.NoSubsetting + //ExSummary:Shows how to get license rights information for embedded fonts (FontInfo). + Document doc = new Document(MyDir + "Embedded font rights.docx"); + + // Get the list of document fonts. + FontInfoCollection fontInfos = doc.FontInfos; + foreach (FontInfo fontInfo in fontInfos) + { + if (fontInfo.EmbeddingLicensingRights != null) + { + Console.WriteLine(fontInfo.EmbeddingLicensingRights.EmbeddingUsagePermissions); + Console.WriteLine(fontInfo.EmbeddingLicensingRights.BitmapEmbeddingOnly); + Console.WriteLine(fontInfo.EmbeddingLicensingRights.NoSubsetting); + } + } + //ExEnd:FontInfoEmbeddingLicensingRights + } + + [Test] + public void PhysicalFontInfoEmbeddingLicensingRights() + { + //ExStart:PhysicalFontInfoEmbeddingLicensingRights + //GistId:708ce40a68fac5003d46f6b4acfd5ff1 + //ExFor:PhysicalFontInfo.EmbeddingLicensingRights + //ExSummary:Shows how to get license rights information for embedded fonts (PhysicalFontInfo). + FontSettings settings = FontSettings.DefaultInstance; + FontSourceBase source = settings.GetFontsSources()[0]; + + // Get the list of available fonts. + IList fontInfos = source.GetAvailableFonts(); + foreach (PhysicalFontInfo fontInfo in fontInfos) + { + if (fontInfo.EmbeddingLicensingRights != null) + { + Console.WriteLine(fontInfo.EmbeddingLicensingRights.EmbeddingUsagePermissions); + Console.WriteLine(fontInfo.EmbeddingLicensingRights.BitmapEmbeddingOnly); + Console.WriteLine(fontInfo.EmbeddingLicensingRights.NoSubsetting); + } + } + //ExEnd:PhysicalFontInfoEmbeddingLicensingRights + } } -} +} \ No newline at end of file diff --git a/Examples/ApiExamples/ApiExamples/ExFontSettings.cs b/Examples/ApiExamples/ApiExamples/ExFontSettings.cs index 885b64ba8..967989519 100644 --- a/Examples/ApiExamples/ApiExamples/ExFontSettings.cs +++ b/Examples/ApiExamples/ApiExamples/ExFontSettings.cs @@ -1286,6 +1286,9 @@ public override Stream OpenFontDataStream() //ExFor:MemoryFontSource.#ctor(Byte[], Int32, String) //ExFor:FontSettings.SaveSearchCache(Stream) //ExFor:FontSettings.SetFontsSources(FontSourceBase[], Stream) + //ExFor:FileFontSource.CacheKey + //ExFor:MemoryFontSource.CacheKey + //ExFor:StreamFontSource.CacheKey //ExSummary:Shows how to speed up the font cache initialization process. [Test]//ExSkip public void LoadFontSearchCache() diff --git a/Examples/ApiExamples/ApiExamples/ExFormFields.cs b/Examples/ApiExamples/ApiExamples/ExFormFields.cs index bfa1223ce..949b52a5e 100644 --- a/Examples/ApiExamples/ApiExamples/ExFormFields.cs +++ b/Examples/ApiExamples/ApiExamples/ExFormFields.cs @@ -315,7 +315,7 @@ private void TestFormField(Document doc) TestUtil.VerifyField(FieldType.FieldFormDropDown, " FORMDROPDOWN \u0001", string.Empty, doc.Range.Fields[0]); TestUtil.VerifyField(FieldType.FieldFormCheckBox, " FORMCHECKBOX \u0001", string.Empty, doc.Range.Fields[1]); - TestUtil.VerifyField(FieldType.FieldFormTextInput, " FORMTEXT \u0001", "New placeholder text", doc.Range.Fields[2]); + TestUtil.VerifyField(FieldType.FieldFormTextInput, " FORMTEXT \u0001", "Regular", doc.Range.Fields[2]); FormFieldCollection formFields = doc.Range.FormFields; Assert.AreEqual(3, formFields.Count); @@ -345,7 +345,7 @@ private void TestFormField(Document doc) Assert.AreEqual("FIRST CAPITAL", formFields[2].TextInputFormat); Assert.AreEqual(TextFormFieldType.Regular, formFields[2].TextInputType); Assert.AreEqual(50, formFields[2].MaxLength); - Assert.AreEqual("New placeholder text", formFields[2].Result); + Assert.AreEqual("Regular", formFields[2].Result); } [Test] diff --git a/Examples/ApiExamples/ApiExamples/ExHeaderFooter.cs b/Examples/ApiExamples/ApiExamples/ExHeaderFooter.cs index 7c94351df..e570d7b2a 100644 --- a/Examples/ApiExamples/ApiExamples/ExHeaderFooter.cs +++ b/Examples/ApiExamples/ApiExamples/ExHeaderFooter.cs @@ -254,6 +254,7 @@ public void ReplaceText() //ExStart //ExFor:IReplacingCallback //ExFor:PageSetup.DifferentFirstPageHeaderFooter + //ExFor:FindReplaceOptions.#ctor(IReplacingCallback) //ExSummary:Shows how to track the order in which a text replacement operation traverses nodes. [TestCase(false)] //ExSkip [TestCase(true)] //ExSkip @@ -264,7 +265,7 @@ public void Order(bool differentFirstPageHeaderFooter) Section firstPageSection = doc.FirstSection; ReplaceLog logger = new ReplaceLog(); - FindReplaceOptions options = new FindReplaceOptions { ReplacingCallback = logger }; + FindReplaceOptions options = new FindReplaceOptions(logger); // Using a different header/footer for the first page will affect the search order. firstPageSection.PageSetup.DifferentFirstPageHeaderFooter = differentFirstPageHeaderFooter; diff --git a/Examples/ApiExamples/ApiExamples/ExHtmlLoadOptions.cs b/Examples/ApiExamples/ApiExamples/ExHtmlLoadOptions.cs index 1c4972f0e..767f862f7 100644 --- a/Examples/ApiExamples/ApiExamples/ExHtmlLoadOptions.cs +++ b/Examples/ApiExamples/ApiExamples/ExHtmlLoadOptions.cs @@ -29,6 +29,7 @@ internal class ExHtmlLoadOptions : ApiExampleBase public void SupportVml(bool supportVml) { //ExStart + //ExFor:HtmlLoadOptions //ExFor:HtmlLoadOptions.#ctor //ExFor:HtmlLoadOptions.SupportVml //ExSummary:Shows how to support conditional comments while loading an HTML document. @@ -212,6 +213,7 @@ public void GetSelectAsSdt() { //ExStart //ExFor:HtmlLoadOptions.PreferredControlType + //ExFor:HtmlControlType //ExSummary:Shows how to set preferred type of document nodes that will represent imported and