/** * Create a new child POIXMLDocumentPart * * @param descriptor the part descriptor * @param factory the factory that will create an instance of the requested relation * @param idx part number * @param noRelation if true, then no relationship is Added. * @return the Created child POIXMLDocumentPart */ protected POIXMLDocumentPart CreateRelationship(POIXMLRelation descriptor, POIXMLFactory factory, int idx, bool noRelation) { try { PackagePartName ppName = PackagingUriHelper.CreatePartName(descriptor.GetFileName(idx)); PackageRelationship rel = null; PackagePart part = packagePart.Package.CreatePart(ppName, descriptor.ContentType); if (!noRelation) { /* only add to relations, if according relationship is being Created. */ rel = packagePart.AddRelationship(ppName, TargetMode.Internal, descriptor.Relation); } POIXMLDocumentPart doc = factory.CreateDocumentPart(descriptor); doc.packageRel = rel; doc.packagePart = part; doc.parent = this; if (!noRelation) { /* only add to relations, if according relationship is being Created. */ AddRelation(rel.Id, doc); } return(doc); } catch (Exception e) { throw new POIXMLException(e); } }
public void TestAddPackageAlreadyAddAssert_Failure() { OPCPackage pkg = OPCPackage.Create("DELETEIFEXISTS.docx"); PackagePartName name1 = null; PackagePartName name2 = null; try { name1 = PackagingUriHelper.CreatePartName("/word/document.xml"); name2 = PackagingUriHelper.CreatePartName("/word/document.xml"); } catch (InvalidFormatException e) { throw new Exception(e.Message); } pkg.CreatePart(name1, ContentTypes.XML); try { pkg.CreatePart(name2, ContentTypes.XML); } catch (InvalidOperationException e) { return; } Assert.Fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); }
protected POIXMLDocumentPart CreateRelationship(POIXMLRelation descriptor, POIXMLFactory factory, int idx, bool noRelation) { try { PackagePartName partName = PackagingUriHelper.CreatePartName(descriptor.GetFileName(idx)); PackageRelationship packageRelationship = (PackageRelationship)null; PackagePart part = this.packagePart.Package.CreatePart(partName, descriptor.ContentType); if (!noRelation) { packageRelationship = this.packagePart.AddRelationship(partName, TargetMode.Internal, descriptor.Relation); } POIXMLDocumentPart documentPart = factory.CreateDocumentPart(descriptor); documentPart.packageRel = packageRelationship; documentPart.packagePart = part; documentPart.parent = this; if (!noRelation) { this.AddRelation(packageRelationship.Id, documentPart); } return(documentPart); } catch (PartAlreadyExistsException ex) { throw ex; } catch (Exception ex) { throw new POIXMLException(ex); } }
public void TestAddRelationshipRelationshipsPartAssert_Failure() { OPCPackage pkg = OPCPackage.Create("DELETEIFEXISTS.docx"); PackagePartName name1 = null; try { name1 = PackagingUriHelper .CreatePartName("/test/_rels/document.xml.rels"); } catch (InvalidFormatException e) { Assert.Fail("This exception should never happen !"); } try { pkg.AddRelationship(name1, TargetMode.Internal, PackageRelationshipTypes.CORE_DOCUMENT); } catch (InvalidOperationException e) { return; } Assert.Fail("Assert.Fail test -> M1.25: The Relationships part shall not have relationships to any other part"); }
/** * Create a new child POIXMLDocumentPart * * @param descriptor the part descriptor * @param factory the factory that will create an instance of the requested relation * @param idx part number * @param noRelation if true, then no relationship is Added. * @return the Created child POIXMLDocumentPart */ protected POIXMLDocumentPart CreateRelationship(POIXMLRelation descriptor, POIXMLFactory factory, int idx, bool noRelation) { try { PackagePartName ppName = PackagingUriHelper.CreatePartName(descriptor.GetFileName(idx)); PackageRelationship rel = null; PackagePart part = packagePart.Package.CreatePart(ppName, descriptor.ContentType); if (!noRelation) { /* only add to relations, if according relationship is being Created. */ rel = packagePart.AddRelationship(ppName, TargetMode.Internal, descriptor.Relation); } POIXMLDocumentPart doc = factory.CreateDocumentPart(descriptor); doc.packageRel = rel; doc.packagePart = part; doc.parent = this; if (!noRelation) { /* only add to relations, if according relationship is being Created. */ AddRelation(rel.Id, doc); } return(doc); } catch (PartAlreadyExistsException pae) { // Return the specific exception so the user knows // that the name is already taken throw pae; } catch (Exception e) { // Give a general wrapped exception for the problem throw new POIXMLException(e); } }
/** * Recursively copy namespace parts to the destination namespace */ private static void Copy(OPCPackage pkg, PackagePart part, OPCPackage tgt, PackagePart part_tgt) { PackageRelationshipCollection rels = part.Relationships; if(rels != null) foreach (PackageRelationship rel in rels) { PackagePart p; if(rel.TargetMode == TargetMode.External){ part_tgt.AddExternalRelationship(rel.TargetUri.ToString(), rel.RelationshipType, rel.Id); //external relations don't have associated namespace parts continue; } Uri uri = rel.TargetUri; if(uri.Fragment != null) { part_tgt.AddRelationship(uri, (TargetMode)rel.TargetMode, rel.RelationshipType, rel.Id); continue; } PackagePartName relName = PackagingUriHelper.CreatePartName(rel.TargetUri); p = pkg.GetPart(relName); part_tgt.AddRelationship(p.PartName, (TargetMode)rel.TargetMode, rel.RelationshipType, rel.Id); PackagePart dest; if(!tgt.ContainPart(p.PartName)){ dest = tgt.CreatePart(p.PartName, p.ContentType); Stream out1 = dest.GetOutputStream(); IOUtils.Copy(p.GetInputStream(), out1); out1.Close(); Copy(pkg, p, tgt, dest); } } }
public void TestRegisterPackagePictureData() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_1.docx"); /* manually assemble a new image package part*/ OPCPackage opcPckg = doc.Package; XWPFRelation jpgRelation = XWPFRelation.IMAGE_JPEG; PackagePartName partName = PackagingUriHelper.CreatePartName(jpgRelation.DefaultFileName.Replace('#', '2')); PackagePart newImagePart = opcPckg.CreatePart(partName, jpgRelation.ContentType); byte[] nature1 = XWPFTestDataSamples.GetImage("abstract4.jpg"); Stream os = newImagePart.GetOutputStream(); os.Write(nature1, 0, nature1.Length); os.Close(); XWPFHeader xwpfHeader = doc.HeaderList[(0)]; PackageRelationship relationship = xwpfHeader.GetPackagePart().AddRelationship(partName, TargetMode.Internal, jpgRelation.Relation); XWPFPictureData newPicData = new XWPFPictureData(newImagePart, relationship); /* new part is now Ready to rumble */ Assert.IsFalse(xwpfHeader.AllPictures.Contains(newPicData)); Assert.IsFalse(doc.AllPictures.Contains(newPicData)); Assert.IsFalse(doc.AllPackagePictures.Contains(newPicData)); doc.RegisterPackagePictureData(newPicData); Assert.IsFalse(xwpfHeader.AllPictures.Contains(newPicData)); Assert.IsFalse(doc.AllPictures.Contains(newPicData)); Assert.IsTrue(doc.AllPackagePictures.Contains(newPicData)); doc.Package.Revert(); }
public void TestContentTypeRemoval() { ContentTypeManager ctm = new ZipContentTypeManager(null, null); PackagePartName name1 = PackagingUriHelper.CreatePartName("/foo/foo.xml"); PackagePartName name2 = PackagingUriHelper.CreatePartName("/foo/foo2.xml"); PackagePartName name3 = PackagingUriHelper.CreatePartName("/foo/doc.rels"); PackagePartName name4 = PackagingUriHelper.CreatePartName("/foo/doc.RELS"); // Add content types ctm.AddContentType(name1, "foo-type1"); ctm.AddContentType(name2, "foo-type2"); ctm.AddContentType(name3, "text/xml+rel"); ctm.AddContentType(name4, "text/xml+rel"); ctm.RemoveContentType(name2); ctm.RemoveContentType(name3); Assert.AreEqual(ctm.GetContentType(name1), "foo-type1"); Assert.AreEqual(ctm.GetContentType(name2), "foo-type1"); Assert.AreEqual(ctm.GetContentType(name3), null); ctm.RemoveContentType(name1); Assert.AreEqual(ctm.GetContentType(name1), null); Assert.AreEqual(ctm.GetContentType(name2), null); }
static void Main(string[] args) { //create ooxml file in memory Package p = Package.Create(); //create package parts PackagePartName pn1 = new PackagePartName(new Uri("/a/abcd/e", UriKind.Relative), true); if (!p.ContainPart(pn1)) { p.CreatePart(pn1, MediaTypeNames.Text.Plain); } PackagePartName pn2 = new PackagePartName(new Uri("/b/test.xml", UriKind.Relative), true); if (!p.ContainPart(pn2)) { p.CreatePart(pn2, MediaTypeNames.Text.Xml); } //save file p.Save("test.zip"); //don't forget to close it p.Close(); }
public void TestOpenPackage() { FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestOpenPackageTMP.docx"); FileInfo inputFile = OpenXml4NetTestDataSamples.GetSampleFile("TestOpenPackageINPUT.docx"); FileInfo expectedFile = OpenXml4NetTestDataSamples.GetSampleFile("TestOpenPackageOUTPUT.docx"); // Copy the input file in the output directory FileHelper.CopyFile(inputFile.FullName, targetFile.FullName); // Create a namespace OPCPackage pkg = OPCPackage.Open(targetFile.FullName); // Modify core part PackagePartName corePartName = PackagingUriHelper .CreatePartName("/word/document.xml"); PackagePart corePart = pkg.GetPart(corePartName); // Delete some part to have a valid document foreach (PackageRelationship rel in corePart.Relationships) { corePart.RemoveRelationship(rel.Id); pkg.RemovePart(PackagingUriHelper.CreatePartName(PackagingUriHelper .ResolvePartUri(corePart.PartName.URI, rel .TargetUri))); } //// Create a content //Document doc = DocumentHelper.CreateDocument(); //Namespace nsWordProcessinML = new Namespace("w", // "http://schemas.openxmlformats.org/wordProcessingml/2006/main"); //Element elDocument = doc.AddElement(new QName("document", // nsWordProcessinML)); //Element elBody = elDocument.AddElement(new QName("body", // nsWordProcessinML)); //Element elParagraph = elBody.AddElement(new QName("p", // nsWordProcessinML)); //Element elRun = elParagraph // .AddElement(new QName("r", nsWordProcessinML)); //Element elText = elRun.AddElement(new QName("t", nsWordProcessinML)); //elText.SetText("Hello Open XML !"); //StreamHelper.saveXmlInStream(doc, corePart.GetOutputStream()); //// Save and close //try //{ // pkg.Close(); //} //catch (IOException e) //{ // Assert.Fail(); //} //ZipFileAssert.AssertEqual(expectedFile, targetFile); //File.Delete(targetFile.FullName); }
public void TestGetExtension() { PackagePartName name1 = PackagingUriHelper.CreatePartName("/doc/props/document.xml"); PackagePartName name2 = PackagingUriHelper.CreatePartName("/root/document"); Assert.AreEqual("xml", name1.Extension); Assert.AreEqual("", name2.Extension); }
/** * Add an override content type for a specific part. * * @param partName * Name of the part. * @param contentType * Content type of the part. */ private void AddOverrideContentType(PackagePartName partName, String contentType) { if (overrideContentType == null) { overrideContentType = new SortedList <PackagePartName, String>(); } overrideContentType.Add(partName, contentType); }
public void TestCreatePackageAddPart() { FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestCreatePackageTMP.docx"); FileInfo expectedFile = OpenXml4NetTestDataSamples.GetSampleFile("TestCreatePackageOUTPUT.docx"); // Zap the target file, in case of an earlier run if (targetFile.Exists) { targetFile.Delete(); targetFile.Refresh(); Assert.IsFalse(targetFile.Exists); } // Create a namespace OPCPackage pkg = OPCPackage.Create(targetFile.FullName); PackagePartName corePartName = PackagingUriHelper .CreatePartName("/word/document.xml"); pkg.AddRelationship(corePartName, TargetMode.Internal, PackageRelationshipTypes.CORE_DOCUMENT, "rId1"); PackagePart corePart = pkg .CreatePart( corePartName, "application/vnd.openxmlformats-officedocument.wordProcessingml.document.main+xml"); XmlDocument doc = new XmlDocument(); XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable); string wuri = "http://schemas.openxmlformats.org/wordProcessingml/2006/main"; mgr.AddNamespace("w", wuri); XmlElement elDocument = doc.CreateElement("w:document", wuri); doc.AppendChild(elDocument); XmlElement elBody = doc.CreateElement("w:body", wuri); elDocument.AppendChild(elBody); XmlElement elParagraph = doc.CreateElement("w:p", wuri); elBody.AppendChild(elParagraph); XmlElement elRun = doc.CreateElement("w:r", wuri); elParagraph.AppendChild(elRun); XmlElement elText = doc.CreateElement("w:t", wuri); elRun.AppendChild(elText); elText.InnerText = ("Hello Open XML !"); StreamHelper.SaveXmlInStream(doc, corePart.GetOutputStream()); pkg.Close(); ZipFileAssert.AssertEqual(expectedFile, targetFile); File.Delete(targetFile.FullName); }
public int GetNextPicNameNumber(int format) { int index = this.AllPackagePictures.Count + 1; for (PackagePartName partName = PackagingUriHelper.CreatePartName(XWPFPictureData.RELATIONS[format].GetFileName(index)); this.Package.GetPart(partName) != null; partName = PackagingUriHelper.CreatePartName(XWPFPictureData.RELATIONS[format].GetFileName(index))) { ++index; } return(index); }
//public XSSFChart CreateChart(IClientAnchor anchor) //{ // return CreateChart((XSSFClientAnchor)anchor); //} /** * Add the indexed picture to this Drawing relations * * @param pictureIndex the index of the picture in the workbook collection of pictures, * {@link NPOI.xssf.usermodel.XSSFWorkbook#getAllPictures()} . */ internal PackageRelationship AddPictureReference(int pictureIndex) { XSSFWorkbook wb = (XSSFWorkbook)GetParent().GetParent(); XSSFPictureData data = (XSSFPictureData)wb.GetAllPictures()[pictureIndex]; PackagePartName ppName = data.GetPackagePart().PartName; PackageRelationship rel = GetPackagePart().AddRelationship(ppName, TargetMode.Internal, XSSFRelation.IMAGES.Relation); AddRelation(rel.Id, new XSSFPictureData(data.GetPackagePart(), rel)); return(rel); }
/** * Save the specified part. * * @throws OpenXml4NetException * Throws if an internal exception is thrown. */ public bool Marshall(PackagePart part, Stream os) { if (!(os is ZipOutputStream)) { logger.Log(POILogger.ERROR, "Unexpected class " + os.GetType().Name); throw new OpenXml4NetException("ZipOutputStream expected !"); // Normally should happen only in developement phase, so just throw // exception } ZipOutputStream zos = (ZipOutputStream)os; string name = ZipHelper .GetZipItemNameFromOPCName(part.PartName.URI .OriginalString); ZipEntry partEntry = new ZipEntry(name); try { // Create next zip entry zos.PutNextEntry(partEntry); // Saving data in the ZIP file Stream ins = part.GetInputStream(); byte[] buff = new byte[ZipHelper.READ_WRITE_FILE_BUFFER_SIZE]; int totalRead = 0; while (true) { int resultRead = ins.Read(buff, 0, buff.Length); if (resultRead == 0) { // End of file reached break; } zos.Write(buff, 0, resultRead); totalRead += resultRead; } zos.CloseEntry(); } catch (IOException ioe) { logger.Log(POILogger.ERROR, "Cannot write: " + part.PartName + ": in ZIP", ioe); return(false); } // Saving relationship part if (part.HasRelationships) { PackagePartName relationshipPartName = PackagingUriHelper .GetRelationshipPartName(part.PartName); MarshallRelationshipPart(part.Relationships, relationshipPartName, zos); } return(true); }
/** * Get the PackagePart that is the target of a relationship. * * @param rel The relationship * @param pkg The namespace to fetch from * @return The target part * @throws InvalidFormatException */ protected static PackagePart GetTargetPart(OPCPackage pkg, PackageRelationship rel) { PackagePartName relName = PackagingUriHelper.CreatePartName(rel.TargetUri); PackagePart part = pkg.GetPart(relName); if (part == null) { throw new ArgumentException("No part found for relationship " + rel); } return(part); }
public Stream GetContents(PackagePart corePart) { IEnumerator <PackageRelationship> enumerator = corePart.GetRelationshipsByType(this._relation).GetEnumerator(); if (enumerator.MoveNext()) { PackagePartName partName = PackagingUriHelper.CreatePartName(enumerator.Current.TargetUri); return(corePart.Package.GetPart(partName).GetInputStream()); } XSSFRelation.log.Log(5, (object)("No part " + this._defaultName + " found")); return((Stream)null); }
public void TestPartNameComparaisonFailure() { String[] partName1 = { "/word/document.xml", "/docProps/core.xml", "/rels/.rels" }; String[] partName2 = { "/WORD/DocUment.XML2", "/docProp/core.xml", "/rels/rels" }; for (int i = 0; i < partName1.Length || i < partName2.Length; ++i) { PackagePartName p1 = PackagingUriHelper.CreatePartName(partName1[i]); PackagePartName p2 = PackagingUriHelper.CreatePartName(partName2[i]); Assert.IsFalse(p1.Equals(p2)); Assert.IsFalse(p1.CompareTo(p2) == 0); Assert.IsFalse(p1.GetHashCode() == p2.GetHashCode()); } }
/** * Add a new child POIXMLDocumentPart * * @param relId the preferred relation id, when null the next free relation id will be used * @param relationshipType the package relationship type * @param part the child to add * * @since 3.14-Beta1 */ public RelationPart AddRelation(String relId, POIXMLRelation relationshipType, POIXMLDocumentPart part) { PackageRelationship pr = FindExistingRelation(part); if (pr == null) { PackagePartName ppn = part.GetPackagePart().PartName; String relType = relationshipType.Relation; pr = packagePart.AddRelationship(ppn, TargetMode.Internal, relType, relId); } AddRelation(pr, part); return(new RelationPart(pr, part)); }
/** * Constructor. * * @param pack * Parent package. * @param partName * The part name, relative to the parent Package root. * @param contentType * The content type. * @param loadRelationships * Specify if the relationships will be loaded * @throws InvalidFormatException * If the specified URI is not valid. */ protected PackagePart(OPCPackage pack, PackagePartName partName, ContentType contentType, bool loadRelationships) { this.partName = partName; this.contentType = contentType; this.container = (ZipPackage)pack; // TODO - enforcing ZipPackage here - perhaps should change constructor signature // Check if this part is a relationship part isRelationshipPart = this.partName.IsRelationshipPartURI(); // Load relationships if any if (loadRelationships) LoadRelationships(); }
public virtual void Commit() { if (this.extPart == null) { if (!POIXMLProperties.NEW_EXT_INSTANCE.ToString().Equals(this.ext.props.ToString())) { try { PackagePartName partName = PackagingUriHelper.CreatePartName("/docProps/app.xml"); this.pkg.AddRelationship(partName, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"); this.extPart = this.pkg.CreatePart(partName, "application/vnd.openxmlformats-officedocument.extended-properties+xml"); } catch (InvalidFormatException ex) { throw new POIXMLException((Exception)ex); } } } if (this.custPart == null) { if (!POIXMLProperties.NEW_CUST_INSTANCE.ToString().Equals(this.cust.props.ToString())) { try { PackagePartName partName = PackagingUriHelper.CreatePartName("/docProps/custom.xml"); this.pkg.AddRelationship(partName, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties"); this.custPart = this.pkg.CreatePart(partName, "application/vnd.openxmlformats-officedocument.custom-properties+xml"); } catch (InvalidFormatException ex) { throw new POIXMLException((Exception)ex); } } } if (this.extPart != null) { Stream outputStream = this.extPart.GetOutputStream(); this.ext.props.Save(outputStream); outputStream.Close(); } if (this.custPart == null) { return; } Stream outputStream1 = this.custPart.GetOutputStream(); this.cust.props.Save(outputStream1); outputStream1.Close(); }
static void Main(string[] args) { OPCPackage p = OPCPackage.Open("test.zip", PackageAccess.READ_WRITE); PackagePartName pn3 = new PackagePartName(new Uri("/c.xml", UriKind.Relative), true); if (!p.ContainPart(pn3)) p.CreatePart(pn3, MediaTypeNames.Text.Xml); //save file p.Save("test1.zip"); //don't forget to close it p.Close(); }
public void Main() { OPCPackage p = OPCPackage.Open("test.zip", PackageAccess.READ_WRITE); PackagePartName pn3 = new PackagePartName(new Uri("/c.xml", UriKind.Relative), true); //if (!p.ContainPart(pn3)) // p.CreatePart(pn3, MediaTypeNames.Text.Xml); //save file p.Save("test1.zip"); //don't forget to close it p.Close(); }
public string AddPictureData(byte[] pictureData, int format) { XWPFPictureData packagePictureData = this.document.FindPackagePictureData(pictureData, format); POIXMLRelation descriptor = XWPFPictureData.RELATIONS[format]; if (packagePictureData == null) { int nextPicNameNumber = this.document.GetNextPicNameNumber(format); XWPFPictureData relationship = (XWPFPictureData)this.CreateRelationship(descriptor, (POIXMLFactory)XWPFFactory.GetInstance(), nextPicNameNumber); PackagePart packagePart = relationship.GetPackagePart(); Stream stream = (Stream)null; try { stream = packagePart.GetOutputStream(); stream.Write(pictureData, 0, pictureData.Length); } catch (IOException ex) { throw new POIXMLException((Exception)ex); } finally { try { stream.Close(); } catch (IOException ex) { } } this.document.RegisterPackagePictureData(relationship); this.pictures.Add(relationship); return(this.GetRelationId((POIXMLDocumentPart)relationship)); } if (this.GetRelations().Contains((POIXMLDocumentPart)packagePictureData)) { return(this.GetRelationId((POIXMLDocumentPart)packagePictureData)); } PackagePart packagePart1 = packagePictureData.GetPackagePart(); TargetMode targetMode = TargetMode.Internal; PackagePartName partName = packagePart1.PartName; string relation = descriptor.Relation; string id = this.GetPackagePart().AddRelationship(partName, targetMode, relation).Id; this.AddRelation(id, (POIXMLDocumentPart)packagePictureData); this.pictures.Add(packagePictureData); return(id); }
/** * Build association extention-> content type (will be stored in * [Content_Types].xml) for example ContentType="image/png" Extension="png" * <p> * [M2.8]: When adding a new part to a package, the package implementer * shall ensure that a content type for that part is specified in the * Content Types stream; the package implementer shall perform the steps * described in §9.1.2.3: * </p><p> * 1. Get the extension from the part name by taking the substring to the * right of the rightmost occurrence of the dot character (.) from the * rightmost segment. * </p><p> * 2. If a part name has no extension, a corresponding Override element * shall be added to the Content Types stream. * </p><p> * 3. Compare the resulting extension with the values specified for the * Extension attributes of the Default elements in the Content Types stream. * The comparison shall be case-insensitive ASCII. * </p><p> * 4. If there is a Default element with a matching Extension attribute, * then the content type of the new part shall be compared with the value of * the ContentType attribute. The comparison might be case-sensitive and * include every character regardless of the role it plays in the * content-type grammar of RFC 2616, or it might follow the grammar of RFC * 2616. * </p><p> * a. If the content types match, no further action is required. * </p><p> * b. If the content types do not match, a new Override element shall be * added to the Content Types stream. . * </p><p> * 5. If there is no Default element with a matching Extension attribute, a * new Default element or Override element shall be added to the Content * Types stream. * </p> */ public void AddContentType(PackagePartName partName, String contentType) { bool defaultCTExists = false; String extension = partName.Extension.ToLower(); if ((extension.Length == 0) || (this.defaultContentType.ContainsKey(extension) && !(defaultCTExists = this.defaultContentType .ContainsValue(contentType)))) { this.AddOverrideContentType(partName, contentType); } else if (!defaultCTExists) { this.AddDefaultContentType(extension, contentType); } }
/** * Fetches the InputStream to read the contents, based * of the specified core part, for which we are defined * as a suitable relationship */ public Stream GetContents(PackagePart corePart) { PackageRelationshipCollection prc = corePart.GetRelationshipsByType(_relation); IEnumerator <PackageRelationship> it = prc.GetEnumerator(); if (it.MoveNext()) { PackageRelationship rel = it.Current; PackagePartName relName = PackagingUriHelper.CreatePartName(rel.TargetUri); PackagePart part = corePart.Package.GetPart(relName); return(part.GetInputStream()); } log.Log(POILogger.WARN, "No part " + _defaultName + " found"); return(null); }
protected static OPCPackage newPackage() { try { OPCPackage opcPackage = OPCPackage.Create((Stream) new MemoryStream()); PackagePartName partName = PackagingUriHelper.CreatePartName(XSSFRelation.WORKBOOK.DefaultFileName); opcPackage.AddRelationship(partName, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"); opcPackage.CreatePart(partName, XSSFRelation.WORKBOOK.ContentType); opcPackage.GetPackageProperties().SetCreatorProperty(POIXMLDocument.DOCUMENT_CREATOR); return(opcPackage); } catch (Exception ex) { throw new POIXMLException(ex); } }
/** * Add an override content type for a specific part. * * @param partName * Name of the part. * @param contentType * Content type of the part. */ private void AddOverrideContentType(PackagePartName partName, String contentType) { if (overrideContentType == null) { overrideContentType = new SortedList <PackagePartName, String>(); } if (!overrideContentType.ContainsKey(partName)) { overrideContentType.Add(partName, contentType); } else { overrideContentType[partName] = contentType; } }
/** * Commit Changes to the underlying OPC namespace */ public virtual void Commit() { if (extPart == null && !NEW_EXT_INSTANCE.ToString().Equals(ext.props.ToString())) { try { PackagePartName prtname = PackagingUriHelper.CreatePartName("/docProps/app.xml"); pkg.AddRelationship(prtname, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"); extPart = pkg.CreatePart(prtname, "application/vnd.openxmlformats-officedocument.extended-properties+xml"); } catch (InvalidFormatException e) { throw new POIXMLException(e); } } if (custPart == null && !NEW_CUST_INSTANCE.ToString().Equals(cust.props.ToString())) { try { PackagePartName prtname = PackagingUriHelper.CreatePartName("/docProps/custom.xml"); pkg.AddRelationship(prtname, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties"); custPart = pkg.CreatePart(prtname, "application/vnd.openxmlformats-officedocument.custom-properties+xml"); } catch (InvalidFormatException e) { throw new POIXMLException(e); } } if (extPart != null) { Stream out1 = extPart.GetOutputStream(); if (extPart.Size > 0) { extPart.Clear(); } ext.props.Save(out1); out1.Dispose(); } if (custPart != null) { Stream out1 = custPart.GetOutputStream(); cust.props.Save(out1); out1.Dispose(); } }
public void TestCreatePackageAddPart() { FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestCreatePackageTMP.docx"); FileInfo expectedFile = OpenXml4NetTestDataSamples.GetSampleFile("TestCreatePackageOUTPUT.docx"); // Zap the target file, in case of an earlier run if (targetFile.Exists) { targetFile.Delete(); } // Create a namespace OPCPackage pkg = OPCPackage.Create(targetFile.FullName); PackagePartName corePartName = PackagingUriHelper .CreatePartName("/word/document.xml"); pkg.AddRelationship(corePartName, TargetMode.Internal, PackageRelationshipTypes.CORE_DOCUMENT, "rId1"); PackagePart corePart = pkg .CreatePart( corePartName, "application/vnd.openxmlformats-officedocument.wordProcessingml.document.main+xml"); //Document doc = DocumentHelper.CreateDocument(); //Namespace nsWordProcessinML = new Namespace("w", // "http://schemas.openxmlformats.org/wordProcessingml/2006/main"); //Element elDocument = doc.AddElement(new QName("document", // nsWordProcessinML)); //Element elBody = elDocument.AddElement(new QName("body", // nsWordProcessinML)); //Element elParagraph = elBody.AddElement(new QName("p", // nsWordProcessinML)); //Element elRun = elParagraph // .AddElement(new QName("r", nsWordProcessinML)); //Element elText = elRun.AddElement(new QName("t", nsWordProcessinML)); //elText.SetText("Hello Open XML !"); //StreamHelper.SaveXmlInStream(doc, corePart.GetOutputStream()); //pkg.Close(); //ZipFileAssert.AssertEqual(expectedFile, targetFile); //File.Delete(targetFile.FullName); }
private void assertMSCompatibility(OPCPackage pkg) { PackagePartName relName = PackagingUriHelper.CreatePartName(PackageRelationship.ContainerPartRelationship); PackagePart relPart = pkg.GetPart(relName); XmlDocument xmlRelationshipsDoc = DocumentHelper.LoadDocument(relPart.GetInputStream()); XmlElement root = xmlRelationshipsDoc.DocumentElement; XmlNodeList nodeList = root.GetElementsByTagName(PackageRelationship.RELATIONSHIP_TAG_NAME); int nodeCount = nodeList.Count; for (int i = 0; i < nodeCount; i++) { XmlElement element = (XmlElement)nodeList.Item(i); String value = element.GetAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME); Assert.IsTrue(value[0] != '/', "Root target must not start with a leading slash ('/'): " + value); } }
static void Main(string[] args) { //create ooxml file in memory Package p = Package.Create(); //create package parts PackagePartName pn1=new PackagePartName(new Uri("/a/abcd/e",UriKind.Relative),true); if (!p.ContainPart(pn1)) p.CreatePart(pn1, MediaTypeNames.Text.Plain); PackagePartName pn2 = new PackagePartName(new Uri("/b/test.xml", UriKind.Relative), true); if (!p.ContainPart(pn2)) p.CreatePart(pn2, MediaTypeNames.Text.Xml); //save file p.Save("test.zip"); //don't forget to close it p.Close(); }
/** * Constructor. * * @param pack * Parent package. * @param partName * The part name, relative to the parent Package root. * @param contentType * The content type. * @throws InvalidFormatException * If the specified URI is not valid. */ protected PackagePart(OPCPackage pack, PackagePartName partName, ContentType contentType) : this(pack, partName, contentType, true) { }
/** * Delete the part with the specified name and its associated relationships * part if one exists. Prefer the use of this method to delete a part in the * package, compare to the Remove() methods that don't Remove associated * relationships part. * * @param PartName * Name of the part to delete */ public void DeletePart(PackagePartName partName) { if (partName == null) throw new ArgumentException("PartName"); // Remove the part this.RemovePart(partName); // Remove the relationships part this.RemovePart(PackagingUriHelper.GetRelationshipPartName(partName)); }
/** * Add a relationship to a part (except relationships part). * * @param targetPartName * Name of the target part. This one must be relative to the * source root directory of the part. * @param targetMode * Mode [Internal|External]. * @param relationshipType * Type of relationship. * @return The newly created and added relationship * @see org.apache.poi.OpenXml4Net.opc.RelationshipSource#AddRelationship(org.apache.poi.OpenXml4Net.opc.PackagePartName, * org.apache.poi.OpenXml4Net.opc.TargetMode, java.lang.String) */ public PackageRelationship AddRelationship(PackagePartName targetPartName, TargetMode targetMode, String relationshipType) { return AddRelationship(targetPartName, targetMode, relationshipType, null); }
/** * Add a relationship to a part (except relationships part). * <p> * Check rule M1.25: The Relationships part shall not have relationships to * any other part. Package implementers shall enforce this requirement upon * the attempt to create such a relationship and shall treat any such * relationship as invalid. * </p> * @param targetPartName * Name of the target part. This one must be relative to the * source root directory of the part. * @param targetMode * Mode [Internal|External]. * @param relationshipType * Type of relationship. * @param id * Relationship unique id. * @return The newly created and added relationship * * @throws InvalidFormatException * If the URI point to a relationship part URI. * @see org.apache.poi.OpenXml4Net.opc.RelationshipSource#AddRelationship(org.apache.poi.OpenXml4Net.opc.PackagePartName, * org.apache.poi.OpenXml4Net.opc.TargetMode, java.lang.String, java.lang.String) */ public PackageRelationship AddRelationship(PackagePartName targetPartName, TargetMode targetMode, String relationshipType, String id) { container.ThrowExceptionIfReadOnly(); if (targetPartName == null) { throw new ArgumentException("targetPartName"); } //if (targetMode == null) //{ // throw new ArgumentException("targetMode"); //} if (relationshipType == null) { throw new ArgumentException("relationshipType"); } if (this.IsRelationshipPart || targetPartName.IsRelationshipPartURI()) { throw new InvalidOperationException( "Rule M1.25: The Relationships part shall not have relationships to any other part."); } if (relationships == null) { relationships = new PackageRelationshipCollection(); } return relationships.AddRelationship(targetPartName.URI, targetMode, relationshipType, id); }
/** * Remove a part in this package. If this part is relationship part, then * delete all relationships in the source part. * * @param PartName * The part name of the part to Remove. */ public void RemovePart(PackagePartName PartName) { ThrowExceptionIfReadOnly(); if (PartName == null || !this.ContainPart(PartName)) throw new ArgumentException("PartName"); // Delete the specified part from the package. if (this.partList.ContainsKey(PartName)) { this.partList[PartName].IsDeleted = (true); this.RemovePartImpl(PartName); this.partList.Remove(PartName); } else { this.RemovePartImpl(PartName); } // Delete content type this.contentTypeManager.RemoveContentType(PartName); // If this part is a relationship part, then delete all relationships of // the source part. if (PartName.IsRelationshipPartURI()) { Uri sourceURI = PackagingUriHelper .GetSourcePartUriFromRelationshipPartUri(PartName.URI); PackagePartName sourcePartName; try { sourcePartName = PackagingUriHelper.CreatePartName(sourceURI); } catch (InvalidFormatException) { logger .Log(POILogger.ERROR, "Part name URI '" + sourceURI + "' is not valid ! This message is not intended to be displayed !"); return; } if (sourcePartName.URI.Equals( PackagingUriHelper.PACKAGE_ROOT_URI)) { ClearRelationships(); } else if (ContainPart(sourcePartName)) { PackagePart part = GetPart(sourcePartName); if (part != null) part.ClearRelationships(); } } this.isDirty = true; }
/** * Constructor. * * @param pack * Parent package. * @param partName * The part name, relative to the parent Package root. * @param contentType * The Multipurpose Internet Mail Extensions (MIME) content type * of the part's data stream. */ public PackagePart(OPCPackage pack, PackagePartName partName, String contentType) : this(pack, partName, new ContentType(contentType)) { }
/* Static initialization */ static PackagingUriHelper() { RELATIONSHIP_PART_SEGMENT_NAME = "_rels"; RELATIONSHIP_PART_EXTENSION_NAME = ".rels"; FORWARD_SLASH_CHAR = '/'; FORWARD_SLASH_STRING = "/"; PACKAGE_PROPERTIES_SEGMENT_NAME = "docProps"; PACKAGE_CORE_PROPERTIES_NAME = "core.xml"; // Make Uri Uri uriPACKAGE_ROOT_URI = null; Uri uriPACKAGE_RELATIONSHIPS_ROOT_URI = null; Uri uriPACKAGE_PROPERTIES_URI = null; uriPACKAGE_ROOT_URI = new Uri("/",UriKind.Relative); uriPACKAGE_RELATIONSHIPS_ROOT_URI = new Uri(FORWARD_SLASH_CHAR + RELATIONSHIP_PART_SEGMENT_NAME + FORWARD_SLASH_CHAR + RELATIONSHIP_PART_EXTENSION_NAME, UriKind.Relative); packageRootUri = new Uri("/", UriKind.Relative); uriPACKAGE_PROPERTIES_URI = new Uri(FORWARD_SLASH_CHAR + PACKAGE_PROPERTIES_SEGMENT_NAME + FORWARD_SLASH_CHAR + PACKAGE_CORE_PROPERTIES_NAME, UriKind.Relative); PACKAGE_ROOT_URI = uriPACKAGE_ROOT_URI; PACKAGE_RELATIONSHIPS_ROOT_URI = uriPACKAGE_RELATIONSHIPS_ROOT_URI; CORE_PROPERTIES_URI = uriPACKAGE_PROPERTIES_URI; // Make part name from previous Uri PackagePartName tmpPACKAGE_ROOT_PART_NAME = null; PackagePartName tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME = null; PackagePartName tmpCORE_PROPERTIES_URI = null; try { tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME = CreatePartName(PACKAGE_RELATIONSHIPS_ROOT_URI); tmpCORE_PROPERTIES_URI = CreatePartName(CORE_PROPERTIES_URI); tmpPACKAGE_ROOT_PART_NAME = new PackagePartName(PACKAGE_ROOT_URI, false); } catch (InvalidFormatException) { // Should never happen in production as all data are fixed } PACKAGE_RELATIONSHIPS_ROOT_PART_NAME = tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME; CORE_PROPERTIES_PART_NAME = tmpCORE_PROPERTIES_URI; PACKAGE_ROOT_PART_NAME = tmpPACKAGE_ROOT_PART_NAME; }
/** * Check if a part already exists in this package from its name. * * @param PartName * Part name to check. * @return <i>true</i> if the part is logically Added to this package, else * <i>false</i>. */ public bool ContainPart(PackagePartName partName) { return (this.GetPart(partName) != null); }
/** * <p> * Delete a content type based on the specified part name. If the specified * part name is register with an override content type, then this content * type is remove, else the content type is remove in the default content * type list if it exists and if no part is associated with it yet. * </p><p> * Check rule M2.4: The package implementer shall require that the Content * Types stream contain one of the following for every part in the package: * One matching Default element One matching Override element Both a * matching Default element and a matching Override element, in which case * the Override element takes precedence. * </p> * @param partName * The part URI associated with the override content type to * delete. * @exception InvalidOperationException * Throws if */ public void RemoveContentType(PackagePartName partName) { if (partName == null) throw new ArgumentException("partName"); /* Override content type */ if (this.overrideContentType != null && this.overrideContentType.ContainsKey(partName)) { // Remove the override definition for the specified part. this.overrideContentType.Remove(partName); return; } /* Default content type */ String extensionToDelete = partName.Extension; bool deleteDefaultContentTypeFlag = true; if (this.container != null) { try { foreach (PackagePart part in this.container.GetParts()) { if (!part.PartName.Equals(partName) && part.PartName.Extension .Equals(extensionToDelete, StringComparison.InvariantCultureIgnoreCase)) { deleteDefaultContentTypeFlag = false; break; } } } catch (InvalidFormatException e) { throw new InvalidOperationException(e.Message); } } // Remove the default content type, no other part use this content type. if (deleteDefaultContentTypeFlag) { this.defaultContentType.Remove(extensionToDelete); } /* * Check rule 2.4: The package implementer shall require that the * Content Types stream contain one of the following for every part in * the package: One matching Default element One matching Override * element Both a matching Default element and a matching Override * element, in which case the Override element takes precedence. */ if (this.container != null) { try { foreach (PackagePart part in this.container.GetParts()) { if (!part.PartName.Equals(partName) && this.GetContentType(part.PartName) == null) throw new InvalidOperationException( "Rule M2.4 is not respected: Nor a default element or override element is associated with the part: " + part.PartName.Name); } } catch (InvalidFormatException e) { throw new InvalidOperationException(e.Message); } } }
/** * Core method to Create a package part. This method must be implemented by * the subclass. * * @param PartName * URI of the part to Create. * @param contentType * Content type of the part to Create. * @return The newly Created package part. */ protected abstract PackagePart CreatePartImpl(PackagePartName PartName, String contentType, bool loadRelationships);
/** * Add an override content type for a specific part. * * @param partName * Name of the part. * @param contentType * Content type of the part. */ private void AddOverrideContentType(PackagePartName partName, String contentType) { if (overrideContentType == null) overrideContentType = new SortedList<PackagePartName, String>(); if(!overrideContentType.ContainsKey(partName)) overrideContentType.Add(partName, contentType); else overrideContentType[partName]= contentType; }
/** * Build association extention-> content type (will be stored in * [Content_Types].xml) for example ContentType="image/png" Extension="png" * <p> * [M2.8]: When adding a new part to a package, the package implementer * shall ensure that a content type for that part is specified in the * Content Types stream; the package implementer shall perform the steps * described in §9.1.2.3: * </p><p> * 1. Get the extension from the part name by taking the substring to the * right of the rightmost occurrence of the dot character (.) from the * rightmost segment. * </p><p> * 2. If a part name has no extension, a corresponding Override element * shall be added to the Content Types stream. * </p><p> * 3. Compare the resulting extension with the values specified for the * Extension attributes of the Default elements in the Content Types stream. * The comparison shall be case-insensitive ASCII. * </p><p> * 4. If there is a Default element with a matching Extension attribute, * then the content type of the new part shall be compared with the value of * the ContentType attribute. The comparison might be case-sensitive and * include every character regardless of the role it plays in the * content-type grammar of RFC 2616, or it might follow the grammar of RFC * 2616. * </p><p> * a. If the content types match, no further action is required. * </p><p> * b. If the content types do not match, a new Override element shall be * added to the Content Types stream. . * </p><p> * 5. If there is no Default element with a matching Extension attribute, a * new Default element or Override element shall be added to the Content * Types stream. * </p> */ public void AddContentType(PackagePartName partName, String contentType) { bool defaultCTExists = false; String extension = partName.Extension.ToLower(); if ((extension.Length == 0) || (this.defaultContentType.ContainsKey(extension) && !(defaultCTExists = this.defaultContentType .ContainsValue(contentType)))) this.AddOverrideContentType(partName, contentType); else if (!defaultCTExists) this.AddDefaultContentType(extension, contentType); }
/** * Constructor. * * @param pack * Container package. * @param partName * Name of this part. * @throws InvalidFormatException * Throws if the content is invalid. */ public PackagePropertiesPart(OPCPackage pack, PackagePartName partName) :base(pack, partName, ContentTypes.CORE_PROPERTIES_PART) { }
public void DeletePart(Uri uri) { PackagePartName partName = new PackagePartName(uri.ToString(), true); if (partName == null) throw new ArgumentException("PartName"); // Remove the part this.RemovePart(partName); // Remove the relationships part this.RemovePart(PackagingUriHelper.GetRelationshipPartName(partName)); }
/** * Core method to delete a package part. This method must be implemented by * the subclass. * * @param PartName * The URI of the part to delete. */ protected abstract void RemovePartImpl(PackagePartName PartName);
/** * Get the content type for the specified part, if any. * <p> * Rule [M2.9]: To get the content type of a part, the package implementer * shall perform the steps described in §9.1.2.4: * </p><p> * 1. Compare the part name with the values specified for the PartName * attribute of the Override elements. The comparison shall be * case-insensitive ASCII. * </p><p> * 2. If there is an Override element with a matching PartName attribute, * return the value of its ContentType attribute. No further action is * required. * </p><p> * 3. If there is no Override element with a matching PartName attribute, * then a. Get the extension from the part name by taking the substring to * the right of the rightmost occurrence of the dot character (.) from the * rightmost segment. b. Check the Default elements of the Content Types * stream, comparing the extension with the value of the Extension * attribute. The comparison shall be case-insensitive ASCII. * </p><p> * 4. If there is a Default element with a matching Extension attribute, * return the value of its ContentType attribute. No further action is * required. * </p><p> * 5. If neither Override nor Default elements with matching attributes are * found for the specified part name, the implementation shall not map this * part name to a part. * </p> * @param partName * The URI part to check. * @return The content type associated with the URI (in case of an override * content type) or the extension (in case of default content type), * else <code>null</code>. * * @exception OpenXml4NetRuntimeException * Throws if the content type manager is not able to find the * content from an existing part. */ public String GetContentType(PackagePartName partName) { if (partName == null) throw new ArgumentException("partName"); if ((this.overrideContentType != null) && this.overrideContentType.ContainsKey(partName)) return this.overrideContentType[partName]; String extension = partName.Extension.ToLower(); if (this.defaultContentType.ContainsKey(extension)) return this.defaultContentType[extension]; /* * [M2.4] : The package implementer shall require that the Content Types * stream contain one of the following for every part in the package: * One matching Default element, One matching Override element, Both a * matching Default element and a matching Override element, in which * case the Override element takes precedence. */ if (this.container != null && this.container.GetPart(partName) != null) { throw new OpenXml4NetException( "Rule M2.4 exception : this error should NEVER happen, if so please send a mail to the developers team, thanks !"); } else { return null; } }
/** * Add a relationship to the package (except relationships part). * * Check rule M4.1 : The format designer shall specify and the format * producer shall Create at most one core properties relationship for a * package. A format consumer shall consider more than one core properties * relationship for a package to be an error. If present, the relationship * shall target the Core Properties part. * * Check rule M1.25: The Relationships part shall not have relationships to * any other part. Package implementers shall enforce this requirement upon * the attempt to Create such a relationship and shall treat any such * relationship as invalid. * * @param targetPartName * Target part name. * @param targetMode * Target mode, either Internal or External. * @param relationshipType * Relationship type. * @param relID * ID of the relationship. * @see PackageRelationshipTypes */ public PackageRelationship AddRelationship(PackagePartName targetPartName, TargetMode targetMode, String relationshipType, String relID) { /* Check OPC compliance */ // Check rule M4.1 : The format designer shall specify and the format // producer // shall Create at most one core properties relationship for a package. // A format consumer shall consider more than one core properties // relationship for a package to be an error. If present, the // relationship shall target the Core Properties part. if (relationshipType.Equals(PackageRelationshipTypes.CORE_PROPERTIES) && this.packageProperties != null) throw new InvalidOperationException( "OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead."); /* * Check rule M1.25: The Relationships part shall not have relationships * to any other part. Package implementers shall enforce this * requirement upon the attempt to Create such a relationship and shall * treat any such relationship as invalid. */ if (targetPartName.IsRelationshipPartURI()) { throw new InvalidOperationException( "Rule M1.25: The Relationships part shall not have relationships to any other part."); } /* End OPC compliance */ EnsureRelationships(); PackageRelationship retRel = relationships.AddRelationship( targetPartName.URI, targetMode, relationshipType, relID); this.isDirty = true; return retRel; }
/** * Create a new MemoryPackagePart from the specified URI and content type * * * aram partName The part URI. * * @param contentType * The part content type. * @return The newly created zip package part, else <b>null</b>. */ protected override PackagePart CreatePartImpl(PackagePartName partName, String contentType, bool loadRelationships) { if (contentType == null) throw new ArgumentException("contentType"); if (partName == null) throw new ArgumentException("partName"); try { return new MemoryPackagePart(this, partName, contentType, loadRelationships); } catch (InvalidFormatException) { // TODO - don't use system.err. Is it valid to return null when this exception occurs? //System.err.println(e); return null; } }
/** * Implement the getPart() method to retrieve a part from its URI in the * current package * * * @see #getPart(PackageRelationship) */ protected override PackagePart GetPartImpl(PackagePartName partName) { if (partList.ContainsKey(partName)) { return partList[partName]; } return null; }
/** * Delete the part with the specified name and all part listed in its * associated relationships part if one exists. This process is recursively * apply to all parts in the relationships part of the specified part. * Prefer the use of this method to delete a part in the package, compare to * the Remove() methods that don't Remove associated relationships part. * * @param PartName * Name of the part to delete */ public void DeletePartRecursive(PackagePartName partName) { if (partName == null || !this.ContainPart(partName)) throw new ArgumentException("PartName"); PackagePart partToDelete = this.GetPart(partName); // Remove the part this.RemovePart(partName); // Remove all relationship parts associated try { foreach (PackageRelationship relationship in partToDelete .Relationships) { PackagePartName targetPartName = PackagingUriHelper .CreatePartName(PackagingUriHelper.ResolvePartUri( partName.URI, relationship.TargetUri)); this.DeletePartRecursive(targetPartName); } } catch (InvalidFormatException e) { logger.Log(POILogger.WARN, "An exception occurs while deleting part '" + partName.Name + "'. Some parts may remain in the package. - " + e.Message); return; } // Remove the relationships part PackagePartName relationshipPartName = PackagingUriHelper .GetRelationshipPartName(partName); if (relationshipPartName != null && ContainPart(relationshipPartName)) this.RemovePart(relationshipPartName); }
/** * Get the package part mapped to the specified URI. * * @param PartName * The URI of the part to retrieve. * @return The package part located by the specified URI, else <b>null</b>. */ protected abstract PackagePart GetPartImpl(PackagePartName PartName);
/** * Delete a part from the package * * @throws ArgumentException * Throws if the part URI is nulll or invalid. */ protected override void RemovePartImpl(PackagePartName partName) { if (partName == null) throw new ArgumentException("partUri"); }
/** * Create and Add a part, with the specified name and content type, to the * package. For general purpose, prefer the overload version of this method * without the 'loadRelationships' parameter. * * @param PartName * Part name. * @param contentType * Part content type. * @param loadRelationships * Specify if the existing relationship part, if any, logically * associated to the newly Created part will be loaded. * @return The newly Created part. * @throws InvalidFormatException * If rule M1.12 is not verified : Packages shall not contain * equivalent part names and package implementers shall neither * Create nor recognize packages with equivalent part names. * @see {@link#CreatePartImpl(URI, String)} */ public PackagePart CreatePart(PackagePartName partName, String contentType, bool loadRelationships) { ThrowExceptionIfReadOnly(); if (partName == null) { throw new ArgumentException("PartName"); } if (contentType == null || contentType == "") { throw new ArgumentException("contentType"); } bool pnFound = false; bool pnDeleted = false; foreach (PackagePartName pn in partList.Keys) { if (partName.Name.StartsWith(pn.Name)) { pnFound = true; if (partList[pn].IsDeleted) { pnDeleted = true; } break; } } // Check if the specified part name already exists if (pnFound && !pnDeleted) { throw new PartAlreadyExistsException( "A part with the name '" + partName.Name + "'" + " already exists : Packages shall not contain equivalent part names and package" + " implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); } /* Check OPC compliance */ // Rule [M4.1]: The format designer shall specify and the format producer // producer // shall Create at most one core properties relationship for a package. // A format consumer shall consider more than one core properties // relationship for a package to be an error. If present, the // relationship shall target the Core Properties part. // Note - POI will read files with more than one Core Properties, which // Office sometimes produces, but is strict on generation if (contentType == ContentTypes.CORE_PROPERTIES_PART) { if (this.packageProperties != null) throw new InvalidOperationException( "OPC Compliance error [M4.1]: you try to add more than one core properties relationship in the package !"); } /* End check OPC compliance */ PackagePart part = this.CreatePartImpl(partName, contentType, loadRelationships); this.contentTypeManager.AddContentType(partName, contentType); this.partList[partName] = part; this.isDirty = true; return part; }
/** * Create and Add a part, with the specified name and content type, to the * package. * * @param PartName * Part name. * @param contentType * Part content type. * @return The newly Created part. * @throws InvalidFormatException * If rule M1.12 is not verified : Packages shall not contain * equivalent part names and package implementers shall neither * Create nor recognize packages with equivalent part names. * @see #CreatePartImpl(PackagePartName, String, bool) */ public PackagePart CreatePart(PackagePartName partName, String contentType) { return this.CreatePart(partName, contentType, true); }
/** * Add a part to the package. * * @param PartName * Part name of the part to Create. * @param contentType * type associated with the file * @param content * the contents to Add. In order to have faster operation in * document merge, the data are stored in memory not on a hard * disk * * @return The new part. * @see #CreatePart(PackagePartName, String) */ public PackagePart CreatePart(PackagePartName partName, String contentType, MemoryStream content) { PackagePart AddedPart = this.CreatePart(partName, contentType); if (AddedPart == null) { return null; } // Extract the zip entry content to put it in the part content if (content != null) { try { Stream partOutput = AddedPart.GetOutputStream(); if (partOutput == null) { return null; } partOutput.Write(content.ToArray(), 0, (int)content.Length); partOutput.Close(); } catch (IOException) { return null; } } else { return null; } return AddedPart; }
/** * Build a part name where the relationship should be stored ((ex * /word/document.xml -> /word/_rels/document.xml.rels) * * @param partName * Source part Uri * @return the full path (as Uri) of the relation file * @throws InvalidOperationException * Throws if the specified Uri is a relationshp part. */ public static PackagePartName GetRelationshipPartName( PackagePartName partName) { if (partName == null) throw new ArgumentException("partName"); if (PackagingUriHelper.PACKAGE_ROOT_URI.OriginalString == partName.URI .OriginalString) return PackagingUriHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME; if (partName.IsRelationshipPartURI()) throw new InvalidOperationException("Can't be a relationship part"); String fullPath = partName.URI.OriginalString; String filename = GetFilename(partName.URI); fullPath = fullPath.Substring(0, fullPath.Length - filename.Length); fullPath = Combine(fullPath, PackagingUriHelper.RELATIONSHIP_PART_SEGMENT_NAME); fullPath = Combine(fullPath, filename); fullPath = fullPath + PackagingUriHelper.RELATIONSHIP_PART_EXTENSION_NAME; PackagePartName retPartName; try { retPartName = CreatePartName(fullPath); } catch (InvalidFormatException) { // Should never happen in production as all data are fixed but in // case of return null: return null; } return retPartName; }
/** * Retrieve a part identified by its name. * * @param PartName * Part name of the part to retrieve. * @return The part with the specified name, else <code>null</code>. */ public PackagePart GetPart(PackagePartName partName) { ThrowExceptionIfWriteOnly(); if (partName == null) throw new ArgumentException("PartName"); // If the partlist is null, then we parse the package. if (partList == null) { try { GetParts(); } catch (InvalidFormatException) { return null; } } return GetPartImpl(partName); }