Beispiel #1
0
        private string SavePicture(Image image)
        {
            ImageConverter ic = new ImageConverter();

            byte[] img = (byte[])ic.ConvertTo(image, typeof(byte[]));
            var    ii  = _drawings._package.AddImage(img);

            if (_drawings._hashes.ContainsKey(ii.Hash))
            {
                var relID = _drawings._hashes[ii.Hash];
                var rel   = _drawings.Part.GetRelationship(relID);
                UriPic = PackUriHelper.ResolvePartUri(rel.SourceUri, rel.TargetUri);
                return(relID);
            }
            else
            {
                UriPic = ii.Uri;
            }

            //Set the Image and save it to the package.
            RelPic = _drawings.Part.CreateRelationship(PackUriHelper.GetRelativeUri(_drawings.UriDrawing, UriPic), TargetMode.Internal, ExcelPackage.schemaRelationships + "/image");

            //AddNewPicture(img, picRelation.Id);
            _drawings._hashes.Add(ii.Hash, RelPic.Id);
            ImageHash = ii.Hash;

            return(RelPic.Id);
        }
Beispiel #2
0
        internal ExcelPicture(ExcelDrawings drawings, XmlNode node) :
            base(drawings, node, "xdr:pic/xdr:nvPicPr/xdr:cNvPr/@name")
        {
            XmlNode picNode = node.SelectSingleNode("xdr:pic/xdr:blipFill/a:blip", drawings.NameSpaceManager);

            if (picNode != null)
            {
                RelPic = drawings.Part.GetRelationship(picNode.Attributes["r:embed"].Value);
                UriPic = PackUriHelper.ResolvePartUri(drawings.UriDrawing, RelPic.TargetUri);

                Part = drawings.Part.Package.GetPart(UriPic);
                FileInfo f = new FileInfo(UriPic.OriginalString);
                ContentType = GetContentType(f.Extension);
                _image      = Image.FromStream(Part.GetStream());
                ImageConverter ic  = new ImageConverter();
                var            iby = (byte[])ic.ConvertTo(_image, typeof(byte[]));
                var            ii  = _drawings._package.LoadImage(iby, UriPic, Part);
                ImageHash = ii.Hash;

                string relID = GetXmlNodeString("xdr:pic/xdr:nvPicPr/xdr:cNvPr/a:hlinkClick/@r:id");
                if (!string.IsNullOrEmpty(relID))
                {
                    HypRel = drawings.Part.GetRelationship(relID);
                    if (HypRel.TargetUri.IsAbsoluteUri)
                    {
                        _hyperlink = new ExcelHyperLink(HypRel.TargetUri.AbsoluteUri);
                    }
                    else
                    {
                        _hyperlink = new ExcelHyperLink(HypRel.TargetUri.OriginalString, UriKind.Relative);
                    }
                    ((ExcelHyperLink)_hyperlink).ToolTip = GetXmlNodeString("xdr:pic/xdr:nvPicPr/xdr:cNvPr/a:hlinkClick/@tooltip");
                }
            }
        }
Beispiel #3
0
        public static bool VytvoritCustomUI(string souborDocx, string customUiXml, bool zalohovat)
        {
            bool uspech = false;

            ZalohovatDokument(souborDocx, zalohovat);

            string customUiRelationshipType = ZjistiVerziCustomUi(customUiXml);

            if (customUiRelationshipType == null)
            {
                return(uspech);
            }

            string customUiXmlUri = "/customUI/customUI.xml";
            string CustomUiId     = "rCustomUiId";

            if (customUiRelationshipType == RelCustomUiW14RelationshipType)
            {
                customUiXmlUri = "/customUI/customUI2010.xml";
                CustomUiId     = "rCustomUi2010Id";
            }

            using (Package wdPackage = Package.Open(souborDocx, FileMode.Open, FileAccess.ReadWrite))
            {
                PackageRelationship docPackageRelationship = wdPackage.GetRelationshipsByType(customUiRelationshipType).FirstOrDefault();
                Uri documentUri = null;
                if (docPackageRelationship == null)
                {
                    documentUri = PackUriHelper.CreatePartUri(new Uri(customUiXmlUri, UriKind.Relative));
                    wdPackage.CreatePart(documentUri, "application/xml");
                    docPackageRelationship = wdPackage.CreateRelationship(documentUri, TargetMode.Internal, customUiRelationshipType, CustomUiId);
                }

                if (docPackageRelationship != null)
                {
                    if (documentUri == null)
                    {
                        documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), docPackageRelationship.TargetUri);
                    }

                    PackagePart documentPart = wdPackage.GetPart(documentUri);
                    string      customXml    = "<customUI xmlns=\"http://schemas.microsoft.com/office/2006/01/customui\"><ribbon><tabs><tab id=\"tbKarta\" label=\"Karta\"></tab></tabs></ribbon></customUI>";
                    if (customUiXml != null)
                    {
                        using (StreamReader streamReader = new StreamReader(customUiXml))
                        {
                            customXml = streamReader.ReadToEnd();
                        }
                    }

                    using (StreamWriter streamWriter = new StreamWriter(documentPart.GetStream(FileMode.Create)))
                    {
                        streamWriter.Write(customXml);
                        uspech = true;
                    }
                }
            }

            return(uspech);
        }
Beispiel #4
0
        public void ResolvePartUri3()
        {
            Uri src  = new Uri("/1/2/3/4", UriKind.Relative);
            Uri dest = new Uri("http://www.example.com", UriKind.Absolute);

            PackUriHelper.ResolvePartUri(src, dest);
        }
Beispiel #5
0
        internal ExcelPivotCacheDefinition(XmlNamespaceManager ns, ExcelPivotTable pivotTable) :
            base(ns, null)
        {
            foreach (var r in pivotTable.Part.GetRelationshipsByType(ExcelPackage.schemaRelationships + "/pivotCacheDefinition"))
            {
                Relationship = r;
            }
            CacheDefinitionUri = PackUriHelper.ResolvePartUri(Relationship.SourceUri, Relationship.TargetUri);

            var pck = pivotTable.WorkSheet._package.Package;

            Part = pck.GetPart(CacheDefinitionUri);
            CacheDefinitionXml = new XmlDocument();
            LoadXmlSafe(CacheDefinitionXml, Part.GetStream());

            TopNode    = CacheDefinitionXml.DocumentElement;
            PivotTable = pivotTable;
            if (CacheSource == eSourceType.Worksheet)
            {
                var worksheetName = GetXmlNodeString(_sourceWorksheetPath);
                if (pivotTable.WorkSheet.Workbook.Worksheets.Any(t => t.Name == worksheetName))
                {
                    _sourceRange = pivotTable.WorkSheet.Workbook.Worksheets[worksheetName].Cells[GetXmlNodeString(_sourceAddressPath)];
                }
            }
        }
Beispiel #6
0
        // Return true if an open XML document is enforcing read-only
        private static bool IsOpenXMLReadOnlyEnforced(string filename)
        {
            // Read an OpenXML type document
            using (Package package = Package.Open(path: filename, packageMode: FileMode.Open, packageAccess: FileAccess.Read))
            {
                if (null == package)
                {
                    return(false);
                }
                try
                {
                    // Document security is set in the extended properties
                    // https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2010/cc845474(v%3doffice.14)
                    string extendedType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties";
                    PackageRelationshipCollection extendedProps = package.GetRelationshipsByType(extendedType);
                    if (null != extendedProps)
                    {
                        IEnumerator extendedPropsList = extendedProps.GetEnumerator();
                        if (extendedPropsList.MoveNext())
                        {
                            Uri         extendedPropsUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), ((PackageRelationship)extendedPropsList.Current).TargetUri);
                            PackagePart props            = package.GetPart(extendedPropsUri);
                            if (null != props)
                            {
                                // Read the internal docProps/app.xml XML file
                                XDocument xmlDoc     = XDocument.Load(props.GetStream());
                                XElement  securityEl = xmlDoc.Root.Element(XName.Get("DocSecurity", xmlDoc.Root.GetDefaultNamespace().NamespaceName));
                                if (null != securityEl)
                                {
                                    if (!String.IsNullOrWhiteSpace(securityEl.Value))
                                    {
                                        // See https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2010/cc840043%28v%3doffice.14%29
                                        return((Int16.Parse(securityEl.Value) & 4) == 4);
                                    }
                                }

                                package.Close();
                                // PowerPoint doesn't use DocSecurity (*sigh*) so need another check
                                XElement appEl = xmlDoc.Root.Element(XName.Get("Application", xmlDoc.Root.GetDefaultNamespace().NamespaceName));
                                if (null != appEl)
                                {
                                    if (!String.IsNullOrWhiteSpace(appEl.Value) &&
                                        appEl.Value.IndexOf("PowerPoint", StringComparison.InvariantCultureIgnoreCase) >= 0)
                                    {
                                        PresentationDocument presentationDocument = PresentationDocument.Open(path: filename, isEditable: false);
                                        if (null != presentationDocument &&
                                            presentationDocument.PresentationPart.Presentation.ModificationVerifier != null)
                                        {
                                            return(true);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception) { }
                return(false);
            }
        }
Beispiel #7
0
        private static Type GetDocumentType(byte[] bytes)
        {
            using (MemoryStream stream = new MemoryStream(bytes))
                using (Package package = Package.Open(stream, FileMode.Open))
                {
                    PackageRelationship relationship = package.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument").FirstOrDefault();
                    if (relationship != null)
                    {
                        PackagePart part = package.GetPart(PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri));
                        switch (part.ContentType)
                        {
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml":
                            return(typeof(WordprocessingDocument));

                        case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml":
                            return(typeof(SpreadsheetDocument));

                        case "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml":
                        case "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml":
                            return(typeof(PresentationDocument));
                        }
                        return(typeof(Package));
                    }
                    return(null);
                }
        }
Beispiel #8
0
        /// <summary>
        /// Add a new pivottable
        /// </summary>
        /// <param name="sheet">The worksheet</param>
        /// <param name="address">the address of the pivottable</param>
        /// <param name="sourceAddress">The address of the Source data</param>
        /// <param name="name"></param>
        /// <param name="tblId"></param>
        internal ExcelPivotTable(ExcelWorksheet sheet, ExcelAddressBase address, ExcelRangeBase sourceAddress, string name, int tblId) :
            base(sheet.NameSpaceManager)
        {
            WorkSheet = sheet;
            Address   = address;
            var pck = sheet._package.Package;

            PivotTableXml = new XmlDocument();
            LoadXmlSafe(PivotTableXml, GetStartXml(name, tblId, address, sourceAddress));
            TopNode       = PivotTableXml.DocumentElement;
            PivotTableUri = GetNewUri(pck, "/xl/pivotTables/pivotTable{0}.xml", tblId);
            init();

            Part = pck.CreatePart(PivotTableUri, ExcelPackage.schemaPivotTable);
            PivotTableXml.Save(Part.GetStream());

            //Worksheet-Pivottable relationship
            Relationship = sheet.Part.CreateRelationship(PackUriHelper.ResolvePartUri(sheet.WorksheetUri, PivotTableUri), TargetMode.Internal, ExcelPackage.schemaRelationships + "/pivotTable");

            _cacheDefinition = new ExcelPivotCacheDefinition(sheet.NameSpaceManager, this, sourceAddress, tblId);
            _cacheDefinition.Relationship = Part.CreateRelationship(PackUriHelper.ResolvePartUri(PivotTableUri, _cacheDefinition.CacheDefinitionUri), TargetMode.Internal, ExcelPackage.schemaRelationships + "/pivotCacheDefinition");

            sheet.Workbook.AddPivotTable(CacheID.ToString(), _cacheDefinition.CacheDefinitionUri);

            LoadFields();

            using (var r = sheet.Cells[address.Address])
            {
                r.Clear();
            }
        }
        /// <summary>
        /// Converts an OpenXml package in OPC format to an <see cref="XDocument"/>
        /// in Flat OPC format.
        /// </summary>
        /// <param name="instruction">The processing instruction.</param>
        /// <returns>The OpenXml package in Flat OPC format.</returns>
        protected XDocument ToFlatOpcDocument(XProcessingInstruction instruction)
        {
            // Save the contents of all parts and relationships that are contained
            // in the OpenXml package to make sure we convert a consistent state.
            // This will also invoke ThrowIfObjectDisposed(), so we don't need
            // to call it here.
            Save();

            // Identify all AlternativeFormatInputParts (AltChunk parts).
            // This is necessary because AltChunk parts must be treated as binary
            // parts regardless of the actual content type, which might even be
            // XML-related such as application/xhtml+xml.
            var altChunkPartUris = new HashSet <Uri>(
                Package.GetParts()
                .Where(part => part.ContentType != RelationshipContentType)
                .SelectMany(part => part.GetRelationshipsByType(AltChunkRelationshipType))
                .Select(pr => PackUriHelper.ResolvePartUri(pr.SourceUri, pr.TargetUri)));

            // Create an XML document with a standalone declaration, processing
            // instruction (if not null), and a package root element with a
            // namespace declaration and one child element for each part.
            return(new XDocument(
                       new XDeclaration("1.0", "UTF-8", "yes"),
                       instruction,
                       new XElement(
                           Pkg + "package",
                           new XAttribute(XNamespace.Xmlns + "pkg", Pkg.ToString()),
                           Package.GetParts().Select(part => GetContentsAsXml(part, altChunkPartUris)))));
        }
Beispiel #10
0
        void ExtractLayouts(Package package, PackageDefinition manifest, string workingDirectory)
        {
            var localContentDirectory = Path.Combine(workingDirectory, AzureCloudServiceConventions.PackageFolders.LocalContent);

            fileSystem.EnsureDirectoryExists(localContentDirectory);

            foreach (var layout in manifest.Layouts)
            {
                if (!layout.Name.StartsWith(AzureCloudServiceConventions.RoleLayoutPrefix))
                {
                    continue;
                }

                var layoutDirectory = Path.Combine(localContentDirectory, layout.Name.Substring(AzureCloudServiceConventions.RoleLayoutPrefix.Length));
                fileSystem.EnsureDirectoryExists(layoutDirectory);

                foreach (var fileDefinition in layout.FileDefinitions)
                {
                    var contentDefinition =
                        manifest.GetContentDefinition(fileDefinition.Description.DataContentReference);

                    var destinationFileName = Path.Combine(layoutDirectory, fileDefinition.FilePath.TrimStart('\\'));
                    ExtractPart(
                        package.GetPart(PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative),
                                                                     contentDefinition.Description.DataStorePath)),
                        destinationFileName);
                }
            }
        }
Beispiel #11
0
        public static PackagePart GetDocumentPart(Package package)
        {
            PackageRelationship relationship = package.GetRelationshipsByType(OfficeDocumentRelType).FirstOrDefault();
            Uri docUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);

            return(package.GetPart(docUri));
        }
        public Dictionary <string, BitmapImage> GetImages()
        {
            if (Part == null)
            {
                throw new InvalidOperationException($"Part was already removed");
            }

            var imageCollection = new Dictionary <string, BitmapImage>();

            foreach (var relationship in Part.GetRelationshipsByType(OfficeDocument.ImagePartRelType))
            {
                var customImageUri = PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri);
                if (!Part.Package.PartExists(customImageUri))
                {
                    continue;
                }

                var imagePart = Part.Package.GetPart(customImageUri);

                var imageStream = imagePart.GetStream(FileMode.Open, FileAccess.Read);

                var image = new BitmapImage();
                image.BeginInit();
                image.StreamSource = imageStream;
                image.CacheOption  = BitmapCacheOption.OnLoad;
                image.EndInit();

                imageCollection.Add(relationship.Id, image);

                imageStream.Close();
            }

            return(imageCollection);
        }
        private string?AddImageHelper(string fileName, string imageId, Func <string?, string?, bool>?alreadyExistingAction = null)
        {
            if (Part == null)
            {
                throw new InvalidOperationException($"Part was already removed");
            }

            if (fileName == null)
            {
                throw new ArgumentNullException(nameof(fileName));
            }

            Debug.Assert(File.Exists(fileName), fileName + " does not exist.");
            if (!File.Exists(fileName))
            {
                return(null);
            }

            var extension = Path.GetExtension(fileName);

            // Check for duplicates and correct ID if necessary
            var originalId = imageId;

            imageId = FindFirstAvailableImageId(Part, imageId);

            if (imageId != originalId && !(alreadyExistingAction?.Invoke(originalId, imageId) ?? true))
            {
                return(null);
            }

            // Now do the same for the Uri (which does need to coincide with the ID)
            var imageUri = FindFirstAvailableImageUri(Part, originalId, extension);

            var imageRel = Part.CreateRelationship(imageUri, TargetMode.Internal, OfficeDocument.ImagePartRelType, imageId);

            var imagePart = Part.Package.CreatePart(
                PackUriHelper.ResolvePartUri(imageRel.SourceUri, imageRel.TargetUri),
                MapImageContentType(Path.GetExtension(fileName)));

            if (imagePart == null)
            {
                Debug.Print("Fail to create image part.");
                return(null);
            }

            using var br = new BinaryReader(File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
            using var bw = new BinaryWriter(imagePart.GetStream(FileMode.Create, FileAccess.Write));

            var buffer = new byte[1024];
            int byteCount;

            while ((byteCount = br.Read(buffer, 0, buffer.Length)) > 0)
            {
                bw.Write(buffer, 0, byteCount);
            }

            bw.Flush();

            return(imageRel.Id);
        }
        public void RemoveImage(string imageId)
        {
            if (Part == null)
            {
                throw new InvalidOperationException("Part was already removed");
            }

            if (imageId == null)
            {
                throw new ArgumentNullException(nameof(imageId));
            }

            if (imageId.Length == 0)
            {
                return;
            }

            if (!Part.RelationshipExists(imageId))
            {
                return;
            }

            var imageRel = Part.GetRelationship(imageId);

            var imageUri = PackUriHelper.ResolvePartUri(imageRel.SourceUri, imageRel.TargetUri);

            if (Part.Package.PartExists(imageUri))
            {
                Part.Package.DeletePart(imageUri);
            }

            Part.DeleteRelationship(imageId);
        }
Beispiel #15
0
        public static void PrekopirovatPanelNastroju(string strZdrojovySoubor, string strCilovySoubor)
        {
            using (Package wdPackage = Package.Open(strCilovySoubor, FileMode.Open, FileAccess.ReadWrite))
            {
                PackageRelationship docPackageRelationship = wdPackage.GetRelationshipsByType(RelDocumentRelationshipType).FirstOrDefault();
                if (docPackageRelationship != null)
                {
                    Uri         documentUri  = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), docPackageRelationship.TargetUri);
                    PackagePart documentPart = wdPackage.GetPart(documentUri);

                    //  Find the styles part. There will only be one.
                    PackageRelationship styleRelation = documentPart.GetRelationshipsByType(RelCustomization).FirstOrDefault();
                    if (styleRelation != null)
                    {
                        Uri         styleUri  = PackUriHelper.ResolvePartUri(documentUri, styleRelation.TargetUri);
                        PackagePart stylePart = wdPackage.GetPart(styleUri);
                        using (StreamReader streamReader = new StreamReader(strZdrojovySoubor))
                            using (StreamWriter streamWriter = new StreamWriter(stylePart.GetStream(FileMode.Create)))
                            {
                                streamWriter.Write(streamReader.ReadToEnd());
                            }
                    }
                }
            }
        }
        /// <summary>
        /// Method that makes two lists, parts to want Sign and indicate relationships to sign
        /// </summary>
        /// <param name="relationship">PackageRelationship</param>
        /// <param name="partsToSign"> Package Parts that you want to sign</param>
        /// <param name="relationshipsToSign">PacakgeRelationshipSelector objects which indicate relationships to sign</param>
        private void AddSignableItems(
            PackageRelationship relationship,
            List <Uri> partsToSign,
            List <PackageRelationshipSelector> relationshipsToSign)
        {
            PackageRelationshipSelector selector =
                new PackageRelationshipSelector(
                    relationship.SourceUri,
                    PackageRelationshipSelectorType.Id,
                    relationship.Id);

            relationshipsToSign.Add(selector);
            if (relationship.TargetMode == TargetMode.Internal)
            {
                PackagePart part = relationship.Package.GetPart(
                    PackUriHelper.ResolvePartUri(
                        relationship.SourceUri, relationship.TargetUri));
                if (partsToSign.Contains(part.Uri) == false)
                {
                    partsToSign.Add(part.Uri);
                    foreach (PackageRelationship childRelationship in
                             part.GetRelationships())
                    {
                        AddSignableItems(childRelationship,
                                         partsToSign, relationshipsToSign);
                    }
                }
            }
        }
Beispiel #17
0
        /// <summary>
        /// Nahradí text dokumentu novým obsahem.
        /// </summary>
        /// <param name="souborDocx">Dokument DOCX, jehož obsah se má nahrazovat.</param>
        /// <param name="dokumentXml">Text dokumentu ve formátu Xml.</param>
        /// <param name="zalohovat">Zda se má dokument před provedením změn zálohovat.</param>
        /// <returns></returns>
        public static bool NahraditDokument(string souborDocx, string dokumentXml, bool zalohovat)
        {
            bool blnNahrazeno = false;

            ZalohovatDokument(souborDocx, zalohovat);

            using (Package wdPackage = Package.Open(souborDocx, FileMode.Open, FileAccess.ReadWrite))
            {
                PackageRelationship docPackageRelationship = wdPackage.GetRelationshipsByType(RelDocumentRelationshipType).FirstOrDefault();
                if (docPackageRelationship != null)
                {
                    Uri         documentUri  = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), docPackageRelationship.TargetUri);
                    PackagePart documentPart = wdPackage.GetPart(documentUri);

                    using (StreamReader streamReader = new StreamReader(dokumentXml))
                        using (StreamWriter streamWriter = new StreamWriter(documentPart.GetStream(FileMode.Create)))
                        {
                            streamWriter.Write(streamReader.ReadToEnd());
                        }

                    blnNahrazeno = true;
                }
            }
            return(blnNahrazeno);
        }
Beispiel #18
0
        internal void GetExternalReferences()
        {
            XmlNodeList nl = WorkbookXml.SelectNodes("//d:externalReferences/d:externalReference", NameSpaceManager);

            if (nl != null)
            {
                foreach (XmlElement elem in nl)
                {
                    string rID = elem.GetAttribute("r:id");
                    PackageRelationship rel = Part.GetRelationship(rID);
                    var         part        = _package.Package.GetPart(PackUriHelper.ResolvePartUri(rel.SourceUri, rel.TargetUri));
                    XmlDocument xmlExtRef   = new XmlDocument();
                    LoadXmlSafe(xmlExtRef, part.GetStream());

                    XmlElement book = xmlExtRef.SelectSingleNode("//d:externalBook", NameSpaceManager) as XmlElement;
                    if (book != null)
                    {
                        string rId_ExtRef = book.GetAttribute("r:id");
                        var    rel_extRef = part.GetRelationship(rId_ExtRef);
                        if (rel_extRef != null)
                        {
                            _externalReferences.Add(rel_extRef.TargetUri.OriginalString);
                        }
                    }
                }
            }
        }
Beispiel #19
0
        public static bool NahraditDefiniciStylu(string strDocx, string strStylyXml)
        {
            bool blnNahrazeno = false;

            using (Package wdPackage = Package.Open(strDocx, FileMode.Open, FileAccess.ReadWrite))
            {
                PackageRelationship docPackageRelationship = wdPackage.GetRelationshipsByType(RelDocumentRelationshipType).FirstOrDefault();
                if (docPackageRelationship != null)
                {
                    Uri         documentUri  = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), docPackageRelationship.TargetUri);
                    PackagePart documentPart = wdPackage.GetPart(documentUri);

                    //  Find the styles part. There will only be one.
                    PackageRelationship styleRelation = documentPart.GetRelationshipsByType(RelStylesRelationshipType).FirstOrDefault();
                    if (styleRelation != null)
                    {
                        Uri         styleUri  = PackUriHelper.ResolvePartUri(documentUri, styleRelation.TargetUri);
                        PackagePart stylePart = wdPackage.GetPart(styleUri);
                        using (StreamReader streamReader = new StreamReader(strStylyXml))
                            using (StreamWriter streamWriter = new StreamWriter(stylePart.GetStream(FileMode.Create)))
                            {
                                streamWriter.Write(streamReader.ReadToEnd());
                            }
                        blnNahrazeno = true;
                    }
                }
            }
            return(blnNahrazeno);
        }
Beispiel #20
0
        internal ExcelPivotCacheDefinition(XmlNamespaceManager ns, ExcelPivotTable pivotTable, ExcelRangeBase sourceAddress, int tblId) :
            base(ns, null)
        {
            PivotTable = pivotTable;

            var pck = pivotTable.WorkSheet._package.Package;

            //CacheDefinition
            CacheDefinitionXml = new XmlDocument();
            LoadXmlSafe(CacheDefinitionXml, GetStartXml(sourceAddress));
            CacheDefinitionUri = GetNewUri(pck, "/xl/pivotCache/pivotCacheDefinition{0}.xml", tblId);
            Part    = pck.CreatePart(CacheDefinitionUri, ExcelPackage.schemaPivotCacheDefinition);
            TopNode = CacheDefinitionXml.DocumentElement;

            //CacheRecord. Create an empty one.
            CacheRecordUri = GetNewUri(pck, "/xl/pivotCache/pivotCacheRecords{0}.xml", tblId);
            var cacheRecord = new XmlDocument();

            cacheRecord.LoadXml("<pivotCacheRecords xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" count=\"0\" />");
            var recPart = pck.CreatePart(CacheRecordUri, ExcelPackage.schemaPivotCacheRecords);

            cacheRecord.Save(recPart.GetStream());

            RecordRelationship   = Part.CreateRelationship(PackUriHelper.ResolvePartUri(CacheDefinitionUri, CacheRecordUri), TargetMode.Internal, ExcelPackage.schemaRelationships + "/pivotCacheRecords");
            RecordRelationshipID = RecordRelationship.Id;

            CacheDefinitionXml.Save(Part.GetStream());
        }
Beispiel #21
0
        internal ExcelWorksheets(ExcelPackage pck, XmlNamespaceManager nsm, XmlNode topNode) :
            base(nsm, topNode)
        {
            _pck = pck;
            _namespaceManager = nsm;
            _worksheets       = new Dictionary <int, ExcelWorksheet>();
            int positionID = 1;

            foreach (XmlNode sheetNode in topNode.ChildNodes)
            {
                string name = sheetNode.Attributes["name"].Value;
                //Get the relationship id
                string relId   = sheetNode.Attributes["r:id"].Value;
                int    sheetID = Convert.ToInt32(sheetNode.Attributes["sheetId"].Value);

                //Hidden property
                eWorkSheetHidden hidden = eWorkSheetHidden.Visible;
                XmlNode          attr   = sheetNode.Attributes["state"];
                if (attr != null)
                {
                    hidden = TranslateHidden(attr.Value);
                }

                PackageRelationship sheetRelation = pck.Workbook.Part.GetRelationship(relId);
                Uri uriWorksheet = PackUriHelper.ResolvePartUri(pck.Workbook.WorkbookUri, sheetRelation.TargetUri);

                //add the worksheet
                _worksheets.Add(positionID, new ExcelWorksheet(_namespaceManager, _pck, relId, uriWorksheet, name, sheetID, positionID, hidden));
                positionID++;
            }
        }
Beispiel #22
0
        public static CopyBuffer ExtractCopyBufferFromClipboardStream(Stream clipboardStream)
        {
            CopyBuffer result;

            using (Package package = Package.Open(clipboardStream, FileMode.Open, FileAccess.Read))
            {
                result = new CopyBuffer();
                foreach (PackageRelationship packageRelationship in package.GetRelationshipsByType("http://schemas.microsoft.com/cfxaml/2006/06/relationships/metadata/core-properties"))
                {
                    Uri         partUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), packageRelationship.TargetUri);
                    PackagePart part    = package.GetPart(partUri);
                    Container.ParseCorePropertyPart(result, part);
                }
                foreach (PackageRelationship packageRelationship in package.GetRelationshipsByType("http://schemas.microsoft.com/cfxaml/2006/06/selected-item"))
                {
                    Uri      partUri     = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), packageRelationship.TargetUri);
                    CopyItem itemToPaste = (CopyItem) new MemoryCopyItem(Container.GetBytes(package.GetPart(partUri)));
                    result.AddSelectedItem(itemToPaste);
                }
                foreach (PackageRelationship packageRelationship1 in package.GetRelationshipsByType("http://schemas.microsoft.com/cfxaml/2006/06/referenced-item"))
                {
                    Uri         partUri1 = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), packageRelationship1.TargetUri);
                    PackagePart part     = package.GetPart(partUri1);
                    CopyItem    copyItem = (CopyItem) new MemoryCopyItem(Container.GetBytes(part));
                    result.AddReferencedItem(copyItem);
                    foreach (PackageRelationship packageRelationship2 in part.GetRelationshipsByType("http://schemas.microsoft.com/cfxaml/2006/06/item-attributes"))
                    {
                        Uri partUri2 = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), packageRelationship2.TargetUri);
                        Container.ReadAttributes(package.GetPart(partUri2), copyItem);
                    }
                }
            }
            return(result);
        }
Beispiel #23
0
        //Create Oid from a bytearray
        //private string ReadHash(byte[] content)
        //{
        //    StringBuilder builder = new StringBuilder();
        //    int offset = 0x6;
        //    if (0 < (content.Length))
        //    {
        //        byte num = content[offset];
        //        byte num2 = (byte)(num / 40);
        //        builder.Append(num2.ToString(null, null));
        //        builder.Append(".");
        //        num2 = (byte)(num % 40);
        //        builder.Append(num2.ToString(null, null));
        //        ulong num3 = 0L;
        //        for (int i = offset + 1; i < content.Length; i++)
        //        {
        //            num2 = content[i];
        //            num3 = (ulong)(ulong)(num3 << 7) + ((byte)(num2 & 0x7f));
        //            if ((num2 & 0x80) == 0)
        //            {
        //                builder.Append(".");
        //                builder.Append(num3.ToString(null, null));
        //                num3 = 0L;
        //            }
        //            //1.2.840.113549.2.5
        //        }
        //    }


        //    string oId = builder.ToString();

        //    return oId;
        //}
        internal void Save(ExcelVbaProject proj)
        {
            if (Certificate == null || Certificate.HasPrivateKey == false)    //No signature. Remove any Signature part
            {
                if (Part != null)
                {
                    foreach (var r in Part.GetRelationships())
                    {
                        Part.DeleteRelationship(r.Id);
                    }
                    Part.Package.DeletePart(Part.Uri);
                }
                return;
            }
            var ms = new MemoryStream();
            var bw = new BinaryWriter(ms);

            byte[] certStore = GetCertStore();

            byte[] cert = SignProject(proj);
            bw.Write((uint)cert.Length);
            bw.Write((uint)44);                                        //?? 36 ref inside cert ??
            bw.Write((uint)certStore.Length);                          //cbSigningCertStore
            bw.Write((uint)(cert.Length + 44));                        //certStoreOffset
            bw.Write((uint)0);                                         //cbProjectName
            bw.Write((uint)(cert.Length + certStore.Length + 44));     //projectNameOffset
            bw.Write((uint)0);                                         //fTimestamp
            bw.Write((uint)0);                                         //cbTimestampUrl
            bw.Write((uint)(cert.Length + certStore.Length + 44 + 2)); //timestampUrlOffset
            bw.Write(cert);
            bw.Write(certStore);
            bw.Write((ushort)0); //rgchProjectNameBuffer
            bw.Write((ushort)0); //rgchTimestampBuffer
            bw.Write((ushort)0);
            bw.Flush();

            var rel = proj.Part.GetRelationshipsByType(schemaRelVbaSignature).FirstOrDefault();

            if (Part == null)
            {
                if (rel != null)
                {
                    Uri  = rel.TargetUri;
                    Part = proj._pck.GetPart(rel.TargetUri);
                }
                else
                {
                    Uri  = new Uri("/xl/vbaProjectSignature.bin", UriKind.Relative);
                    Part = proj._pck.CreatePart(Uri, ExcelPackage.schemaVBASignature);
                }
            }
            if (rel == null)
            {
                proj.Part.CreateRelationship(PackUriHelper.ResolvePartUri(proj.Uri, Uri), TargetMode.Internal, schemaRelVbaSignature);
            }
            var b = ms.ToArray();

            Part.GetStream(FileMode.Create).Write(b, 0, b.Length);
        }
Beispiel #24
0
        public void ResolvePartUri()
        {
            Uri src  = new Uri("/1/2/3/4", UriKind.Relative);
            Uri dest = new Uri("/MyFile", UriKind.Relative);

            // Can't be empty url
            Assert.AreEqual(new Uri(""), PackUriHelper.ResolvePartUri(src, dest), "#1");
        }
Beispiel #25
0
        }// end:main()

        //  ----------------------- ExtractPackageParts -----------------------
        /// <summary>
        ///   Extracts content and resource parts from a given Package
        ///   zip file to a specified target directory.</summary>
        /// <param name="packagePath">
        ///   The relative path and filename of the Package zip file.</param>
        /// <param name="targetDirectory">
        ///   The relative path from the current directory to the targer folder.
        /// </param>
        private static void ExtractPackageParts(
            string packagePath, string targetDirectory)
        {
            // Create a new Target directory.  If the Target directory
            // exists, first delete it and then create a new empty one.
            DirectoryInfo directoryInfo = new DirectoryInfo(targetDirectory);

            if (directoryInfo.Exists)
            {
                directoryInfo.Delete(true);
            }
            directoryInfo.Create();

            //<SnippetPackageReadUsing>
            // Open the Package.
            // ('using' statement insures that 'package' is
            //  closed and disposed when it goes out of scope.)
            using (Package package =
                       Package.Open(packagePath, FileMode.Open, FileAccess.Read))
            {
                PackagePart documentPart = null;
                PackagePart resourcePart = null;

                // Get the Package Relationships and look for
                //   the Document part based on the RelationshipType
                Uri uriDocumentTarget = null;
                foreach (PackageRelationship relationship in
                         package.GetRelationshipsByType(PackageRelationshipType))
                {
                    // Resolve the Relationship Target Uri
                    //   so the Document Part can be retrieved.
                    uriDocumentTarget = PackUriHelper.ResolvePartUri(
                        new Uri("/", UriKind.Relative), relationship.TargetUri);

                    // Open the Document Part, write the contents to a file.
                    documentPart = package.GetPart(uriDocumentTarget);
                    ExtractPart(documentPart, targetDirectory);
                }

                // Get the Document part's Relationships,
                //   and look for required resources.
                Uri uriResourceTarget = null;
                foreach (PackageRelationship relationship in
                         documentPart.GetRelationshipsByType(
                             ResourceRelationshipType))
                {
                    // Resolve the Relationship Target Uri
                    //   so the Resource Part can be retrieved.
                    uriResourceTarget = PackUriHelper.ResolvePartUri(
                        documentPart.Uri, relationship.TargetUri);

                    // Open the Resource Part and write the contents to a file.
                    resourcePart = package.GetPart(uriResourceTarget);
                    ExtractPart(resourcePart, targetDirectory);
                }
            } // end:using(Package package) - Close & dispose package.
             //</SnippetPackageReadUsing>
        }     // end:ExtractPackageParts()
 public Uri GetUniquePartUri(string contentType, Uri parentUri, Uri targetUri)
 {
     return(GetUniquePartUri(
                contentType,
                PackUriHelper.ResolvePartUri(parentUri, targetUri),
                ".",
                Path.GetFileNameWithoutExtension(targetUri.OriginalString),
                Path.GetExtension(targetUri.OriginalString)));
 }
Beispiel #27
0
        void IPersistable.Load(ExcelLoadContext context)
        {
            PackageRelationship drawingsRelation = context.Package.GetPart(this._WorkSheet.SheetUri).GetRelationship(this.RelationshipID);

            this.DrawingUri = PackUriHelper.ResolvePartUri(drawingsRelation.SourceUri, drawingsRelation.TargetUri);
            XElement drawingsElement = context.Package.GetXElementFromUri(this.DrawingUri);

            context.Reader.ReadWrokSheetDrawings(this, drawingsElement, context);
        }
Beispiel #28
0
 void ExtractContents(Package package, PackageDefinition manifest, string contentNamePrefix, string workingDirectory)
 {
     foreach (var namedStreamsContent in manifest.Contents.Where(x => x.Name.StartsWith(contentNamePrefix)))
     {
         var destinationFileName = Path.Combine(workingDirectory, ConvertToWindowsPath(namedStreamsContent.Description.DataStorePath.ToString()).TrimStart('\\'));
         ExtractPart(package.GetPart(PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), namedStreamsContent.Description.DataStorePath)),
                     destinationFileName);
     }
 }
Beispiel #29
0
        /// <summary>
        /// Extract a container Zip. NOTE: container must be created as Open Packaging Conventions (OPC) specification
        /// </summary>
        /// <param name="folderName">The folder to extract the package to</param>
        /// <param name="compressedFileName">The package file</param>
        /// <param name="overrideExisting">override existing files</param>
        /// <param name="removeDescFile">Delete [Content_Types].xml when done</param>
        /// <returns>ReturnResult</returns>
        public ReturnResult UncompressFile(string folderName, string compressedFileName, bool overrideExisting, bool removeDescFile)
        {
            ReturnResult result = new ReturnResult();

            try
            {
                if (!File.Exists(compressedFileName))
                {
                    result.Success = false;
                    result.Message = "Compressed File not found";
                    return(result);
                }

                DirectoryInfo directoryInfo = new DirectoryInfo(folderName);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }

                using (Package package = Package.Open(compressedFileName, FileMode.Open, FileAccess.Read))
                {
                    PackagePart documentPart = null;
                    PackagePart resourcePart = null;

                    Uri uriDocumentTarget = null;
                    foreach (PackageRelationship relationship in package.GetRelationshipsByType(PackageRelationshipType))
                    {
                        uriDocumentTarget = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
                        documentPart      = package.GetPart(uriDocumentTarget);
                        ExtractPart(documentPart, folderName, overrideExisting);
                    }
                    if (documentPart != null)
                    {
                        Uri uriResourceTarget = null;
                        foreach (PackageRelationship relationship in documentPart.GetRelationshipsByType(ResourceRelationshipType))
                        {
                            uriResourceTarget = PackUriHelper.ResolvePartUri(documentPart.Uri, relationship.TargetUri);
                            resourcePart      = package.GetPart(uriResourceTarget);
                            ExtractPart(resourcePart, folderName, overrideExisting);
                        }
                    }
                }

                if (removeDescFile && File.Exists(folderName + "\\[Content_Types].xml"))
                {
                    File.Delete(folderName + "\\[Content_Types].xml");
                }
            }
            catch (Exception e)
            {
                throw new Exception("Error unzipping file " + compressedFileName, e);
            }
            OnZipEnd(new ZipEndEventArgs());
            result.Success = true;
            result.Message = "OK";
            return(result);
        }
Beispiel #30
0
        /// <summary>
        /// Creates a new instance of the ExcelWorksheets class.
        /// For internal use only!
        /// </summary>
        /// <param name="xlPackage"></param>
        protected internal ExcelWorksheets(ExcelPackage xlPackage)
        {
            _xlPackage = xlPackage;
            //  Create a NamespaceManager to handle the default namespace,
            //  and create a prefix for the default namespace:
            var nt = new NameTable();

            _nsManager = new XmlNamespaceManager(nt);
            _nsManager.AddNamespace("d", ExcelPackage.schemaMain);
            _nsManager.AddNamespace("r", ExcelPackage.schemaRelationships);

            // obtain container node for all worksheets
            _worksheetsNode = _xlPackage.Workbook.WorkbookXml.SelectSingleNode("//d:sheets", _nsManager);
            if (_worksheetsNode == null)
            {
                // create new node as it did not exist
                _worksheetsNode = _xlPackage.Workbook.WorkbookXml.CreateElement("sheets", ExcelPackage.schemaMain);
                _xlPackage.Workbook.WorkbookXml.DocumentElement.AppendChild(_worksheetsNode);
            }

            _worksheets = new Dictionary <int, ExcelWorksheet>();
            var positionId = 1;

            foreach (XmlNode sheetNode in _worksheetsNode.ChildNodes)
            {
                var name = sheetNode.Attributes["name"].Value;
                //  Get the relationship id attribute:
                var relId   = sheetNode.Attributes["r:id"].Value;
                var sheetId = Convert.ToInt32(sheetNode.Attributes["sheetId"].Value);
                //if (sheetID != count)
                //{
                //  // renumber the sheets as they are in an odd order
                //  sheetID = count;
                //  sheetNode.Attributes["sheetId"].Value = sheetID.ToString();
                //}
                // get hidden attribute (if present)
                var     hidden = false;
                XmlNode attr   = sheetNode.Attributes["hidden"];
                if (attr != null)
                {
                    hidden = Convert.ToBoolean(attr.Value);
                }

                //string type = "";
                //attr = sheetNode.Attributes["type"];
                //if (attr != null)
                //  type = attr.Value;

                var sheetRelation = _xlPackage.Workbook.Part.GetRelationship(relId);
                var uriWorksheet  = PackUriHelper.ResolvePartUri(_xlPackage.Workbook.WorkbookUri, sheetRelation.TargetUri);

                // add worksheet to our collection
                _worksheets.Add(positionId, new ExcelWorksheet(_xlPackage, relId, name, uriWorksheet, sheetId, hidden));
                positionId++;
            }
        }