Ejemplo n.º 1
0
        protected override void Commit()
        {
            if (ctStyles == null)
            {
                throw new InvalidOperationException("Unable to write out styles that were never read in!");
            }

            /*XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
             * xmlOptions.SaveSyntheticDocumentElement=(new QName(CTStyles.type.Name.NamespaceURI, "styles"));
             * Dictionary<String,String> map = new Dictionary<String,String>();
             * map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/relationships", "r");
             * map.Put("http://schemas.Openxmlformats.org/wordProcessingml/2006/main", "w");
             * xmlOptions.SaveSuggestedPrefixes=(map);*/
            PackagePart             part       = GetPackagePart();
            Stream                  out1       = part.GetOutputStream();
            StylesDocument          doc        = new StylesDocument(ctStyles);
            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
                new XmlQualifiedName("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006"),
                new XmlQualifiedName("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),
                new XmlQualifiedName("m", "http://schemas.openxmlformats.org/officeDocument/2006/math"),
                new XmlQualifiedName("v", "urn:schemas-microsoft-com:vml"),
                new XmlQualifiedName("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"),
                new XmlQualifiedName("w10", "urn:schemas-microsoft-com:office:word"),
                new XmlQualifiedName("wne", "http://schemas.microsoft.com/office/word/2006/wordml"),
                new XmlQualifiedName("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")
            });

            doc.Save(out1, namespaces);
            out1.Close();
        }
Ejemplo n.º 2
0
        protected internal override void Commit()
        {
            PackagePart part = GetPackagePart();
            Stream      out1 = part.GetOutputStream();

            //XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
            //Sets the pivotCacheDefInition tag
            //xmlOptions.SetSaveSyntheticDocumentElement(new QName(CTPivotCacheDefInition.type.Name.
            //         GetNamespaceURI(), "pivotCacheDefInition"));

            //// ensure the fields have names
            //if (ctPivotCacheDefinition.cacheFields != null)
            //{
            //    CT_CacheFields cFields = ctPivotCacheDefinition.cacheFields;
            //    foreach (CT_CacheField cf in cFields.cacheField)
            //    {
            //        if (cf.name == null || cf.name.Equals(""))
            //        {
            //            cf.name = "A";
            //        }
            //    }
            //}

            ctPivotCacheDefinition.Save(out1);
            out1.Close();
        }
Ejemplo n.º 3
0
        protected void Commit()
        {
            //XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);

            /*
             * Saved chart space must have the following namespaces Set:
             * <c:chartSpace
             *    xmlns:c="http://schemas.Openxmlformats.org/drawingml/2006/chart"
             *    xmlns:a="http://schemas.Openxmlformats.org/drawingml/2006/main"
             *    xmlns:r="http://schemas.Openxmlformats.org/officeDocument/2006/relationships">
             */
            //xmlOptions.SetSaveSyntheticDocumentElement(new QName(CTChartSpace.type.GetName().GetNamespaceURI(), "chartSpace", "c"));
            Dictionary <String, String> map = new Dictionary <String, String>();

            map[XSSFDrawing.NAMESPACE_A]        = "a";
            map[XSSFDrawing.NAMESPACE_C]        = "c";
            map[ST_RelationshipId.NamespaceURI] = "r";
            //xmlOptions.SetSaveSuggestedPrefixes(map);

            PackagePart part = GetPackagePart();
            Stream      out1 = part.GetOutputStream();

            chartSpace.Save(out1);
            out1.Close();
        }
Ejemplo n.º 4
0
        /**
         * save and Commit numbering
         */

        protected internal override void Commit()
        {
            /*XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
             * xmlOptions.SaveSyntheticDocumentElement=(new QName(CTNumbering.type.Name.NamespaceURI, "numbering"));
             * Dictionary<String,String> map = new Dictionary<String,String>();
             * map.Put("http://schemas.Openxmlformats.org/markup-compatibility/2006", "ve");
             * map.Put("urn:schemas-microsoft-com:office:office", "o");
             * map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/relationships", "r");
             * map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/math", "m");
             * map.Put("urn:schemas-microsoft-com:vml", "v");
             * map.Put("http://schemas.Openxmlformats.org/drawingml/2006/wordProcessingDrawing", "wp");
             * map.Put("urn:schemas-microsoft-com:office:word", "w10");
             * map.Put("http://schemas.Openxmlformats.org/wordProcessingml/2006/main", "w");
             * map.Put("http://schemas.microsoft.com/office/word/2006/wordml", "wne");
             * xmlOptions.SaveSuggestedPrefixes=(map);*/
            PackagePart       part = GetPackagePart();
            Stream            out1 = part.GetOutputStream();
            NumberingDocument doc  = new NumberingDocument(ctNumbering);

            //XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            //    new XmlQualifiedName("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006"),
            //    new XmlQualifiedName("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),
            //    new XmlQualifiedName("m", "http://schemas.openxmlformats.org/officeDocument/2006/math"),
            //    new XmlQualifiedName("v", "urn:schemas-microsoft-com:vml"),
            //    new XmlQualifiedName("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"),
            //    new XmlQualifiedName("w10", "urn:schemas-microsoft-com:office:word"),
            //    new XmlQualifiedName("wne", "http://schemas.microsoft.com/office/word/2006/wordml"),
            //     new XmlQualifiedName("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")
            // });
            doc.Save(out1);
            out1.Close();
        }
Ejemplo n.º 5
0
        /**
         * Adds a picture to the document.
         *
         * @param pictureData       The picture data
         * @param format            The format of the picture.
         *
         * @return the index to this picture (0 based), the Added picture can be obtained from {@link #getAllPictures()} .
         * @throws InvalidFormatException
         */
        public String AddPictureData(byte[] pictureData, int format)
        {
            XWPFPictureData xwpfPicData = document.FindPackagePictureData(pictureData, format);
            POIXMLRelation  relDesc     = XWPFPictureData.RELATIONS[format];

            if (xwpfPicData == null)
            {
                /* Part doesn't exist, create a new one */
                int idx = document.GetNextPicNameNumber(format);
                xwpfPicData = (XWPFPictureData)CreateRelationship(relDesc, XWPFFactory.GetInstance(), idx);
                /* write bytes to new part */
                PackagePart picDataPart = xwpfPicData.GetPackagePart();
                Stream      out1        = null;
                try
                {
                    out1 = picDataPart.GetOutputStream();
                    out1.Write(pictureData, 0, pictureData.Length);
                }
                catch (IOException e)
                {
                    throw new POIXMLException(e);
                }
                finally
                {
                    try
                    {
                        if (out1 != null)
                        {
                            out1.Close();
                        }
                    }
                    catch (IOException)
                    {
                        // ignore
                    }
                }

                document.RegisterPackagePictureData(xwpfPicData);
                pictures.Add(xwpfPicData);
                return(GetRelationId(xwpfPicData));
            }
            else if (!GetRelations().Contains(xwpfPicData))
            {
                /*
                 * Part already existed, but was not related so far. Create
                 * relationship to the already existing part and update
                 * POIXMLDocumentPart data.
                 */
                PackagePart picDataPart = xwpfPicData.GetPackagePart();
                // TODO add support for TargetMode.EXTERNAL relations.
                RelationPart rp = AddRelation(null, XWPFRelation.IMAGES, xwpfPicData);
                pictures.Add(xwpfPicData);
                return(rp.Relationship.Id);
            }
            else
            {
                /* Part already existed, Get relation id and return it */
                return(GetRelationId(xwpfPicData));
            }
        }
Ejemplo n.º 6
0
        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();
        }
Ejemplo n.º 7
0
        public static OPCPackage Clone(OPCPackage pkg, string path)
        {
            OPCPackage tgt = OPCPackage.Create(path);

            foreach (PackageRelationship relationship in pkg.Relationships)
            {
                PackagePart part1 = pkg.GetPart(relationship);
                if (relationship.RelationshipType.Equals("http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"))
                {
                    PackageHelper.CopyProperties(pkg.GetPackageProperties(), tgt.GetPackageProperties());
                }
                else
                {
                    tgt.AddRelationship(part1.PartName, relationship.TargetMode.Value, relationship.RelationshipType);
                    PackagePart part2        = tgt.CreatePart(part1.PartName, part1.ContentType);
                    Stream      outputStream = part2.GetOutputStream();
                    IOUtils.Copy(part1.GetInputStream(), outputStream);
                    outputStream.Close();
                    if (part1.HasRelationships)
                    {
                        PackageHelper.Copy(pkg, part1, tgt, part2);
                    }
                }
            }
            tgt.Close();
            return(OPCPackage.Open(path));
        }
Ejemplo n.º 8
0
        protected internal override void Commit()
        {
            PackagePart part = GetPackagePart();
            Stream      out1 = part.GetOutputStream();

            Write(out1);
            out1.Dispose();
        }
Ejemplo n.º 9
0
        protected override void Commit()
        {
            PackagePart part = GetPackagePart();
            Stream      out1 = part.GetOutputStream();

            WriteTo(out1);
            out1.Close();
        }
Ejemplo n.º 10
0
        protected internal override void Commit()
        {
            PackagePart part = GetPackagePart();
            Stream      out1 = part.GetOutputStream();

            drawing.Save(out1);
            out1.Close();
        }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
        protected internal override void Commit()
        {
            PackagePart part = GetPackagePart();
            Stream      out1 = part.GetOutputStream();

            //XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
            //Sets the pivotCacheDefInition tag
            //xmlOptions.SetSaveSyntheticDocumentElement(new QName(CTPivotCacheDefInition.type.Name.
            //         GetNamespaceURI(), "pivotCacheDefInition"));
            ctPivotCacheDefinition.Save(out1);
            out1.Close();
        }
Ejemplo n.º 13
0
        protected internal override void Commit()
        {
            //XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);

            /*
             * Saved chart space must have the following namespaces Set:
             * <c:chartSpace
             *    xmlns:c="http://schemas.Openxmlformats.org/drawingml/2006/chart"
             *    xmlns:a="http://schemas.Openxmlformats.org/drawingml/2006/main"
             *    xmlns:r="http://schemas.Openxmlformats.org/officeDocument/2006/relationships">
             */
            PackagePart part = GetPackagePart();

            chartSpaceDocument.Save(part.GetOutputStream());
        }
Ejemplo n.º 14
0
        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);
        }
Ejemplo n.º 15
0
        protected internal override void Commit()
        {
            /*XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
             * xmlOptions.SaveSyntheticDocumentElement=(new QName(CTFootnotes.type.Name.NamespaceURI, "footnotes"));
             * Dictionary<String,String> map = new Dictionary<String,String>();
             * map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/relationships", "r");
             * map.Put("http://schemas.Openxmlformats.org/wordProcessingml/2006/main", "w");
             * xmlOptions.SaveSuggestedPrefixes=(map);*/
            PackagePart part = GetPackagePart();

            using (Stream out1 = part.GetOutputStream())
            {
                FootnotesDocument notesDoc = new FootnotesDocument(ctFootnotes);
                notesDoc.Save(out1);
            }
        }
Ejemplo n.º 16
0
        /**
         * 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();
            }
        }
Ejemplo n.º 17
0
        protected override void Commit()
        {
            /*XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
             * xmlOptions.SaveSyntheticDocumentElement=(new QName(CTSettings.type.Name.NamespaceURI, "settings"));
             * Dictionary<String, String> map = new Dictionary<String, String>();
             * map.Put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w");
             * xmlOptions.SaveSuggestedPrefixes=(map);*/
            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new[] {
                new XmlQualifiedName("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")
            });
            PackagePart      part = GetPackagePart();
            Stream           out1 = part.GetOutputStream();
            SettingsDocument sd   = new SettingsDocument(ctSettings);

            sd.Save(out1, namespaces);
            out1.Close();
        }
Ejemplo n.º 18
0
        protected override void Commit()
        {
            /*XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
             * xmlOptions.SaveSyntheticDocumentElement=(new QName(CTFootnotes.type.Name.NamespaceURI, "footnotes"));
             * Dictionary<String,String> map = new Dictionary<String,String>();
             * map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/relationships", "r");
             * map.Put("http://schemas.Openxmlformats.org/wordProcessingml/2006/main", "w");
             * xmlOptions.SaveSuggestedPrefixes=(map);*/
            PackagePart             part       = GetPackagePart();
            Stream                  out1       = part.GetOutputStream();
            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
                new XmlQualifiedName("w", "http://schemas.Openxmlformats.org/wordProcessingml/2006/main"),
                new XmlQualifiedName("r", "http://schemas.Openxmlformats.org/officeDocument/2006/relationships")
            });
            FootnotesDocument notesDoc = new FootnotesDocument(ctFootnotes);

            notesDoc.Save(out1, null);
            out1.Close();
        }
Ejemplo n.º 19
0
        protected override void Commit()
        {
            // /*
            //    Saved Drawings must have the following namespaces Set:
            //    <xdr:wsDr
            //        xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
            //        xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing">
            // */
            ////if(isNew) xmlOptions.SetSaveSyntheticDocumentElement(new QName(CT_Drawing.type.GetName().GetNamespaceURI(), "wsDr", "xdr"));
            //Dictionary<String, String> map = new Dictionary<String, String>();
            //map[NAMESPACE_A]= "a";
            //map[ST_RelationshipId.NamespaceURI]= "r";
            //xmlOptions.SetSaveSuggestedPrefixes(map);

            PackagePart part = GetPackagePart();
            Stream      out1 = part.GetOutputStream();

            drawing.Save(out1);
            out1.Close();
        }
Ejemplo n.º 20
0
        protected internal override void Commit()
        {
            if (ctStyles == null)
            {
                throw new InvalidOperationException("Unable to write out styles that were never read in!");
            }

            /*XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
             * xmlOptions.SaveSyntheticDocumentElement=(new QName(CTStyles.type.Name.NamespaceURI, "styles"));
             * Dictionary<String,String> map = new Dictionary<String,String>();
             * map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/relationships", "r");
             * map.Put("http://schemas.Openxmlformats.org/wordProcessingml/2006/main", "w");
             * xmlOptions.SaveSuggestedPrefixes=(map);*/
            PackagePart part = GetPackagePart();

            using (Stream out1 = part.GetOutputStream())
            {
                StylesDocument doc = new StylesDocument(ctStyles);
                doc.Save(out1);
            }
        }
Ejemplo n.º 21
0
        /**
         * Sets the Thumbnail for the document, replacing any existing
         *  one.
         *
         * @param name The filename for the thumbnail image, eg <code>thumbnail.jpg</code>
         * @param imageData The inputstream to read the thumbnail image from
         */
        public void SetThumbnail(String filename, Stream imageData)
        {
            PackagePart tPart = ThumbnailPart;

            if (tPart == null)
            {
                // New thumbnail
                pkg.AddThumbnail(filename, imageData);
            }
            else
            {
                // Change existing
                String newType = ContentTypes.GetContentTypeFromFileExtension(filename);
                if (!newType.Equals(tPart.ContentType))
                {
                    throw new ArgumentException("Can't set a Thumbnail of type " +
                                                newType + " when existing one is of a different type " +
                                                tPart.ContentType);
                }
                StreamHelper.CopyStream(imageData, tPart.GetOutputStream());
            }
        }
Ejemplo n.º 22
0
        private static void Copy(OPCPackage pkg, PackagePart part, OPCPackage tgt, PackagePart part_tgt)
        {
            PackageRelationshipCollection relationships = part.Relationships;

            if (relationships == null)
            {
                return;
            }
            foreach (PackageRelationship packageRelationship in relationships)
            {
                TargetMode?targetMode = packageRelationship.TargetMode;
                if ((targetMode.GetValueOrDefault() != TargetMode.External ? 0 : (targetMode.HasValue ? 1 : 0)) != 0)
                {
                    part_tgt.AddExternalRelationship(packageRelationship.TargetUri.ToString(), packageRelationship.RelationshipType, packageRelationship.Id);
                }
                else
                {
                    Uri targetUri = packageRelationship.TargetUri;
                    if (targetUri.Fragment != null)
                    {
                        part_tgt.AddRelationship(targetUri, packageRelationship.TargetMode.Value, packageRelationship.RelationshipType, packageRelationship.Id);
                    }
                    else
                    {
                        PackagePartName partName = PackagingUriHelper.CreatePartName(packageRelationship.TargetUri);
                        PackagePart     part1    = pkg.GetPart(partName);
                        part_tgt.AddRelationship(part1.PartName, packageRelationship.TargetMode.Value, packageRelationship.RelationshipType, packageRelationship.Id);
                        if (!tgt.ContainPart(part1.PartName))
                        {
                            PackagePart part2        = tgt.CreatePart(part1.PartName, part1.ContentType);
                            Stream      outputStream = part2.GetOutputStream();
                            IOUtils.Copy(part1.GetInputStream(), outputStream);
                            outputStream.Close();
                            PackageHelper.Copy(pkg, part1, tgt, part2);
                        }
                    }
                }
            }
        }
Ejemplo n.º 23
0
        protected internal override void Commit()
        {
            if (ctSettings == null)
            {
                throw new InvalidOperationException("Unable to write out settings that were never read in!");
            }

            /*XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
             * xmlOptions.SaveSyntheticDocumentElement=(new QName(CTSettings.type.Name.NamespaceURI, "settings"));
             * Dictionary<String, String> map = new Dictionary<String, String>();
             * map.Put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w");
             * xmlOptions.SaveSuggestedPrefixes=(map);*/
            //XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            //    new XmlQualifiedName("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")});
            PackagePart part = GetPackagePart();

            using (Stream out1 = part.GetOutputStream())
            {
                SettingsDocument sd = new SettingsDocument(ctSettings);
                sd.Save(out1);
            }
        }
Ejemplo n.º 24
0
        /**
         * Called to update the embedded Excel workbook. As the format and structire
         * of the workbook are known in advance, all this code attempts to do is
         * write a new value into the first cell on the first row of the first
         * worksheet. Prior to executing this method, that cell will contain the
         * value 1.
         *
         * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException
         *                             Rather
         *                             than use the specific classes (HSSF/XSSF) to handle the embedded
         *                             workbook this method uses those defeined in the SS stream. As
         *                             a result, it might be the case that a SpreadsheetML file is
         *                             opened for processing, throwing this exception if that file is
         *                             invalid.
         * @throws java.io.IOException Thrown if a problem occurs in the underlying
         *                             file system.
         */
        public void UpdateEmbeddedDoc1()
        {
            IWorkbook workbook = null;
            ISheet    sheet    = null;
            IRow      row      = null;

            NPOI.SS.UserModel.ICell   cell         = null;
            PackagePart               pPart        = null;
            IEnumerator <PackagePart> pIter        = null;
            List <PackagePart>        embeddedDocs = this.doc.GetAllEmbedds();

            if (embeddedDocs != null && embeddedDocs.Count != 0)
            {
                pIter = embeddedDocs.GetEnumerator();
                while (pIter.MoveNext())
                {
                    pPart = pIter.Current;
                    if (pPart.PartName.Extension.Equals(BINARY_EXTENSION) ||
                        pPart.PartName.Extension.Equals(OPENXML_EXTENSION))
                    {
                        // Get an InputStream from the pacage part and pass that
                        // to the create method of the WorkbookFactory class. Update
                        // the resulting Workbook and then stream that out again
                        // using an OutputStream obtained from the same PackagePart.
                        workbook = WorkbookFactory.Create(pPart.GetInputStream());
                        sheet    = workbook.GetSheetAt(SHEET_NUM);
                        row      = sheet.GetRow(ROW_NUM);
                        cell     = row.GetCell(CELL_NUM);
                        cell.SetCellValue(NEW_VALUE);
                        workbook.Write(pPart.GetOutputStream());
                    }
                }

                // Finally, write the newly modified Word document out to file.
                string file = Path.GetFileNameWithoutExtension(this.docFile) + "tmp" + Path.GetExtension(this.docFile);
                this.doc.Write(new FileStream(file, FileMode.CreateNew));
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Save and commit footer
        /// </summary>
        protected internal override void Commit()
        {
            /*XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
             * xmlOptions.SaveSyntheticDocumentElement=(new QName(CTNumbering.type.Name.NamespaceURI, "hdr"));
             * Dictionary<String,String> map = new Dictionary<String, String>();
             * map.Put("http://schemas.Openxmlformats.org/markup-compatibility/2006", "ve");
             * map.Put("urn:schemas-microsoft-com:office:office", "o");
             * map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/relationships", "r");
             * map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/math", "m");
             * map.Put("urn:schemas-microsoft-com:vml", "v");
             * map.Put("http://schemas.Openxmlformats.org/drawingml/2006/wordProcessingDrawing", "wp");
             * map.Put("urn:schemas-microsoft-com:office:word", "w10");
             * map.Put("http://schemas.Openxmlformats.org/wordProcessingml/2006/main", "w");
             * map.Put("http://schemas.microsoft.com/office/word/2006/wordml", "wne");
             * xmlOptions.SaveSuggestedPrefixes=(/map);*/
            PackagePart part = GetPackagePart();

            using (Stream out1 = part.GetOutputStream())
            {
                HdrDocument doc = new HdrDocument((CT_Hdr)headerFooter);
                doc.Save(out1);
            }
        }
Ejemplo n.º 26
0
        protected override void Commit()
        {
            //XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);

            /*
             * Saved chart space must have the following namespaces Set:
             * <c:chartSpace
             *    xmlns:c="http://schemas.Openxmlformats.org/drawingml/2006/chart"
             *    xmlns:a="http://schemas.Openxmlformats.org/drawingml/2006/main"
             *    xmlns:r="http://schemas.Openxmlformats.org/officeDocument/2006/relationships">
             */
            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();

            namespaces.Add("a", XSSFDrawing.NAMESPACE_A);
            namespaces.Add("c", XSSFDrawing.NAMESPACE_C);
            namespaces.Add("r", ST_RelationshipId.NamespaceURI);

            PackagePart part = GetPackagePart();
            Stream      out1 = part.GetOutputStream();

            chartSpace.Save(out1, namespaces);
            out1.Close();
        }
Ejemplo n.º 27
0
        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
            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());
            // Save and close
            try
            {
                pkg.Close();
            }
            catch (IOException)
            {
                Assert.Fail();
            }

            ZipFileAssert.AssertEqual(expectedFile, targetFile);
            File.Delete(targetFile.FullName);

            Assert.AreEqual(0, Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tmp").Length, "At Last: There are no temporary files.");
        }
Ejemplo n.º 28
0
        //[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.");
        }