Ejemplo n.º 1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OpenXmlPartTreeViewItem"/> class
 /// with the referenced <see cref="IdPartPair"/> object.
 /// </summary>
 /// <param name="p">
 /// The <see cref="IdPartPair"/> object that the new instance will hold.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="p"/> is <see langword="null"/>.
 /// </exception>
 public OpenXmlPartTreeViewItem(IdPartPair p)
     : base(p != null && p.OpenXmlPart != null && p.OpenXmlPart.Parts != null &&
            (p.OpenXmlPart.Parts.Count() > 0 || p.OpenXmlPart.RootElement != null))
 {
     part = p ?? throw new ArgumentNullException(nameof(p));
 }
        /// <summary>
        /// Creates the appropriate code objects needed to create the entry method for the
        /// current request.
        /// </summary>
        /// <param name="part">
        /// The <see cref="OpenXmlPart"/> object and relationship id to build code for.
        /// </param>
        /// <param name="settings">
        /// The <see cref="ISerializeSettings"/> to use during the code generation
        /// process.
        /// </param>
        /// /// <param name="typeCounts">
        /// A lookup <see cref="IDictionary{TKey, TValue}"/> object containing the
        /// number of times a given type was referenced.  This is used for variable naming
        /// purposes.
        /// </param>
        /// <param name="namespaces">
        /// Collection <see cref="ISet{T}"/> used to keep track of all openxml namespaces
        /// used during the process.
        /// </param>
        /// <param name="blueprints">
        /// The collection of <see cref="OpenXmlPartBluePrint"/> objects that have already been
        /// visited.
        /// </param>
        /// <param name="rootVar">
        /// The root variable name and <see cref="Type"/> to use when building code
        /// statements to create new <see cref="OpenXmlPart"/> objects.
        /// </param>
        /// <returns>
        /// A collection of code statements and expressions that could be used to generate
        /// a new <paramref name="part"/> object from code.
        /// </returns>
        public static CodeStatementCollection BuildEntryMethodCodeStatements(
            IdPartPair part,
            ISerializeSettings settings,
            IDictionary <string, int> typeCounts,
            ISet <string> namespaces,
            OpenXmlPartBluePrintCollection blueprints,
            KeyValuePair <string, Type> rootVar)
        {
            // Argument validation
            if (part is null)
            {
                throw new ArgumentNullException(nameof(part));
            }
            if (settings is null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (blueprints is null)
            {
                throw new ArgumentNullException(nameof(blueprints));
            }
            if (String.IsNullOrWhiteSpace(rootVar.Key))
            {
                throw new ArgumentNullException(nameof(rootVar.Key));
            }
            bool hasHandlers = settings?.Handlers != null;

            // Use the custom handler methods if present and provide actual code
            if (hasHandlers && settings.Handlers.TryGetValue(part.OpenXmlPart.GetType(), out IOpenXmlHandler h))
            {
                if (h is IOpenXmlPartHandler partHandler)
                {
                    var customStatements = partHandler.BuildEntryMethodCodeStatements(
                        part, settings, typeCounts, namespaces, blueprints, rootVar);

                    if (customStatements != null)
                    {
                        return(customStatements);
                    }
                }
            }

            var    result                   = new CodeStatementCollection();
            var    partType                 = part.OpenXmlPart.GetType();
            var    partTypeName             = partType.Name;
            var    partTypeFullName         = partType.FullName;
            string varName                  = partType.Name.ToCamelCase();
            bool   customAddNewPartRequired = CheckForCustomAddNewPartMethod(partType, rootVar.Value, out string addNewPartName);

#pragma warning disable IDE0018 // Inline variable declaration
            OpenXmlPartBluePrint bpTemp;
#pragma warning restore IDE0018 // Inline variable declaration

            CodeMethodReferenceExpression referenceExpression;
            CodeMethodInvokeExpression    invokeExpression;
            CodeMethodReferenceExpression methodReference;

            // Make sure that the namespace for the current part is captured
            namespaces.Add(partType.Namespace);

            // If the URI of the current part has already been included into
            // the blue prints collection, build the AddPart invocation
            // code statement and exit current method iteration.
            if (blueprints.TryGetValue(part.OpenXmlPart.Uri, out bpTemp))
            {
                // Surround this snippet with blank lines to make it
                // stand out in the current section of code.
                result.AddBlankLine();
                referenceExpression = new CodeMethodReferenceExpression(
                    new CodeVariableReferenceExpression(rootVar.Key), "AddPart",
                    new CodeTypeReference(part.OpenXmlPart.GetType().Name));
                invokeExpression = new CodeMethodInvokeExpression(referenceExpression,
                                                                  new CodeVariableReferenceExpression(bpTemp.VariableName),
                                                                  new CodePrimitiveExpression(part.RelationshipId));
                result.Add(invokeExpression);
                result.AddBlankLine();
                return(result);
            }

            // Assign the appropriate variable name
            if (typeCounts.ContainsKey(partTypeFullName))
            {
                varName = String.Concat(varName, typeCounts[partTypeFullName]++);
            }
            else
            {
                typeCounts.Add(partTypeFullName, 1);
            }

            // Setup the blueprint
            bpTemp = new OpenXmlPartBluePrint(part.OpenXmlPart, varName);

            // Need to evaluate the current OpenXmlPart type first to make sure the
            // correct "Add" statement is used as not all Parts can be initialized
            // using the "AddNewPart" method

            // Check for image part methods
            if (customAddNewPartRequired)
            {
                referenceExpression = new CodeMethodReferenceExpression(
                    new CodeVariableReferenceExpression(rootVar.Key), addNewPartName);
            }
            else
            {
                // Setup the add new part statement for the current OpenXmlPart object
                referenceExpression = new CodeMethodReferenceExpression(
                    new CodeVariableReferenceExpression(rootVar.Key), "AddNewPart",
                    new CodeTypeReference(partTypeName));
            }

            // Create the invoke expression
            invokeExpression = new CodeMethodInvokeExpression(referenceExpression);

            // Add content type to invoke method for embeddedpackage and image parts.
            if (part.OpenXmlPart is EmbeddedPackagePart || customAddNewPartRequired)
            {
                invokeExpression.Parameters.Add(
                    new CodePrimitiveExpression(part.OpenXmlPart.ContentType));
            }
            else if (!customAddNewPartRequired)
            {
                invokeExpression.Parameters.Add(
                    new CodePrimitiveExpression(part.RelationshipId));
            }

            result.Add(new CodeVariableDeclarationStatement(partTypeName, varName, invokeExpression));

            // Because the custom AddNewPart methods don't consistently take in a string relId
            // as a parameter, the id needs to be assigned after it is created.
            if (customAddNewPartRequired)
            {
                methodReference = new CodeMethodReferenceExpression(
                    new CodeVariableReferenceExpression(rootVar.Key), "ChangeIdOfPart");
                result.Add(new CodeMethodInvokeExpression(methodReference,
                                                          new CodeVariableReferenceExpression(varName),
                                                          new CodePrimitiveExpression(part.RelationshipId)));
            }

            // Add the call to the method to populate the current OpenXmlPart object
            methodReference = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), bpTemp.MethodName);
            result.Add(new CodeMethodInvokeExpression(methodReference,
                                                      new CodeDirectionExpression(FieldDirection.Ref,
                                                                                  new CodeVariableReferenceExpression(varName))));

            // Add the appropriate code statements if the current part
            // contains any hyperlink relationships
            if (part.OpenXmlPart.HyperlinkRelationships.Count() > 0)
            {
                // Add a line break first for easier reading
                result.AddBlankLine();
                result.AddRange(
                    part.OpenXmlPart.HyperlinkRelationships.BuildHyperlinkRelationshipStatements(varName));
            }

            // Add the appropriate code statements if the current part
            // contains any non-hyperlink external relationships
            if (part.OpenXmlPart.ExternalRelationships.Count() > 0)
            {
                // Add a line break first for easier reading
                result.AddBlankLine();
                result.AddRange(
                    part.OpenXmlPart.ExternalRelationships.BuildExternalRelationshipStatements(varName));
            }

            // put a line break before going through the child parts
            result.AddBlankLine();

            // Add the current blueprint to the collection
            blueprints.Add(bpTemp);

            // Now check to see if there are any child parts for the current OpenXmlPart object.
            if (bpTemp.Part.Parts != null)
            {
                OpenXmlPartBluePrint childBluePrint;

                foreach (var p in bpTemp.Part.Parts)
                {
                    // If the current child object has already been created, simply add a reference to
                    // said object using the AddPart method.
                    if (blueprints.Contains(p.OpenXmlPart.Uri))
                    {
                        childBluePrint = blueprints[p.OpenXmlPart.Uri];

                        referenceExpression = new CodeMethodReferenceExpression(
                            new CodeVariableReferenceExpression(varName), "AddPart",
                            new CodeTypeReference(p.OpenXmlPart.GetType().Name));

                        invokeExpression = new CodeMethodInvokeExpression(referenceExpression,
                                                                          new CodeVariableReferenceExpression(childBluePrint.VariableName),
                                                                          new CodePrimitiveExpression(p.RelationshipId));

                        result.Add(invokeExpression);
                        continue;
                    }

                    // If this is a new part, call this method with the current part's details
                    result.AddRange(BuildEntryMethodCodeStatements(p, settings, typeCounts, namespaces, blueprints,
                                                                   new KeyValuePair <string, Type>(varName, partType)));
                }
            }

            return(result);
        }
Ejemplo n.º 3
0
        public static void SetContentOfContentControl(SdtElement contentControl, string content)
        {
            if (contentControl == null)
            {
                throw new ArgumentNullException("contentControl");
            }

            content = string.IsNullOrEmpty(content) ? string.Empty : content;
            var isCombobox = contentControl.SdtProperties.Descendants <SdtContentDropDownList>().FirstOrDefault() != null;
            var isImage    = contentControl.SdtProperties.Descendants <SdtContentPicture>().FirstOrDefault() != null;
            var prop       = contentControl.Elements <SdtProperties>().FirstOrDefault();

            if (isCombobox)
            {
                var openXmlCompositeElement = GetSdtContentOfContentControl(contentControl);
                var run = CreateRun(openXmlCompositeElement, content);
                SetSdtContentKeepingPermissionElements(openXmlCompositeElement, run);
            }

            if (isImage)
            {
                string  embed = null;
                Drawing dr    = contentControl.Descendants <Drawing>().FirstOrDefault();
                if (dr != null)
                {
                    DocumentFormat.OpenXml.Drawing.Blip blip = dr.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                    if (blip != null)
                    {
                        embed = blip.Embed;
                    }
                }

                if (embed != null)
                {
                    var        document = (Document)prop.Ancestors <Body>().FirstOrDefault().Parent;
                    IdPartPair idpp     = document.MainDocumentPart.Parts.Where(pa => pa.RelationshipId == embed).FirstOrDefault();
                    if (idpp != null)
                    {
                        ImagePart     ip = (ImagePart)idpp.OpenXmlPart;
                        DirectoryInfo di = new DirectoryInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
                        using (FileStream fileStream = File.Open(Path.Combine(di.Parent.FullName, content), FileMode.Open))
                        {
                            ip.FeedData(fileStream);
                        }
                    }
                }
            }
            else
            {
                var openXmlCompositeElement = GetSdtContentOfContentControl(contentControl);
                contentControl.SdtProperties.RemoveAllChildren <ShowingPlaceholder>();
                var runs = new List <Run>();

                if (IsContentControlMultiline(contentControl))
                {
                    var textSplitted = content.Split(Environment.NewLine.ToCharArray()).ToList();
                    var addBreak     = false;

                    foreach (var textSplit in textSplitted)
                    {
                        var run = CreateRun(openXmlCompositeElement, textSplit);

                        if (addBreak)
                        {
                            run.AppendChild(new Break());
                        }

                        if (!addBreak)
                        {
                            addBreak = true;
                        }

                        runs.Add(run);
                    }
                }
                else
                {
                    runs.Add(CreateRun(openXmlCompositeElement, content));
                }

                SdtContentCell aopenXmlCompositeElement = openXmlCompositeElement as SdtContentCell;
                if (aopenXmlCompositeElement != null)
                {
                    AddRunsToSdtContentCell(aopenXmlCompositeElement, runs);
                }
                else if (openXmlCompositeElement is SdtContentBlock)
                {
                    var para = CreateParagraph(openXmlCompositeElement, runs);
                    SetSdtContentKeepingPermissionElements(openXmlCompositeElement, para);
                }
                else
                {
                    SetSdtContentKeepingPermissionElements(openXmlCompositeElement, runs);
                }
            }
        }
Ejemplo n.º 4
0
        private static void ReplaceParagraphParts(OpenXmlElement element, WordprocessingDocument wordDocument)
        {
            //int i = 1;

            // Getting all Paragraph in Xml File

            Drawing  draw     = element.Descendants <Drawing>().FirstOrDefault();
            FileInfo fileInfo = new FileInfo("C:\\Users\\Gaurav Koli\\Downloads\\battlefield_bad_company_2_table_room_parquet-740403.jpg");
            string   embed    = null;

            DocumentFormat.OpenXml.Drawing.Blip blip = null;

            foreach (var paragraph in element.Descendants <Paragraph>())
            {
                //Getting blip Id to get Image Part
                SdtAlias sa = paragraph.Descendants <SdtAlias>().SingleOrDefault();
                if (sa != null && sa.Val == "crmndc_signatureurl")
                {
                    sa.Val = "Change Picture";
                    Console.WriteLine("Done");
                    Drawing dr = paragraph.Descendants <Drawing>().FirstOrDefault();
                    //9525 is EMU per pixel
                    Int64 finalCx = (600 * 9525);
                    Int64 finalCy = (300 * 9525);

                    //resize the image
                    dr.Inline.Extent.Cx = finalCx;
                    dr.Inline.Extent.Cy = finalCy;

                    dr.Inline.Graphic.GraphicData.GetFirstChild <DocumentFormat.OpenXml.Drawing.Pictures.Picture>().ShapeProperties.Transform2D.Extents.Cx = finalCx;
                    dr.Inline.Graphic.GraphicData.GetFirstChild <DocumentFormat.OpenXml.Drawing.Pictures.Picture>().ShapeProperties.Transform2D.Extents.Cy = finalCy;

                    if (dr != null)
                    {
                        blip = dr.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                        if (blip != null)
                        {
                            embed = blip.Embed;
                        }
                    }
                }

                //Getting Image part and change the Image

                if (embed != null)
                {
                    IdPartPair idpp = wordDocument.MainDocumentPart.Parts.Where(pa => pa.RelationshipId == embed).FirstOrDefault();
                    if (idpp != null)
                    {
                        ImagePart ip = (ImagePart)idpp.OpenXmlPart;
                        try
                        {
                            using (FileStream fileStream = fileInfo.OpenRead())
                            {
                                ip.FeedData(fileStream);
                                // fileStream.Close();
                            }
                            if (blip != null)
                            {
                                blip.Embed.Value = wordDocument.MainDocumentPart.GetIdOfPart(ip);
                            }
                            Console.WriteLine("done " + wordDocument.MainDocumentPart.GetIdOfPart(ip));
                            // Console.ReadKey();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.StackTrace);
                            Console.ReadKey();
                        }
                    }
                    embed = null;
                }

                //Changing the Templete Text
                var sdtContentText = paragraph.Descendants <Text>();

                if (sdtContentText != null)
                {
                    foreach (Text text in sdtContentText)
                    {
                        switch (text.Text)
                        {
                        case "<<crmndc_seller1_fullname>>":
                            text.Text = "Common" + i;
                            i++;
                            break;

                        case "Lysaker, ":
                            text.Text = "Common" + i;
                            i++;
                            break;

                        case "21.03.2016":
                            text.Text = "Common" + i;
                            i++;
                            break;

                        case "<<title>>":
                            text.Text = "Common" + i;
                            i++;
                            break;

                        case "<<crmndc_buyer1_fullname>>":
                            text.Text = "Common" + i;
                            i++;
                            break;

                        case "crmndc_insurancecompany_name":
                            text.Text = "Common" + i;
                            i++;
                            break;

                        case "<<":
                            text.Text = "";
                            break;

                        case ">>":
                            text.Text = "";
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
        }