Ejemplo n.º 1
0
        public void GetSignerUnsigned()
        {
            String[] testFiles =
            {
                "hello-world-unsigned.docx",
                "hello-world-unsigned.pptx",
                "hello-world-unsigned.xlsx",
                "hello-world-office-2010-technical-preview-unsigned.docx"
            };

            foreach (String testFile in testFiles)
            {
                OPCPackage      pkg = OPCPackage.Open(testdata.GetFileInfo(testFile), PackageAccess.READ);
                SignatureConfig sic = new SignatureConfig();
                sic.SetOpcPackage(pkg);
                SignatureInfo si = new SignatureInfo();
                si.SetSignatureConfig(sic);
                List <X509Certificate> result = new List <X509Certificate>();
                foreach (SignatureInfo.SignaturePart sp in si.GetSignatureParts())
                {
                    if (sp.Validate())
                    {
                        result.Add(sp.GetSigner());
                    }
                }
                pkg.Revert();
                pkg.Close();
                Assert.IsNotNull(result);
                Assert.IsEmpty(result);
            }
        }
Ejemplo n.º 2
0
        /**
         * Clone the specified namespace.
         *
         * @param   pkg   the namespace to clone
         * @param   file  the destination file
         * @return  the Cloned namespace
         */
        public static OPCPackage Clone(OPCPackage pkg, string path)
        {
            OPCPackage dest = OPCPackage.Create(path);
            PackageRelationshipCollection rels = pkg.Relationships;

            foreach (PackageRelationship rel in rels)
            {
                PackagePart part = pkg.GetPart(rel);
                PackagePart part_tgt;
                if (rel.RelationshipType.Equals(PackageRelationshipTypes.CORE_PROPERTIES))
                {
                    CopyProperties(pkg.GetPackageProperties(), dest.GetPackageProperties());
                    continue;
                }
                dest.AddRelationship(part.PartName, (TargetMode)rel.TargetMode, rel.RelationshipType);
                part_tgt = dest.CreatePart(part.PartName, part.ContentType);

                Stream out1 = part_tgt.GetOutputStream();
                IOUtils.Copy(part.GetInputStream(), out1);
                out1.Close();

                if (part.HasRelationships)
                {
                    Copy(pkg, part, dest, part_tgt);
                }
            }
            dest.Close();

            //the temp file will be deleted when JVM terminates
            //new File(path).deleteOnExit();
            return(OPCPackage.Open(path));
        }
Ejemplo n.º 3
0
        public void TestBug56479()
        {
            Stream     is1 = OpenXml4NetTestDataSamples.OpenSampleStream("dcterms_bug_56479.zip");
            OPCPackage p   = OPCPackage.Open(is1);

            // Check we found the contents of it
            bool foundCoreProps = false, foundDocument = false, foundTheme1 = false;

            foreach (PackagePart part in p.GetParts())
            {
                if (part.PartName.ToString().Equals("/docProps/core.xml"))
                {
                    Assert.AreEqual(ContentTypes.CORE_PROPERTIES_PART, part.ContentType);
                    foundCoreProps = true;
                }
                if (part.PartName.ToString().Equals("/word/document.xml"))
                {
                    Assert.AreEqual(XWPFRelation.DOCUMENT.ContentType, part.ContentType);
                    foundDocument = true;
                }
                if (part.PartName.ToString().Equals("/word/theme/theme1.xml"))
                {
                    Assert.AreEqual(XWPFRelation.THEME.ContentType, part.ContentType);
                    foundTheme1 = true;
                }
            }
            Assert.IsTrue(foundCoreProps, "Core not found in " + p.GetParts());
            Assert.IsFalse(foundDocument, "Document should not be found in " + p.GetParts());
            Assert.IsFalse(foundTheme1, "Theme1 should not found in " + p.GetParts());
            p.Close();
            is1.Close();
        }
Ejemplo n.º 4
0
        public void TestSelfRelations_bug51187()
        {
            MemoryStream baos = new MemoryStream();
            OPCPackage   pkg  = OPCPackage.Create(baos);

            PackagePart partA =
                pkg.CreatePart(PackagingUriHelper.CreatePartName("/partA"), "text/plain");

            Assert.IsNotNull(partA);

            // reference itself
            PackageRelationship rel1 = partA.AddRelationship(partA.PartName, TargetMode.Internal, "partA");


            // Save, and re-load
            pkg.Close();
            MemoryStream bais = new MemoryStream(baos.ToArray());

            pkg = OPCPackage.Open(bais);

            partA = pkg.GetPart(PackagingUriHelper.CreatePartName("/partA"));


            // Check the relations
            Assert.AreEqual(1, partA.Relationships.Size);

            PackageRelationship rel2 = partA.Relationships.GetRelationship(0);

            Assert.AreEqual(rel1.RelationshipType, rel2.RelationshipType);
            Assert.AreEqual(rel1.Id, rel2.Id);
            Assert.AreEqual(rel1.SourceUri, rel2.SourceUri);
            Assert.AreEqual(rel1.TargetUri, rel2.TargetUri);
            Assert.AreEqual(rel1.TargetMode, rel2.TargetMode);
        }
Ejemplo n.º 5
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.º 6
0
        static void Main(string[] args)
        {
            //create ooxml file in memory
            OPCPackage p = OPCPackage.Create(new MemoryStream());

            //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();
        }
Ejemplo n.º 7
0
        public void TestSignSpreadsheet()
        {
            String     testFile = "hello-world-unsigned.xlsx";
            OPCPackage pkg      = OPCPackage.Open(copy(testdata.GetFileInfo(testFile)), PackageAccess.READ_WRITE);

            sign(pkg, "Test", "CN=Test", 1);
            pkg.Close();
        }
Ejemplo n.º 8
0
        public void TestSetProperties()
        {
            String inputPath = OpenXml4NetTestDataSamples.GetSampleFileName("TestPackageCoreProperiesSetters.docx");

            FileInfo outputFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx");

            // Open namespace
            OPCPackage p = OPCPackage.Open(inputPath, PackageAccess.READ_WRITE);

            try
            {
                SimpleDateFormat df           = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                DateTime         dateToInsert = DateTime.Parse("2007-05-12T08:00:00Z").ToUniversalTime();

                PackageProperties props = p.GetPackageProperties();
                props.SetCategoryProperty("MyCategory");
                props.SetContentStatusProperty("MyContentStatus");
                props.SetContentTypeProperty("MyContentType");
                props.SetCreatedProperty(new DateTime?(dateToInsert));
                props.SetCreatorProperty("MyCreator");
                props.SetDescriptionProperty("MyDescription");
                props.SetIdentifierProperty("MyIdentifier");
                props.SetKeywordsProperty("MyKeywords");
                props.SetLanguageProperty("MyLanguage");
                props.SetLastModifiedByProperty("Julien Chable");
                props.SetLastPrintedProperty(new Nullable <DateTime>(dateToInsert));
                props.SetModifiedProperty(new Nullable <DateTime>(dateToInsert));
                props.SetRevisionProperty("2");
                props.SetTitleProperty("MyTitle");
                props.SetSubjectProperty("MySubject");
                props.SetVersionProperty("2");

                using (FileStream fs = outputFile.OpenWrite())
                {
                    // Save the namespace in the output directory
                    p.Save(fs);
                }

                // Open the newly Created file to check core properties saved values.
                OPCPackage p2 = OPCPackage.Open(outputFile.Name, PackageAccess.READ);
                try
                {
                    CompareProperties(p2);
                    p2.Revert();
                }
                finally
                {
                    p2.Close();
                }
                outputFile.Delete();
            }
            finally
            {
                // use revert to not re-write the input file
                p.Revert();
            }
        }
Ejemplo n.º 9
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.º 10
0
        public void TestOpenFileThenOverWrite()
        {
            string   tempFile = TempFile.GetTempFilePath("poiTesting", "tmp");
            FileInfo origFile = OpenXml4NetTestDataSamples.GetSampleFile("TestPackageCommon.docx");

            FileHelper.CopyFile(origFile.FullName, tempFile);

            // Open the temp file
            OPCPackage p = OPCPackage.Open(tempFile, PackageAccess.READ_WRITE);

            // Close it
            p.Close();
            // Delete it
            File.Delete(tempFile);

            // Reset
            FileHelper.CopyFile(origFile.FullName, tempFile);
            p = OPCPackage.Open(tempFile, PackageAccess.READ_WRITE);

            // Save it to the same file - not allowed
            try
            {
                p.Save(tempFile);
                Assert.Fail("You shouldn't be able to call save(File) to overwrite the current file");
            }
            catch (IOException) { }

            p.Close();
            // Delete it
            File.Delete(tempFile);


            // Open it read only, then close and delete - allowed
            FileHelper.CopyFile(origFile.FullName, tempFile);
            p = OPCPackage.Open(tempFile, PackageAccess.READ);
            p.Close();
            File.Delete(tempFile);

            Assert.AreEqual(0, Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tmp").Length, "At Last: There are no temporary files.");
        }
Ejemplo n.º 11
0
        public void ProtectedTempZip()
        {
            FileInfo        tmpFile  = TempFile.CreateTempFile("protectedXlsx", ".zip");
            FileInfo        tikaProt = XSSFTestDataSamples.GetSampleFile("protected_passtika.xlsx");
            FileInputStream fis      = new FileInputStream(tikaProt.Open(FileMode.Open));
            POIFSFileSystem poifs    = new POIFSFileSystem(fis);
            EncryptionInfo  ei       = new EncryptionInfo(poifs);
            Decryptor       dec      = ei.Decryptor;
            bool            passOk   = dec.VerifyPassword("tika");

            Assert.IsTrue(passOk);

            // generate session key
            SecureRandom sr = new SecureRandom();

            byte[] ivBytes = new byte[16], keyBytes = new byte[16];
            sr.NextBytes(ivBytes);
            sr.NextBytes(keyBytes);

            // extract encrypted ooxml file and write to custom encrypted zip file
            InputStream is1 = dec.GetDataStream(poifs);

            CopyToFile(is1, tmpFile, CipherAlgorithm.aes128, keyBytes, ivBytes);
            is1.Close();

            // provide ZipEntrySource to poi which decrypts on the fly
            ZipEntrySource source = fileToSource(tmpFile, CipherAlgorithm.aes128, keyBytes, ivBytes);

            // test the source
            OPCPackage opc      = OPCPackage.Open(source);
            String     expected = "This is an Encrypted Excel spreadsheet.";

            //XSSFEventBasedExcelExtractor extractor = new XSSFEventBasedExcelExtractor(opc);
            //extractor.IncludeSheetNames = (/*setter*/false);
            //String txt = extractor.Text;
            //Assert.AreEqual(expected, txt.Trim());

            //XSSFWorkbook wb = new XSSFWorkbook(opc);
            //txt = wb.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue;
            //Assert.AreEqual(expected, txt);

            //extractor.Close();

            //wb.Close();
            opc.Close();
            source.Close();
            poifs.Close();
            fis.Close();
            tmpFile.Delete();

            throw new NotImplementedException();
        }
Ejemplo n.º 12
0
        public void TestCreateRelationsFromScratch()
        {
            MemoryStream baos = new MemoryStream();
            OPCPackage   pkg  = OPCPackage.Create(baos);

            PackagePart partA =
                pkg.CreatePart(PackagingUriHelper.CreatePartName("/partA"), "text/plain");
            PackagePart partB =
                pkg.CreatePart(PackagingUriHelper.CreatePartName("/partB"), "image/png");

            Assert.IsNotNull(partA);
            Assert.IsNotNull(partB);

            // Internal
            partA.AddRelationship(partB.PartName, TargetMode.Internal, "http://example/Rel");

            // External
            partA.AddExternalRelationship("http://poi.apache.org/", "http://example/poi");
            partB.AddExternalRelationship("http://poi.apache.org/ss/", "http://example/poi/ss");

            // Check as expected currently
            Assert.AreEqual("/partB", partA.GetRelationship("rId1").TargetUri.ToString());
            Assert.AreEqual("http://poi.apache.org/",
                            partA.GetRelationship("rId2").TargetUri.ToString());
            Assert.AreEqual("http://poi.apache.org/ss/",
                            partB.GetRelationship("rId1").TargetUri.ToString());


            // Save, and re-load
            pkg.Close();
            MemoryStream bais = new MemoryStream(baos.ToArray());

            pkg = OPCPackage.Open(bais);

            partA = pkg.GetPart(PackagingUriHelper.CreatePartName("/partA"));
            partB = pkg.GetPart(PackagingUriHelper.CreatePartName("/partB"));


            // Check the relations
            Assert.AreEqual(2, partA.Relationships.Size);
            Assert.AreEqual(1, partB.Relationships.Size);

            Assert.AreEqual("/partB", partA.GetRelationship("rId1").TargetUri.OriginalString);
            Assert.AreEqual("http://poi.apache.org/",
                            partA.GetRelationship("rId2").TargetUri.ToString());
            Assert.AreEqual("http://poi.apache.org/ss/",
                            partB.GetRelationship("rId1").TargetUri.ToString());
            // Check core too
            Assert.AreEqual("/docProps/core.xml",
                            pkg.GetRelationshipsByType(
                                "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties").GetRelationship(0).TargetUri.ToString());
        }
Ejemplo n.º 13
0
 public override void Close()
 {
     // e.g. XSSFEventBaseExcelExtractor passes a null-document
     if (_document != null)
     {
         OPCPackage pkg = _document.Package;
         if (pkg != null)
         {
             pkg.Close();
         }
     }
     base.Close();
 }
Ejemplo n.º 14
0
        public void office2007prettyPrintedRels()
        {
            OPCPackage pkg = OPCPackage.Open(testdata.GetFileInfo("office2007prettyPrintedRels.docx"), PackageAccess.READ);

            try {
                SignatureConfig sic = new SignatureConfig();
                sic.SetOpcPackage(pkg);
                SignatureInfo si = new SignatureInfo();
                si.SetSignatureConfig(sic);
                bool isValid = si.VerifySignature();
                Assert.IsTrue(isValid);
            } finally {
                pkg.Close();
            }
        }
Ejemplo n.º 15
0
 /**
  * Closes the underlying {@link OPCPackage} from which this
  *  document was read, if there is one
  */
 public void Close()
 {
     if (pkg != null)
     {
         if (pkg.GetPackageAccess() == PackageAccess.READ)
         {
             pkg.Revert();
         }
         else
         {
             pkg.Close();
         }
         pkg = null;
     }
 }
Ejemplo n.º 16
0
        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();
        }
Ejemplo n.º 17
0
        public void Existing()
        {
            XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("Formatting.xlsx");

            Assert.IsNotNull(workbook.GetSharedStringSource());
            Assert.IsNotNull(workbook.GetStylesSource());

            // And check a few low level bits too
            OPCPackage  pkg    = OPCPackage.Open(HSSFTestDataSamples.OpenSampleFileStream("Formatting.xlsx"));
            PackagePart wbPart =
                pkg.GetPart(PackagingUriHelper.CreatePartName("/xl/workbook.xml"));

            // Links to the three sheets, shared, styles and themes
            Assert.IsTrue(wbPart.HasRelationships);
            Assert.AreEqual(6, wbPart.Relationships.Size);
            pkg.Close();
        }
Ejemplo n.º 18
0
        public void TestListOfCustomProperties()
        {
            FileInfo     inp = POIDataSamples.GetSpreadSheetInstance().GetFileInfo("ExcelWithAttachments.xlsm");
            OPCPackage   pkg = OPCPackage.Open(inp, PackageAccess.READ);
            XSSFWorkbook wb  = new XSSFWorkbook(pkg);

            Assert.IsNotNull(wb.GetProperties());
            Assert.IsNotNull(wb.GetProperties().CustomProperties);

            foreach (CT_Property prop in wb.GetProperties().CustomProperties.GetUnderlyingProperties().GetPropertyList())
            {
                Assert.IsNotNull(prop);
            }

            wb.Close();
            pkg.Close();
        }
Ejemplo n.º 19
0
        public void GetSigner()
        {
            String[] testFiles =
            {
                "hyperlink-example-signed.docx",
                "hello-world-signed.docx",
                "hello-world-signed.pptx",
                "hello-world-signed.xlsx",
                "hello-world-office-2010-technical-preview.docx",
                "ms-office-2010-signed.docx",
                "ms-office-2010-signed.pptx",
                "ms-office-2010-signed.xlsx",
                "Office2010-SP1-XAdES-X-L.docx",
                "signed.docx",
            };

            foreach (String testFile in testFiles)
            {
                OPCPackage pkg = OPCPackage.Open(testdata.GetFileInfo(testFile), PackageAccess.READ);
                try {
                    SignatureConfig sic = new SignatureConfig();
                    sic.SetOpcPackage(pkg);
                    SignatureInfo si = new SignatureInfo();
                    si.SetSignatureConfig(sic);
                    List <X509Certificate> result = new List <X509Certificate>();
                    foreach (SignatureInfo.SignaturePart sp in si.GetSignatureParts())
                    {
                        if (sp.Validate())
                        {
                            result.Add(sp.GetSigner());
                        }
                    }

                    Assert.IsNotNull(result);
                    Assert.AreEqual(1, result.Count, "test-file: " + testFile);
                    X509Certificate signer = result[0];
                    //LOG.Log(POILogger.DEBUG, "signer: " + signer.SubjectX500Principal);

                    bool b = si.VerifySignature();
                    Assert.IsTrue(b, "test-file: " + testFile);
                    pkg.Revert();
                } finally {
                    pkg.Close();
                }
            }
        }
Ejemplo n.º 20
0
        public void TestNoCoreProperties_saveNew()
        {
            String     sampleFileName = "OPCCompliance_NoCoreProperties.xlsx";
            OPCPackage pkg            = OPCPackage.Open(POIDataSamples.GetOpenXML4JInstance().GetFileInfo(sampleFileName).FullName);

            // Verify it has empty properties
            Assert.AreEqual(0, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
            Assert.IsNotNull(pkg.GetPackageProperties());
            Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty());
            //Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty().Value);

            // Save and re-load
            MemoryStream baos = new MemoryStream();

            pkg.Save(baos);
            MemoryStream bais = new MemoryStream(baos.ToArray());

            pkg.Revert();

            pkg = OPCPackage.Open(bais);

            // An Empty Properties part has been Added in the save/load
            Assert.AreEqual(1, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
            Assert.IsNotNull(pkg.GetPackageProperties());
            Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty());
            //Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty().Value);
            pkg.Close();

            // Open a new copy of it
            pkg = OPCPackage.Open(POIDataSamples.GetOpenXML4JInstance().GetFileInfo(sampleFileName).FullName);

            // Save and re-load, without having touched the properties yet
            baos = new MemoryStream();
            pkg.Save(baos);
            pkg.Revert();

            bais = new MemoryStream(baos.ToArray());
            pkg  = OPCPackage.Open(bais);

            // Check that this too Added empty properties without error
            Assert.AreEqual(1, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
            Assert.IsNotNull(pkg.GetPackageProperties());
            Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty());
            //Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty().Value);
        }
Ejemplo n.º 21
0
        public void TestSetProperties()
        {
            String inputPath = OpenXml4NetTestDataSamples.GetSampleFileName("TestPackageThumbnail.docx");

            String imagePath = OpenXml4NetTestDataSamples.GetSampleFileName("thumbnail.jpg");

            FileInfo outputFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageThumbnailOUTPUT.docx");

            // Open namespace
            using (Stream inputfile = File.OpenRead(inputPath))
            {
                OPCPackage p = OPCPackage.Open(inputfile);
                try
                {
                    using (FileStream fs = outputFile.OpenWrite())
                    {
                        p.AddThumbnail(imagePath);
                        // Save the namespace in the output directory
                        p.Save(fs);
                        p.Close();
                    }

                    // Open the newly created file to check core properties saved values.
                    OPCPackage p2 = OPCPackage.Open(outputFile.FullName, PackageAccess.READ);
                    try
                    {
                        if (p2.GetRelationshipsByType(PackageRelationshipTypes.THUMBNAIL)
                            .Size == 0)
                        {
                            Assert.Fail("Thumbnail not added to the namespace !");
                        }
                        p2.Revert();
                    }
                    finally
                    {
                        p2.Revert();
                        p2.Close();
                    }
                }
                finally
                {
                    File.Delete(outputFile.Name);
                }
            }
        }
Ejemplo n.º 22
0
        public void TestSetVBAProject()
        {
            FileInfo file;

            byte[] allBytes = new byte[256];
            for (int i = 0; i < 256; i++)
            {
                allBytes[i] = (byte)(i - 128);
            }

            XSSFWorkbook wb1 = new XSSFWorkbook();

            wb1.CreateSheet();
            wb1.SetVBAProject(new ByteArrayInputStream(allBytes));
            file = TempFile.CreateTempFile("poi-", ".xlsm");
            Stream out1 = new FileStream(file.FullName, FileMode.Open, FileAccess.ReadWrite);

            wb1.Write(out1);
            out1.Close();
            wb1.Close();


            // Check the package contains what we'd expect it to
            OPCPackage  pkg    = OPCPackage.Open(file);
            PackagePart wbPart = pkg.GetPart(PackagingUriHelper.CreatePartName("/xl/workbook.xml"));

            Assert.IsTrue(wbPart.HasRelationships);
            PackageRelationshipCollection relationships = wbPart.Relationships.GetRelationships(XSSFRelation.VBA_MACROS.Relation);

            Assert.AreEqual(1, relationships.Size);
            Assert.AreEqual(XSSFRelation.VBA_MACROS.DefaultFileName, relationships.GetRelationship(0).TargetUri.ToString());
            PackagePart vbaPart = pkg.GetPart(PackagingUriHelper.CreatePartName(XSSFRelation.VBA_MACROS.DefaultFileName));

            Assert.IsNotNull(vbaPart);
            Assert.IsFalse(vbaPart.IsRelationshipPart);
            Assert.AreEqual(XSSFRelation.VBA_MACROS.ContentType, vbaPart.ContentType);
            byte[] fromFile = IOUtils.ToByteArray(vbaPart.GetInputStream());
            CollectionAssert.AreEqual(allBytes, fromFile);
            // Load back the XSSFWorkbook just to check nothing explodes
            XSSFWorkbook wb2 = new XSSFWorkbook(pkg);

            Assert.AreEqual(1, wb2.NumberOfSheets);
            Assert.AreEqual(XSSFWorkbookType.XLSM, wb2.WorkbookType);
            pkg.Close();
        }
Ejemplo n.º 23
0
        public void TestNoCoreProperties_saveInPlace()
        {
            String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx";

            // Copy this into a temp file, so we can play with it
            FileInfo   tmp  = TempFile.CreateTempFile("poi-test", ".opc");
            FileStream out1 = new FileStream(tmp.FullName, FileMode.Create, FileAccess.ReadWrite);
            Stream     in1  = POIDataSamples.GetOpenXML4JInstance().OpenResourceAsStream(sampleFileName);

            IOUtils.Copy(
                in1,
                out1);
            out1.Close();
            in1.Close();

            // Open it from that temp file
            OPCPackage pkg = OPCPackage.Open(tmp);

            // Empty properties
            Assert.AreEqual(0, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
            Assert.IsNotNull(pkg.GetPackageProperties());
            Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty());
            //Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty().Value);

            // Save and close
            pkg.Close();


            // Re-open and check
            pkg = OPCPackage.Open(tmp);

            // An Empty Properties part has been Added in the save/load
            Assert.AreEqual(1, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
            Assert.IsNotNull(pkg.GetPackageProperties());
            Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty());
            //Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty().Value);

            // Finish and tidy
            pkg.Revert();
            tmp.Delete();

            Assert.AreEqual(0, Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tmp").Length, "At Last: There are no temporary files.");
        }
Ejemplo n.º 24
0
        public void TestOpenFileThenSaveDelete()
        {
            string   tempFile  = TempFile.GetTempFilePath("poiTesting", "tmp");
            string   tempFile2 = TempFile.GetTempFilePath("poiTesting", "tmp");
            FileInfo origFile  = OpenXml4NetTestDataSamples.GetSampleFile("TestPackageCommon.docx");

            FileHelper.CopyFile(origFile.FullName, tempFile);

            // Open the temp file
            OPCPackage p = OPCPackage.Open(tempFile, PackageAccess.READ_WRITE);

            // Save it to a different file
            p.Save(tempFile2);
            p.Close();

            // Delete both the files
            File.Delete(tempFile);
            File.Delete(tempFile2);
        }
Ejemplo n.º 25
0
        public void TestGetPropertiesLO()
        {
            // Open the namespace
            OPCPackage        pkg1   = OPCPackage.Open(OpenXml4NetTestDataSamples.OpenSampleStream("51444.xlsx"));
            PackageProperties props1 = pkg1.GetPackageProperties();

            Assert.AreEqual(null, props1.GetTitleProperty());
            props1.SetTitleProperty("Bug 51444 fixed");
            MemoryStream out1 = new MemoryStream();

            pkg1.Save(out1);
            out1.Close();
            pkg1.Close();

            OPCPackage        pkg2   = OPCPackage.Open(new MemoryStream(out1.ToArray()));
            PackageProperties props2 = pkg2.GetPackageProperties();

            props2.SetTitleProperty("Bug 51444 fixed");
            pkg2.Close();
        }
Ejemplo n.º 26
0
        public void TestOpenFileThenSaveDelete()
        {
            string   tempFile  = TempFile.GetTempFilePath("poiTesting", "tmp");
            string   tempFile2 = TempFile.GetTempFilePath("poiTesting", "tmp");
            FileInfo origFile  = OpenXml4NetTestDataSamples.GetSampleFile("TestPackageCommon.docx");

            FileHelper.CopyFile(origFile.FullName, tempFile);

            // Open the temp file
            OPCPackage p = OPCPackage.Open(tempFile, PackageAccess.READ_WRITE);

            // Save it to a different file
            p.Save(tempFile2);
            p.Close();

            // Delete both the files
            File.Delete(tempFile);
            File.Delete(tempFile2);

            Assert.AreEqual(0, Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tmp").Length, "At Last: There are no temporary files.");
        }
Ejemplo n.º 27
0
        public void TestMultipleDrawings()
        {
            XSSFWorkbook wb = new XSSFWorkbook();

            for (int i = 0; i < 3; i++)
            {
                XSSFSheet   sheet   = (XSSFSheet)wb.CreateSheet();
                XSSFDrawing drawing = (XSSFDrawing)sheet.CreateDrawingPatriarch();
                Assert.IsNotNull(drawing);
            }
            OPCPackage pkg = wb.Package;

            try
            {
                Assert.AreEqual(3, pkg.GetPartsByContentType(XSSFRelation.DRAWINGS.ContentType).Count);
                checkRewrite(wb);
            }
            finally
            {
                pkg.Close();
            }
            wb.Close();
        }
Ejemplo n.º 28
0
        public void TestCorruptFile()
        {
            OPCPackage pkg  = null;
            FileInfo   file = OpenXml4NetTestDataSamples.GetSampleFile("invalid.xlsx");

            try
            {
                pkg = OPCPackage.Open(file, PackageAccess.READ);
            }
            catch (Exception e)
            {
                //System.out.println(e.GetClass().getName());
                //System.out.println(e.GetMessage());
                //e.printStackTrace();
            }
            finally
            {
                if (pkg != null)
                {
                    pkg.Close();
                }
            }
        }
Ejemplo n.º 29
0
        public void TestEntitiesInCoreProps_56164()
        {
            Stream     is1 = OpenXml4NetTestDataSamples.OpenSampleStream("CorePropertiesHasEntities.ooxml");
            OPCPackage p   = OPCPackage.Open(is1);

            is1.Close();

            // Should have 3 root relationships
            bool foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false;

            foreach (PackageRelationship pr in p.Relationships)
            {
                if (pr.RelationshipType.Equals(PackageRelationshipTypes.CORE_DOCUMENT))
                {
                    foundDocRel = true;
                }
                if (pr.RelationshipType.Equals(PackageRelationshipTypes.CORE_PROPERTIES))
                {
                    foundCorePropRel = true;
                }
                if (pr.RelationshipType.Equals(PackageRelationshipTypes.EXTENDED_PROPERTIES))
                {
                    foundExtPropRel = true;
                }
            }
            Assert.IsTrue(foundDocRel, "Core/Doc Relationship not found in " + p.Relationships);
            Assert.IsTrue(foundCorePropRel, "Core Props Relationship not found in " + p.Relationships);
            Assert.IsTrue(foundExtPropRel, "Ext Props Relationship not found in " + p.Relationships);

            // Get the Core Properties
            PackagePropertiesPart props = (PackagePropertiesPart)p.GetPackageProperties();

            // Check
            Assert.AreEqual("Stefan Kopf", props.GetCreatorProperty());

            p.Close();
        }
Ejemplo n.º 30
0
        public void SaveLoadNew()
        {
            XSSFWorkbook workbook = new XSSFWorkbook();

            //check that the default date system is Set to 1900
            CT_WorkbookPr pr = workbook.GetCTWorkbook().workbookPr;

            Assert.IsNotNull(pr);
            Assert.IsTrue(pr.IsSetDate1904());
            Assert.IsFalse(pr.date1904, "XSSF must use the 1900 date system");

            ISheet sheet1 = workbook.CreateSheet("sheet1");
            ISheet sheet2 = workbook.CreateSheet("sheet2");

            workbook.CreateSheet("sheet3");

            IRichTextString rts = workbook.GetCreationHelper().CreateRichTextString("hello world");

            sheet1.CreateRow(0).CreateCell((short)0).SetCellValue(1.2);
            sheet1.CreateRow(1).CreateCell((short)0).SetCellValue(rts);
            sheet2.CreateRow(0);

            Assert.AreEqual(0, workbook.GetSheetAt(0).FirstRowNum);
            Assert.AreEqual(1, workbook.GetSheetAt(0).LastRowNum);
            Assert.AreEqual(0, workbook.GetSheetAt(1).FirstRowNum);
            Assert.AreEqual(0, workbook.GetSheetAt(1).LastRowNum);
            Assert.AreEqual(0, workbook.GetSheetAt(2).FirstRowNum);
            Assert.AreEqual(0, workbook.GetSheetAt(2).LastRowNum);

            FileInfo file = TempFile.CreateTempFile("poi-", ".xlsx");
            Stream   out1 = File.OpenWrite(file.Name);

            workbook.Write(out1);
            out1.Close();

            // Check the namespace Contains what we'd expect it to
            OPCPackage  pkg       = OPCPackage.Open(file.ToString());
            PackagePart wbRelPart =
                pkg.GetPart(PackagingUriHelper.CreatePartName("/xl/_rels/workbook.xml.rels"));

            Assert.IsNotNull(wbRelPart);
            Assert.IsTrue(wbRelPart.IsRelationshipPart);
            Assert.AreEqual(ContentTypes.RELATIONSHIPS_PART, wbRelPart.ContentType);

            PackagePart wbPart =
                pkg.GetPart(PackagingUriHelper.CreatePartName("/xl/workbook.xml"));

            // Links to the three sheets, shared strings and styles
            Assert.IsTrue(wbPart.HasRelationships);
            Assert.AreEqual(5, wbPart.Relationships.Size);

            // Load back the XSSFWorkbook
            workbook = new XSSFWorkbook(pkg);
            Assert.AreEqual(3, workbook.NumberOfSheets);
            Assert.IsNotNull(workbook.GetSheetAt(0));
            Assert.IsNotNull(workbook.GetSheetAt(1));
            Assert.IsNotNull(workbook.GetSheetAt(2));

            Assert.IsNotNull(workbook.GetSharedStringSource());
            Assert.IsNotNull(workbook.GetStylesSource());

            Assert.AreEqual(0, workbook.GetSheetAt(0).FirstRowNum);
            Assert.AreEqual(1, workbook.GetSheetAt(0).LastRowNum);
            Assert.AreEqual(0, workbook.GetSheetAt(1).FirstRowNum);
            Assert.AreEqual(0, workbook.GetSheetAt(1).LastRowNum);
            Assert.AreEqual(0, workbook.GetSheetAt(2).FirstRowNum);
            Assert.AreEqual(0, workbook.GetSheetAt(2).LastRowNum);

            sheet1 = workbook.GetSheetAt(0);
            Assert.AreEqual(1.2, sheet1.GetRow(0).GetCell(0).NumericCellValue, 0.0001);
            Assert.AreEqual("hello world", sheet1.GetRow(1).GetCell(0).RichStringCellValue.String);

            pkg.Close();
        }