protected Fooder(FooderType fooderType, PackagePart packagePart, XDocument xDocument, PackageRelationship relationship, FooderDesignation designation, WordDocument document) : base(xDocument.Root ?? throw new Exception("Header or footer root must not be null"), packagePart, document) { this.xDocument = xDocument; FooderType = fooderType; Relationship = relationship; Designation = designation; }
internal RelationPart(PackageRelationship relationship, POIXMLDocumentPart documentPart) { this.relationship = relationship; this.documentPart = documentPart; }
void getBinary(Experiment e) { if (!Directory.Exists(e.localDir)) { throw new Exception("Local scratch directory does not exist: " + e.localDir); } if (!File.Exists(e.localExecutable)) { Console.WriteLine("Downloading binary..."); FileStream fs = null; try { fs = new FileStream(e.localExecutable, FileMode.CreateNew); } catch (IOException) { if (File.Exists(e.localExecutable)) { // All is good, someone else downloaded it! return; } } byte[] data = new byte[0]; Dictionary <string, Object> r = SQLRead("SELECT Binary FROM Binaries WHERE ID=" + e.binaryID); data = (byte[])r["Binary"]; int sz = data.GetUpperBound(0); fs.Write(data, 0, sz); fs.Flush(); fs.Close(); if (data[0] == 0x50 && data[1] == 0x4b && data[2] == 0x03 && data[3] == 0x04) { // This is a zip file. string tfn = Path.Combine(Path.GetTempFileName() + ".zip"); File.Move(e.localExecutable, tfn); e.localExecutable = null; Package pkg = Package.Open(tfn, FileMode.Open); PackageRelationshipCollection rels = pkg.GetRelationships(); if (rels.Count() != 1) { throw new Exception("Missing package relationships"); } PackageRelationship main = rels.First(); foreach (PackagePart part in pkg.GetParts()) { // Uri uriDocumentTarget = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), rel.TargetUri); // PackagePart part = pkg.GetPart(uriDocumentTarget); Stream s = part.GetStream(FileMode.Open, FileAccess.Read); string fn = CreateFilenameFromUri(part.Uri).Substring(1); fs = new FileStream(e.localDir + @"\" + fn, FileMode.OpenOrCreate); CopyStream(s, fs); fs.Close(); if (part.Uri == main.TargetUri) { e.localExecutable = e.localDir + @"\" + fn; } } pkg.Close(); if (e.localExecutable == null) { throw new Exception("Main executable not found in zip."); } try { File.Delete(tfn); } catch (Exception) { } } string ext = Path.GetExtension(e.localExecutable); string localname = e.localExecutable + "-" + myName + ext; File.Move(e.localExecutable, localname); e.localExecutable += "-" + myName + ext; int retry_count = 1000; while (!File.Exists(localname)) { Thread.Sleep(100); retry_count--; if (retry_count == 0) { throw new Exception("Local binary missing."); } } retry_count = 1000; retry: try { FileStream tmp = File.OpenRead(localname); tmp.Close(); } catch { Thread.Sleep(100); retry_count--; if (retry_count == 0) { throw new Exception("Local binary is not readable."); } goto retry; } } }
private Worksheet AddWorksheet(string name) { try { PackageRelationship sheetRelationship = null; using (Stream workbookStream = _workbookPart.GetStream(FileMode.Open, FileAccess.ReadWrite)) { Uri sheetUri = null; using (var writer = XmlWriter.Create(workbookStream)) { var document = XDocument.Load(workbookStream); XElement sheets = document.Descendants().FirstOrDefault(d => d.Name.Equals(Constants.MainXNamespace + "sheets")); var sheetElements = sheets.Descendants(Constants.MainXNamespace + "sheet"); int sheetId; if (sheetElements.Any()) { if (sheetElements.Any(se => se.Attribute("name").Value == name)) { throw new Exception(String.Format("Sheet with name {0} already exists", name)); } Int32.TryParse(sheetElements.Last().Attribute("sheetId").Value, out sheetId); sheetId++; } else { sheetId = 1; } sheetUri = new Uri(String.Format(Constants.SheetUriFormatPath, sheetId), UriKind.Relative); sheetRelationship = _workbookPart.CreateRelationship(sheetUri, TargetMode.Internal, Constants.RelationshipNamespace + "/worksheet"); sheets.Add(new XElement(Constants.MainXNamespace + "sheet" , new XAttribute("name", name) , new XAttribute("sheetId", sheetId) , new XAttribute(Constants.RelationshipXNamespace + "id", sheetRelationship.Id))); // Clear the workbook xml file workbookStream.SetLength(0); document.WriteTo(writer); } PackagePart worksheetPart = _package.CreatePart(sheetUri, Constants.WorksheetContentType); var worksheet = new Worksheet(_stylesheet, worksheetPart) { Name = name, RelationshipId = sheetRelationship.Id, }; using (var writer = XmlWriter.Create(worksheetPart.GetStream(FileMode.Create, FileAccess.Write))) { worksheet.WorksheetXml = new XDocument(new XElement(Constants.MainXNamespace + "worksheet", new XAttribute(XNamespace.Xmlns + "r", Constants.RelationshipNamespace))); worksheet.WorksheetXml.WriteTo(writer); } return(worksheet); } } catch { // TODO :: Add exception handling logic throw; } }
public POIXMLDocumentPart(PackagePart part, PackageRelationship rel) : this(null, part) { }
/** * Construct XWPFPictureData from a package part * * @param part the package part holding the Drawing data, * @param rel the package relationship holding this Drawing, * the relationship type must be http://schemas.Openxmlformats.org/officeDocument/2006/relationships/image */ public XWPFPictureData(PackagePart part, PackageRelationship rel) : base(part, rel) { }
/// <summary> /// Reads the metadata parts of a CDDX file. /// </summary> void ReadMetadata() { // Read core properties PackageRelationship coreRelationship = m_package.GetRelationshipsByType(RelationshipTypes.CoreProperties).FirstOrDefault(); if (coreRelationship != null) { PackagePart corePart = m_package.GetPart(coreRelationship.TargetUri); try { using (Stream coreStream = corePart.GetStream(FileMode.Open)) { XmlDocument doc = new XmlDocument(); doc.Load(coreStream); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable); namespaceManager.AddNamespace("cp", "http://schemas.circuit-diagram.org/circuitDiagramDocument/2012/metadata/core-properties"); namespaceManager.AddNamespace("dc", Namespaces.DublinCore); XmlNode creator = doc.SelectSingleNode("cp:coreProperties/dc:creator", namespaceManager); if (creator != null) { Document.Metadata.Creator = creator.InnerText; } XmlNode date = doc.SelectSingleNode("cp:coreProperties/dc:date", namespaceManager); if (date != null) { DateTime dateTime; if (DateTime.TryParse(date.InnerText, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal, out dateTime)) { Document.Metadata.Created = dateTime; } } XmlNode description = doc.SelectSingleNode("cp:coreProperties/dc:description", namespaceManager); if (description != null) { Document.Metadata.Description = description.InnerText; } XmlNode title = doc.SelectSingleNode("cp:coreProperties/dc:title", namespaceManager); if (title != null) { Document.Metadata.Title = title.InnerText; } } } catch { } } // Read extended properties PackageRelationship extendedRelationship = m_package.GetRelationshipsByType(RelationshipTypes.ExtendedProperties).FirstOrDefault(); if (extendedRelationship != null) { PackagePart extendedPart = m_package.GetPart(extendedRelationship.TargetUri); try { using (Stream extendedStream = extendedPart.GetStream(FileMode.Open)) { XmlDocument doc = new XmlDocument(); doc.Load(extendedStream); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable); namespaceManager.AddNamespace("cp", "http://schemas.circuit-diagram.org/circuitDiagramDocument/2012/metadata/extended-properties"); XmlNode application = doc.SelectSingleNode("cp:extendedProperties/cp:application", namespaceManager); if (application != null) { Document.Metadata.Application = application.InnerText; } XmlNode appVersion = doc.SelectSingleNode("cp:extendedProperties/cp:appVersion", namespaceManager); if (appVersion != null) { Document.Metadata.AppVersion = appVersion.InnerText; } } } catch { } } }
public XWPFSettings(PackagePart part, PackageRelationship rel) : base(part, rel) { }
private string AddImageHelper(string fileName, string id) { if (fileName == null) { throw new ArgumentNullException("fileName"); } Debug.Assert(File.Exists(fileName), fileName + "does not exist."); if (!File.Exists(fileName)) { return(null); } BinaryReader br = new BinaryReader(File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); Debug.Assert(br != null, "Fail to create a BinaryReader from file."); if (br == null) { return(null); } Uri imageUri = new Uri("images/" + Path.GetFileName(fileName), UriKind.Relative); int fileIndex = 0; while (true) { if (_part.Package.PartExists(PackUriHelper.ResolvePartUri(_part.Uri, imageUri))) { Debug.Write(imageUri.ToString() + " already exists."); imageUri = new Uri( "images/" + Path.GetFileNameWithoutExtension(fileName) + (fileIndex++).ToString() + Path.GetExtension(fileName), UriKind.Relative); continue; } break; } if (id != null) { int idIndex = 0; string testId = id; while (true) { if (_part.RelationshipExists(testId)) { Debug.Write(testId + " already exists."); testId = id + (idIndex++); continue; } id = testId; break; } } PackageRelationship imageRel = _part.CreateRelationship(imageUri, TargetMode.Internal, OfficeDocument.ImagePartRelType, id); Debug.Assert(imageRel != null, "Fail to create image relationship."); if (imageRel == null) { return(null); } PackagePart imagePart = _part.Package.CreatePart( PackUriHelper.ResolvePartUri(imageRel.SourceUri, imageRel.TargetUri), OfficePart.MapImageContentType(Path.GetExtension(fileName))); Debug.Assert(imagePart != null, "Fail to create image part."); if (imagePart == null) { return(null); } BinaryWriter bw = new BinaryWriter(imagePart.GetStream(FileMode.Create, FileAccess.Write)); Debug.Assert(bw != null, "Fail to create a BinaryWriter to write to part."); if (bw == null) { return(null); } byte[] buffer = new byte[1024]; int byteCount = 0; while ((byteCount = br.Read(buffer, 0, buffer.Length)) > 0) { bw.Write(buffer, 0, byteCount); } bw.Flush(); bw.Close(); br.Close(); return(imageRel.Id); }
/** * Create a POIXMLDocumentPart from existing namespace part and relation. This method is called * from {@link POIXMLDocument#load(POIXMLFactory)} when parsing a document * * @param parent parent part * @param rel the namespace part relationship * @param part the PackagePart representing the Created instance * @return A new instance of a POIXMLDocumentPart. */ public abstract POIXMLDocumentPart CreateDocumentPart(POIXMLDocumentPart parent, PackageRelationship rel, PackagePart part);
public override POIXMLDocumentPart CreateDocumentPart(POIXMLDocumentPart parent, PackageRelationship rel, PackagePart part) { return(new POIXMLDocumentPart(part, rel)); }
public PackageDocumentPart(Document owner, PackageRelationship relationship) : base(owner, relationship) { }
internal SingleXmlCells(PackagePart part, PackageRelationship rel) : base(part, rel) { ReadFrom(part.GetInputStream()); }
public void TestCreateExcelHyperlinkRelations() { string filepath = OpenXml4NetTestDataSamples.GetSampleFileName("ExcelWithHyperlinks.xlsx"); OPCPackage pkg = OPCPackage.Open(filepath, PackageAccess.READ_WRITE); PackagePart sheet = pkg.GetPart( PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS)); Assert.IsNotNull(sheet); Assert.AreEqual(3, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size); // Add three new ones PackageRelationship openxml4j = sheet.AddExternalRelationship("http://www.Openxml4j.org/", HYPERLINK_REL_TYPE); PackageRelationship sf = sheet.AddExternalRelationship("http://openxml4j.sf.net/", HYPERLINK_REL_TYPE); PackageRelationship file = sheet.AddExternalRelationship("MyDocument.docx", HYPERLINK_REL_TYPE); // Check they were Added properly Assert.IsNotNull(openxml4j); Assert.IsNotNull(sf); Assert.IsNotNull(file); Assert.AreEqual(6, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size); Assert.AreEqual("http://www.openxml4j.org/", openxml4j.TargetUri.ToString()); Assert.AreEqual("/xl/worksheets/sheet1.xml", openxml4j.SourceUri.ToString()); Assert.AreEqual(HYPERLINK_REL_TYPE, openxml4j.RelationshipType); Assert.AreEqual("http://openxml4j.sf.net/", sf.TargetUri.ToString()); Assert.AreEqual("/xl/worksheets/sheet1.xml", sf.SourceUri.ToString()); Assert.AreEqual(HYPERLINK_REL_TYPE, sf.RelationshipType); Assert.AreEqual("MyDocument.docx", file.TargetUri.ToString()); Assert.AreEqual("/xl/worksheets/sheet1.xml", file.SourceUri.ToString()); Assert.AreEqual(HYPERLINK_REL_TYPE, file.RelationshipType); // Will Get ids 7, 8 and 9, as we already have 1-6 Assert.AreEqual("rId7", openxml4j.Id); Assert.AreEqual("rId8", sf.Id); Assert.AreEqual("rId9", file.Id); // Write out and re-load MemoryStream baos = new MemoryStream(); pkg.Save(baos); MemoryStream bais = new MemoryStream(baos.ToArray()); pkg = OPCPackage.Open(bais); // use revert to not re-write the input file pkg.Revert(); // Check again sheet = pkg.GetPart( PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS)); Assert.AreEqual(6, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size); Assert.AreEqual("http://poi.apache.org/", sheet.GetRelationship("rId1").TargetUri.ToString()); Assert.AreEqual("mailto:[email protected]?subject=XSSF Hyperlinks", sheet.GetRelationship("rId3").TargetUri.ToString()); Assert.AreEqual("http://www.openxml4j.org/", sheet.GetRelationship("rId7").TargetUri.ToString()); Assert.AreEqual("http://openxml4j.sf.net/", sheet.GetRelationship("rId8").TargetUri.ToString()); Assert.AreEqual("MyDocument.docx", sheet.GetRelationship("rId9").TargetUri.ToString()); }
protected XSSFChart(PackagePart part, PackageRelationship rel) : base(part, rel) { this.chartSpace = ChartSpaceDocument.Parse(part.GetInputStream()).GetChartSpace(); this.chart = this.chartSpace.chart; }
// appelé uniquement par la fonction AddCurrHeadLevel dans la classe d'origine /// <summary> /// /// </summary> /// <param name="prevHeadLvl"></param> /// <param name="currLvl"></param> /// <param name="location"></param> /// <param name="absId"></param> public void NumberHeadings(int prevHeadLvl, int currLvl, String location, String absId) { foreach (PackageRelationship searchRelation in pack.GetRelationshipsByType(wordRelationshipType)) { relationship = searchRelation; break; } Uri partUri = PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri); PackagePart mainPartxml = pack.GetPart(partUri); foreach (PackageRelationship searchRelation in mainPartxml.GetRelationshipsByType(numberRelationshipType)) { numberRelationship = searchRelation; break; } Uri numberPartUri = PackUriHelper.ResolvePartUri(numberRelationship.SourceUri, numberRelationship.TargetUri); PackagePart numberPartxml = pack.GetPart(numberPartUri); XmlDocument doc = new XmlDocument(); doc.Load(numberPartxml.GetStream()); NameTable nt = new NameTable(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); nsManager.AddNamespace("w", docNamespace); StartNewHeadingCounter(prevHeadId[1].ToString(), absId); CopyToCurrCounter(prevHeadId[1].ToString()); int val = prevHeadLvl + 1; for (int i = val; i <= currLvl; i++) { XmlNodeList listDel = doc.SelectNodes("w:numbering/w:num[@w:numId=" + prevHeadId[0] + "]/w:lvlOverride[@w:ilvl=" + i + "]/w:startOverride", nsManager); if (listDel.Count != 0) { StartHeadingValueCtr(prevHeadId[1].ToString(), absId); String tempId = ""; tempId = CheckAbstCounter(prevHeadId[1].ToString(), absId); String valAbs = listDel[0].Attributes[0].Value; if (valAbs == "") { valAbs = "0"; } if (i == currLvl) { if (location == "Style") { ((ArrayList)startHeadingItem["List" + tempId])[i] = Convert.ToInt16(valAbs) - 1; ((ArrayList)headingCounters["List" + prevHeadId[1]])[Convert.ToInt16(i)] = Convert.ToInt16(valAbs) - 1; } else { ((ArrayList)startHeadingItem["List" + tempId])[i] = valAbs; ((ArrayList)headingCounters["List" + prevHeadId[1]])[Convert.ToInt16(i)] = valAbs; } } else { ((ArrayList)startHeadingItem["List" + tempId])[i] = valAbs; ((ArrayList)headingCounters["List" + prevHeadId[1]])[Convert.ToInt16(i)] = valAbs; } } else { XmlNodeList listAbsDel = doc.SelectNodes("w:numbering/w:num[@w:numId=" + prevHeadId[0] + "]/w:abstractNumId", nsManager); XmlNodeList list = doc.SelectNodes("w:numbering/w:abstractNum[@w:abstractNumId=" + listAbsDel[0].Attributes[0].Value + "]/w:lvl[@w:ilvl=" + i + "]/w:start", nsManager); StartHeadingValueCtr(prevHeadId[1].ToString(), absId); String tempId = ""; tempId = CheckAbstCounter(prevHeadId[1].ToString(), absId); if (list.Count != 0) { String valAbs = list[0].Attributes[0].Value; if (valAbs == "") { valAbs = "0"; } if (i == currLvl) { if (location == "Style") { ((ArrayList)startHeadingItem["List" + tempId])[i] = Convert.ToInt16(valAbs) - 1; ((ArrayList)headingCounters["List" + prevHeadId[1]])[Convert.ToInt16(i)] = Convert.ToInt16(valAbs) - 1; } else { ((ArrayList)startHeadingItem["List" + tempId])[i] = valAbs; ((ArrayList)headingCounters["List" + prevHeadId[1]])[Convert.ToInt16(i)] = valAbs; } } else { ((ArrayList)startHeadingItem["List" + tempId])[i] = valAbs; ((ArrayList)headingCounters["List" + prevHeadId[1]])[Convert.ToInt16(i)] = valAbs; } } else { String valAbs = "0"; if (i == currLvl) { if (location == "Style") { ((ArrayList)startHeadingItem["List" + tempId])[i] = Convert.ToInt16(valAbs) - 1; ((ArrayList)headingCounters["List" + prevHeadId[1]])[Convert.ToInt16(i)] = Convert.ToInt16(valAbs) - 1; } else { ((ArrayList)startHeadingItem["List" + tempId])[i] = valAbs; ((ArrayList)headingCounters["List" + prevHeadId[1]])[Convert.ToInt16(i)] = valAbs; } } else { ((ArrayList)startHeadingItem["List" + tempId])[i] = valAbs; ((ArrayList)headingCounters["List" + prevHeadId[1]])[Convert.ToInt16(i)] = valAbs; } } } } }
/** * Creates an POIXMLDocumentPart representing the given namespace part, relationship and parent * Called by {@link #read(POIXMLFactory, java.util.Map)} when Reading in an exisiting file. * * @param parent - Parent part * @param part - The namespace part that holds xml data represenring this sheet. * @param rel - the relationship of the given namespace part * @see #read(POIXMLFactory, java.util.Map) */ public POIXMLDocumentPart(POIXMLDocumentPart parent, PackagePart part, PackageRelationship rel) { this.packagePart = part; this.packageRel = rel; this.parent = parent; }
internal Image(DocX document, PackageRelationship pr) { this.document = document; this.pr = pr; this.id = pr.Id; }
/// <summary> /// Loads the main document part of a CDDX file. /// </summary> /// <param name="package">The package containing the document to load.</param> /// <returns>True if succeeded, false otherwise.</returns> bool LoadMainDocument(Package package) { // Open the document part PackageRelationship documentRelationship = package.GetRelationshipsByType(RelationshipTypes.Document).FirstOrDefault(); PackagePart documentPart = package.GetPart(documentRelationship.TargetUri); using (Stream docStream = documentPart.GetStream(FileMode.Open)) { Document = new IODocument(); XmlDocument doc = new XmlDocument(); doc.Load(docStream); // Set up namespaces XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable); namespaceManager.AddNamespace("cdd", Namespaces.Document); namespaceManager.AddNamespace("ec", Namespaces.DocumentComponentDescriptions); // Read version double version = 1.0; XmlElement rootElement = doc.SelectSingleNode("/cdd:circuit", namespaceManager) as XmlElement; if (rootElement != null && rootElement.HasAttribute("version")) { double.TryParse(rootElement.Attributes["version"].InnerText, out version); } if (version > FormatVersion) { m_newerVersion = true; } if (m_newerVersion) { LoadResult.Type = DocumentLoadResultType.SuccessNewerVersion; } else { LoadResult.Type = DocumentLoadResultType.Success; } // Read size double width = 640d; double height = 480d; XmlNode widthNode = doc.SelectSingleNode("/cdd:circuit/cdd:properties/cdd:width", namespaceManager); if (widthNode != null) { double.TryParse(widthNode.InnerText, out width); } XmlNode heightNode = doc.SelectSingleNode("/cdd:circuit/cdd:properties/cdd:height", namespaceManager); if (heightNode != null) { double.TryParse(heightNode.InnerText, out height); } Document.Size = new Size(width, height); // Read sources m_typeParts.Clear(); Dictionary <string, IOComponentType> componentTypes = new Dictionary <string, IOComponentType>(); // for use when loading component elements XmlNodeList componentSourceNodes = doc.SelectNodes("/cdd:circuit/cdd:definitions/cdd:src", namespaceManager); foreach (XmlElement source in componentSourceNodes) { // Read collection string collection = null; if (source.HasAttribute("col")) { collection = source.Attributes["col"].InnerText; } foreach (XmlElement addType in source.SelectNodes("cdd:add", namespaceManager)) { // Read item string typeId = addType.Attributes["id"].InnerText; string item = null; if (addType.HasAttribute("item")) { item = addType.Attributes["item"].InnerText; } // Read additional attributes for opening with the same component description string name = null; if (addType.HasAttribute("name", Namespaces.DocumentComponentDescriptions)) { name = addType.Attributes["name", Namespaces.DocumentComponentDescriptions].InnerText; } Guid guid = Guid.Empty; if (addType.HasAttribute("guid", Namespaces.DocumentComponentDescriptions)) { guid = new Guid(addType.Attributes["guid", Namespaces.DocumentComponentDescriptions].InnerText); } // Create new IOComponentType IOComponentType type = new IOComponentType(collection, item); type.Name = name; type.GUID = guid; // Read additional attributes for embedding if (addType.HasAttribute("id", Namespaces.Relationships)) { string relationshipId = addType.Attributes["id", Namespaces.Relationships].InnerText; PackageRelationship relationship = documentPart.GetRelationship(relationshipId); PackagePart embeddedTypePart = package.GetPart(PackUriHelper.ResolvePartUri(documentPart.Uri, relationship.TargetUri)); m_typeParts.Add(type, embeddedTypePart); } componentTypes.Add(typeId, type); } } // Read wire elements XmlNodeList wires = doc.SelectNodes("/cdd:circuit/cdd:elements//cdd:w", namespaceManager); foreach (XmlElement wire in wires) { // Read wire double x = double.Parse(wire.Attributes["x"].InnerText); double y = double.Parse(wire.Attributes["y"].InnerText); Orientation orientation = Orientation.Vertical; if (wire.HasAttribute("o") && wire.Attributes["o"].InnerText.ToLowerInvariant() == "h") { orientation = Orientation.Horizontal; } double size = 10d; if (wire.HasAttribute("sz")) { size = double.Parse(wire.Attributes["sz"].InnerText); } Document.Wires.Add(new IOWire(new Point(x, y), size, orientation)); } // Read component elements XmlNodeList componentElements = doc.SelectNodes("/cdd:circuit/cdd:elements//cdd:c", namespaceManager); foreach (XmlElement element in componentElements) { // Read component element string id = null; if (element.HasAttribute("id")) { id = element.Attributes["id"].InnerText; } string typeId = element.Attributes["tp"].InnerText; // Read layout information Point?location = null; if (element.HasAttribute("x") && element.HasAttribute("y")) { location = new Point(double.Parse(element.Attributes["x"].InnerText), double.Parse(element.Attributes["y"].InnerText)); } double?size = null; if (element.HasAttribute("sz")) { size = double.Parse(element.Attributes["sz"].InnerText); } Orientation?orientation = null; if (element.HasAttribute("o") && element.Attributes["o"].InnerText.ToLowerInvariant() == "h") { orientation = Orientation.Horizontal; } else if (element.HasAttribute("o") && element.Attributes["o"].InnerText.ToLowerInvariant() == "v") { orientation = Orientation.Vertical; } bool?flipped = null; if (element.HasAttribute("flp") && element.Attributes["flp"].InnerText.ToLowerInvariant() == "false") { flipped = false; } else if (element.HasAttribute("flp")) { flipped = true; } // Read properties List <IOComponentProperty> properties = new List <IOComponentProperty>(); XmlNodeList propertyNodes = element.SelectNodes("cdd:prs/cdd:p", namespaceManager); foreach (XmlElement property in propertyNodes) { // Read property string key = property.Attributes["k"].InnerText; string value = property.Attributes["v"].InnerText; bool isStandard = true; if (property.HasAttribute("st", Namespaces.DocumentComponentDescriptions) && property.Attributes["st", Namespaces.DocumentComponentDescriptions].InnerText == "false") { isStandard = false; } properties.Add(new IOComponentProperty(key, value, isStandard)); } // Read connections Dictionary <string, string> connections = new Dictionary <string, string>(); XmlNodeList connectionNodes = element.SelectNodes("cdd:cns/cdd:cn", namespaceManager); foreach (XmlNode connection in connectionNodes) { // Read connection string point = connection.Attributes["pt"].InnerText; string connectionId = connection.Attributes["id"].InnerText; connections.Add(point, connectionId); } // Find type IOComponentType type = null; if (typeId.StartsWith("{") && typeId.EndsWith("}")) { // Type in expected format: {0} string typeIdOnly = typeId.Substring(1, typeId.Length - 2); // Remove curly braces if (componentTypes.ContainsKey(typeIdOnly)) { type = componentTypes[typeIdOnly]; } else { throw new NotSupportedException(); // Undefined type } } Document.Components.Add(new IOComponent(id, location, size, flipped, orientation, type, properties, connections)); } return(true); } }
/** * Construct XWPFFootnotes from a package part * * @param part the package part holding the data of the footnotes, * @param rel the package relationship of type "http://schemas.Openxmlformats.org/officeDocument/2006/relationships/footnotes" */ public XWPFFootnotes(PackagePart part, PackageRelationship rel) : base(part, rel) { ; }
private static List <string> ProcessWordDoc(MemoryStream fileBytes) { const string documentRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; const string stylesRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"; const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; XNamespace w = wordmlNamespace; XDocument xDoc = null; XDocument styleDoc = null; using (Package wdPackage = Package.Open(fileBytes, FileMode.Open, FileAccess.Read)) { PackageRelationship docPackageRelationship = wdPackage .GetRelationshipsByType(documentRelationshipType) .FirstOrDefault(); if (docPackageRelationship != null) { Uri documentUri = PackUriHelper .ResolvePartUri( new Uri("/", UriKind.Relative), docPackageRelationship.TargetUri); PackagePart documentPart = wdPackage.GetPart(documentUri); // Load the document XML in the part into an XDocument instance. xDoc = XDocument.Load(XmlReader.Create(documentPart.GetStream())); // Find the styles part. There will only be one. PackageRelationship styleRelation = documentPart.GetRelationshipsByType(stylesRelationshipType) .FirstOrDefault(); if (styleRelation != null) { Uri styleUri = PackUriHelper.ResolvePartUri(documentUri, styleRelation.TargetUri); PackagePart stylePart = wdPackage.GetPart(styleUri); // Load the style XML in the part into an XDocument instance. styleDoc = XDocument.Load(XmlReader.Create(stylePart.GetStream())); } } } string defaultStyle = (string)( from style in styleDoc.Root.Elements(w + "style") where (string)style.Attribute(w + "type") == "paragraph" && (string)style.Attribute(w + "default") == "1" select style ).First().Attribute(w + "styleId"); // Find all paragraphs in the document. var paragraphs = from para in xDoc .Root .Element(w + "body") .Descendants(w + "p") let styleNode = para .Elements(w + "pPr") .Elements(w + "pStyle") .FirstOrDefault() select new { ParagraphNode = para, StyleName = styleNode != null ? (string)styleNode.Attribute(w + "val") : defaultStyle }; // Retrieve the text of each paragraph. var paraWithText = from para in paragraphs select new { ParagraphNode = para.ParagraphNode, StyleName = para.StyleName, Text = ParagraphText(para.ParagraphNode) }; List <string> array = new List <string>(); foreach (var para in paraWithText) { array.Add(para.Text); } return(array); }
internal MapInfo(PackagePart part, PackageRelationship rel) : base(part, rel) { xml = ConvertStreamToXml(part.GetInputStream()); ReadFrom(xml); }
protected XSSFPivotCache(PackagePart part, PackageRelationship rel) : this(part) { }
public XWPFSettings(PackagePart part, PackageRelationship rel) : this(part) { }
public void AddRelation(String id, POIXMLDocumentPart part) { PackageRelationship pr = part.GetPackagePart().GetRelationship(id); AddRelation(pr, part); }
internal void SetPictureReference(PackageRelationship rel) { this.ctPicture.blipFill.blip.embed = rel.Id; }
/** * Get the PackagePart that is the target of a relationship. * * @param rel The relationship * @return The target part * @throws InvalidFormatException */ protected PackagePart GetTargetPart(PackageRelationship rel) { return(GetPackagePart().GetRelatedPart(rel)); }
public bool SaveAs(string fn, bool writeFreshly = false, PreferredFormat prefFmt = PreferredFormat.None, MemoryStream useMemoryStream = null) { if (fn.ToLower().EndsWith(".xml")) { // save only XML this.fn = fn; try { using (var s = new StreamWriter(this.fn)) { // TODO: use aasenv serialzers here! var serializer = new XmlSerializer(typeof(AdminShell.AdministrationShellEnv)); var nss = new XmlSerializerNamespaces(); nss.Add("xsi", System.Xml.Schema.XmlSchema.InstanceNamespace); nss.Add("aas", "http://www.admin-shell.io/aas/2/0"); nss.Add("IEC61360", "http://www.admin-shell.io/IEC61360/2/0"); serializer.Serialize(s, this.aasenv, nss); } } catch (Exception ex) { throw (new Exception(string.Format("While writing AAS {0} at {1} gave: {2}", fn, AdminShellUtil.ShortLocation(ex), ex.Message))); } return(true); } if (fn.ToLower().EndsWith(".json")) { // save only JSON // this funcitonality is a initial test this.fn = fn; try { using (var sw = new StreamWriter(fn)) { // TODO: use aasenv serialzers here! sw.AutoFlush = true; JsonSerializer serializer = new JsonSerializer() { NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, Formatting = Newtonsoft.Json.Formatting.Indented }; using (JsonWriter writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, this.aasenv); } } } catch (Exception ex) { throw (new Exception(string.Format("While writing AAS {0} at {1} gave: {2}", fn, AdminShellUtil.ShortLocation(ex), ex.Message))); } return(true); } if (fn.ToLower().EndsWith(".aasx")) { // save package AASX try { // we want existing contents to be preserved, but no possiblity to change file name // therefore: copy file to new name, re-open! // fn could be changed, therefore close "old" package first if (this.openPackage != null) { // ReSharper disable EmptyGeneralCatchClause try { this.openPackage.Close(); if (!writeFreshly) { if (this.tempFn != null) { System.IO.File.Copy(this.tempFn, fn); } else { System.IO.File.Copy(this.fn, fn); } } } catch { } // ReSharper enable EmptyGeneralCatchClause this.openPackage = null; } // approach is to utilize the existing package, if possible. If not, create from scratch Package package = null; if (useMemoryStream != null) { package = Package.Open(useMemoryStream, (writeFreshly) ? FileMode.Create : FileMode.OpenOrCreate); } else { package = Package.Open((this.tempFn != null) ? this.tempFn : fn, (writeFreshly) ? FileMode.Create : FileMode.OpenOrCreate); } this.fn = fn; // get the origin from the package PackagePart originPart = null; var xs = package.GetRelationshipsByType("http://www.admin-shell.io/aasx/relationships/aasx-origin"); foreach (var x in xs) { if (x.SourceUri.ToString() == "/") { originPart = package.GetPart(x.TargetUri); break; } } if (originPart == null) { // create, as not existing originPart = package.CreatePart(new Uri("/aasx/aasx-origin", UriKind.RelativeOrAbsolute), System.Net.Mime.MediaTypeNames.Text.Plain, CompressionOption.Maximum); using (var s = originPart.GetStream(FileMode.Create)) { var bytes = System.Text.Encoding.ASCII.GetBytes("Intentionally empty."); s.Write(bytes, 0, bytes.Length); } package.CreateRelationship(originPart.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aasx-origin"); } // get the specs from the package PackagePart specPart = null; PackageRelationship specRel = null; xs = originPart.GetRelationshipsByType("http://www.admin-shell.io/aasx/relationships/aas-spec"); foreach (var x in xs) { specRel = x; specPart = package.GetPart(x.TargetUri); break; } // check, if we have to change the spec part if (specPart != null && specRel != null) { var name = System.IO.Path.GetFileNameWithoutExtension(specPart.Uri.ToString()).ToLower().Trim(); var ext = System.IO.Path.GetExtension(specPart.Uri.ToString()).ToLower().Trim(); if ((ext == ".json" && prefFmt == PreferredFormat.Xml) || (ext == ".xml" && prefFmt == PreferredFormat.Json) || (name.StartsWith("aasenv-with-no-id"))) { // try kill specpart // ReSharper disable EmptyGeneralCatchClause try { originPart.DeleteRelationship(specRel.Id); package.DeletePart(specPart.Uri); } catch { } finally { specPart = null; specRel = null; } // ReSharper enable EmptyGeneralCatchClause } } if (specPart == null) { // create, as not existing var frn = "aasenv-with-no-id"; if (this.aasenv.AdministrationShells.Count > 0) { frn = this.aasenv.AdministrationShells[0].GetFriendlyName() ?? frn; } var aas_spec_fn = "/aasx/#/#.aas"; if (prefFmt == PreferredFormat.Json) { aas_spec_fn += ".json"; } else { aas_spec_fn += ".xml"; } aas_spec_fn = aas_spec_fn.Replace("#", "" + frn); specPart = package.CreatePart(new Uri(aas_spec_fn, UriKind.RelativeOrAbsolute), System.Net.Mime.MediaTypeNames.Text.Xml, CompressionOption.Maximum); originPart.CreateRelationship(specPart.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aas-spec"); } // now, specPart shall be != null! if (specPart.Uri.ToString().ToLower().Trim().EndsWith("json")) { using (var s = specPart.GetStream(FileMode.Create)) { JsonSerializer serializer = new JsonSerializer(); serializer.NullValueHandling = NullValueHandling.Ignore; serializer.ReferenceLoopHandling = ReferenceLoopHandling.Serialize; serializer.Formatting = Newtonsoft.Json.Formatting.Indented; using (var sw = new StreamWriter(s)) { using (JsonWriter writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, this.aasenv); } } } } else { using (var s = specPart.GetStream(FileMode.Create)) { var serializer = new XmlSerializer(typeof(AdminShell.AdministrationShellEnv)); var nss = new XmlSerializerNamespaces(); nss.Add("xsi", System.Xml.Schema.XmlSchema.InstanceNamespace); nss.Add("aas", "http://www.admin-shell.io/aas/2/0"); nss.Add("IEC61360", "http://www.admin-shell.io/IEC61360/2/0"); serializer.Serialize(s, this.aasenv, nss); } } // there might be pending files to be deleted (first delete, then add, in case of identical files in both categories) foreach (var psfDel in pendingFilesToDelete) { // try find an existing part for that file .. var found = false; // normal files xs = specPart.GetRelationshipsByType("http://www.admin-shell.io/aasx/relationships/aas-suppl"); foreach (var x in xs) { if (x.TargetUri == psfDel.uri) { // try to delete specPart.DeleteRelationship(x.Id); package.DeletePart(psfDel.uri); found = true; break; } } // thumbnails xs = package.GetRelationshipsByType("http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail"); foreach (var x in xs) { if (x.TargetUri == psfDel.uri) { // try to delete package.DeleteRelationship(x.Id); package.DeletePart(psfDel.uri); found = true; break; } } if (!found) { throw (new Exception($"Not able to delete pending file {psfDel.uri} in saving package {fn}")); } } // after this, there are no more pending for delete files pendingFilesToDelete.Clear(); // write pending supplementary files foreach (var psfAdd in pendingFilesToAdd) { // make sure .. if ((psfAdd.sourceLocalPath == null && psfAdd.sourceGetBytesDel == null) || psfAdd.location != AdminShellPackageSupplementaryFile.LocationType.AddPending) { continue; } // normal file? if (psfAdd.specialHandling == AdminShellPackageSupplementaryFile.SpecialHandlingType.None || psfAdd.specialHandling == AdminShellPackageSupplementaryFile.SpecialHandlingType.EmbedAsThumbnail) { // try find an existing part for that file .. PackagePart filePart = null; if (psfAdd.specialHandling == AdminShellPackageSupplementaryFile.SpecialHandlingType.None) { xs = specPart.GetRelationshipsByType("http://www.admin-shell.io/aasx/relationships/aas-suppl"); foreach (var x in xs) { if (x.TargetUri == psfAdd.uri) { filePart = package.GetPart(x.TargetUri); break; } } } if (psfAdd.specialHandling == AdminShellPackageSupplementaryFile.SpecialHandlingType.EmbedAsThumbnail) { xs = package.GetRelationshipsByType("http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail"); foreach (var x in xs) { if (x.SourceUri.ToString() == "/" && x.TargetUri == psfAdd.uri) { filePart = package.GetPart(x.TargetUri); break; } } } if (filePart == null) { // determine mimeType var mimeType = psfAdd.useMimeType; // reconcile mime if (mimeType == null && psfAdd.sourceLocalPath != null) { mimeType = AdminShellPackageEnv.GuessMimeType(psfAdd.sourceLocalPath); } // still null? if (mimeType == null) { // see: https://stackoverflow.com/questions/6783921/which-mime-type-to-use-for-a-binary-file-thats-specific-to-my-program mimeType = "application/octet-stream"; } // create new part and link filePart = package.CreatePart(psfAdd.uri, mimeType, CompressionOption.Maximum); if (psfAdd.specialHandling == AdminShellPackageSupplementaryFile.SpecialHandlingType.None) { specPart.CreateRelationship(filePart.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aas-suppl"); } if (psfAdd.specialHandling == AdminShellPackageSupplementaryFile.SpecialHandlingType.EmbedAsThumbnail) { package.CreateRelationship(filePart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail"); } } // now should be able to write using (var s = filePart.GetStream(FileMode.Create)) { if (psfAdd.sourceLocalPath != null) { var bytes = System.IO.File.ReadAllBytes(psfAdd.sourceLocalPath); s.Write(bytes, 0, bytes.Length); } if (psfAdd.sourceGetBytesDel != null) { var bytes = psfAdd.sourceGetBytesDel(); if (bytes != null) { s.Write(bytes, 0, bytes.Length); } } } } } // after this, there are no more pending for add files pendingFilesToAdd.Clear(); // flush, but leave open package.Flush(); this.openPackage = package; // if in temp fn, close the package, copy to original fn, re-open the package if (this.tempFn != null) { try { package.Close(); System.IO.File.Copy(this.tempFn, this.fn, overwrite: true); this.openPackage = Package.Open(this.tempFn, FileMode.OpenOrCreate); } catch (Exception ex) { throw (new Exception(string.Format("While write AASX {0} indirectly at {1} gave: {2}", fn, AdminShellUtil.ShortLocation(ex), ex.Message))); } } } catch (Exception ex) { throw (new Exception(string.Format("While write AASX {0} at {1} gave: {2}", fn, AdminShellUtil.ShortLocation(ex), ex.Message))); } return(true); } // Don't know to handle throw (new Exception(string.Format($"Not able to handle {fn}."))); }
public XWPFStyles(PackagePart part, PackageRelationship rel) : base(part, rel) { }
//[Ignore("add relation Uri #Sheet1!A1")] public void TestCreatePackageWithCoreDocument() { MemoryStream baos = new MemoryStream(); OPCPackage pkg = OPCPackage.Create(baos); // Add a core document PackagePartName corePartName = PackagingUriHelper.CreatePartName("/xl/workbook.xml"); // Create main part relationship pkg.AddRelationship(corePartName, TargetMode.Internal, PackageRelationshipTypes.CORE_DOCUMENT, "rId1"); // Create main document part PackagePart corePart = pkg.CreatePart(corePartName, "application/vnd.Openxmlformats-officedocument.spreadsheetml.sheet.main+xml"); // Put in some dummy content Stream coreOut = corePart.GetOutputStream(); byte[] buffer = Encoding.UTF8.GetBytes("<dummy-xml />"); coreOut.Write(buffer, 0, buffer.Length); coreOut.Close(); // And another bit PackagePartName sheetPartName = PackagingUriHelper.CreatePartName("/xl/worksheets/sheet1.xml"); PackageRelationship rel = corePart.AddRelationship(sheetPartName, TargetMode.Internal, "http://schemas.Openxmlformats.org/officeDocument/2006/relationships/worksheet", "rSheet1"); Assert.IsNotNull(rel); PackagePart part = pkg.CreatePart(sheetPartName, "application/vnd.Openxmlformats-officedocument.spreadsheetml.worksheet+xml"); Assert.IsNotNull(part); // Dummy content again coreOut = corePart.GetOutputStream(); buffer = Encoding.UTF8.GetBytes("<dummy-xml2 />"); coreOut.Write(buffer, 0, buffer.Length); coreOut.Close(); //add a relationship with internal target: "#Sheet1!A1" corePart.AddRelationship(PackagingUriHelper.ToUri("#Sheet1!A1"), TargetMode.Internal, "http://schemas.Openxmlformats.org/officeDocument/2006/relationships/hyperlink", "rId2"); // Check things are as expected PackageRelationshipCollection coreRels = pkg.GetRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); Assert.AreEqual(1, coreRels.Size); PackageRelationship coreRel = coreRels.GetRelationship(0); Assert.IsNotNull(coreRel); Assert.AreEqual("/", coreRel.SourceUri.ToString()); Assert.AreEqual("/xl/workbook.xml", coreRel.TargetUri.ToString()); Assert.IsNotNull(pkg.GetPart(coreRel)); // Save and re-load pkg.Close(); FileInfo tmp = TempFile.CreateTempFile("testCreatePackageWithCoreDocument", ".zip"); FileStream fout = new FileStream(tmp.FullName, FileMode.Create, FileAccess.ReadWrite); try { buffer = baos.ToArray(); fout.Write(buffer, 0, buffer.Length); } finally { fout.Close(); } pkg = OPCPackage.Open(tmp.FullName); //tmp.Delete(); try { // Check still right coreRels = pkg.GetRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); Assert.AreEqual(1, coreRels.Size); coreRel = coreRels.GetRelationship(0); Assert.IsNotNull(coreRel); Assert.AreEqual("/", coreRel.SourceUri.ToString()); Assert.AreEqual("/xl/workbook.xml", coreRel.TargetUri.ToString()); corePart = pkg.GetPart(coreRel); Assert.IsNotNull(corePart); PackageRelationshipCollection rels = corePart.GetRelationshipsByType("http://schemas.Openxmlformats.org/officeDocument/2006/relationships/hyperlink"); Assert.AreEqual(1, rels.Size); rel = rels.GetRelationship(0); Assert.IsNotNull(rel); Assert.Warn(" 'Sheet1!A1' and rel.TargetUri.Fragment should be equal."); //Assert.AreEqual("Sheet1!A1", rel.TargetUri.Fragment); assertMSCompatibility(pkg); } finally { pkg.Close(); } Assert.AreEqual(0, Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tmp").Length, "At Last: There are no temporary files."); }