Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            POIFSFileSystem fs = new POIFSFileSystem();

            //get the root directory
            DirectoryEntry dir = fs.Root;

            //create a entry of DocumentSummaryInformation
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "NPOI Team";
            CustomProperties customProperties = dsi.CustomProperties;
            if (customProperties == null)
                customProperties = new CustomProperties();
            customProperties.Put("测试", "value A");
            customProperties.Put("BB", "value BB");
            customProperties.Put("CCC", "value CCC");
            dsi.CustomProperties = customProperties;
            //Write the stream data of the DocumentSummaryInformation entry to the root directory
            dsi.Write(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);


            //create a POIFS file called Foo.poifs
            FileStream output = new FileStream("Foo.xls", FileMode.OpenOrCreate);
            fs.WriteFileSystem(output);
            output.Close();
        }
Ejemplo n.º 2
0
        /**
         * Write out, with any properties changes, but nothing else
         */
        public override void Write(Stream out1)
        {
            POIFSFileSystem fs = new POIFSFileSystem();

            // For tracking what we've written out, so far
            List<String> excepts = new List<String>(1);

            // Write out our HPFS properties, with any changes
            WriteProperties(fs, excepts);
        
            // Copy over everything else unchanged
            EntryUtils.CopyNodes(directory, fs.Root, excepts);
        
            // Save the resultant POIFSFileSystem to the output stream
            fs.WriteFileSystem(out1);
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            POIFSFileSystem fs = new POIFSFileSystem();

            //get the root directory
            DirectoryEntry dir = fs.Root;
            //create a document entry
            dir.CreateDocument("Foo", new MemoryStream(new byte[] {0x01,0x02,0x03 }));

            //create a folder
            dir.CreateDirectory("Hello");

            //create a POIFS file called Foo.poifs
            FileStream output = new FileStream("Foo.poifs", FileMode.OpenOrCreate);
            fs.WriteFileSystem(output);
            output.Close();
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            POIFSFileSystem fs = new POIFSFileSystem();

            //get the root directory
            DirectoryEntry dir = fs.Root;
            
            //create a entry of DocumentSummaryInformation
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "NPOI Team";
            //Write the stream data of the DocumentSummaryInformation entry to the root directory
            dsi.Write(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);

            //create a entry of SummaryInformation
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Subject = "NPOI SDK Example";
            //Write the stream data of the SummaryInformation entry to the root directory
            si.Write(dir, SummaryInformation.DEFAULT_STREAM_NAME);

            //create a POIFS file called Foo.poifs
            FileStream output = new FileStream("Foo.poifs", FileMode.OpenOrCreate);
            fs.WriteFileSystem(output);
            output.Close();
        }
Ejemplo n.º 5
0
        /**
         * Performs the check described in {@link #TestReCreate()} for a single
         * POI filesystem.
         *
         * @param f the POI filesystem to check
         */
        private void TestRecreate(FileInfo f)
        {
            Console.WriteLine("Recreating file \"" + f.Name + "\"");
            
            /* Read the POI filesystem's property Set streams: */
            POIFile[] psf1 = Util.ReadPropertySets(_samples.GetFile(f.Name));

            /* Create a new POI filesystem containing the origin file's
             * property Set streams: */
            FileInfo fi = new FileInfo(f.Name);
            FileStream copy = File.Create(fi.Name);
            //copy.deleteOnExit();
            FileStream out1 = copy;
            POIFSFileSystem poiFs = new POIFSFileSystem();
            for (int i = 0; i < psf1.Length; i++)
            {
                Stream in1 =
                    new ByteArrayInputStream(psf1[i].GetBytes());
                PropertySet psIn = PropertySetFactory.Create(in1);
                MutablePropertySet psOut = new MutablePropertySet(psIn);
                MemoryStream psStream =
                    new MemoryStream();
                psOut.Write(psStream);
                psStream.Close();
                byte[] streamData = psStream.ToArray();
                poiFs.CreateDocument(new ByteArrayInputStream(streamData),
                                     psf1[i].GetName());
                poiFs.WriteFileSystem(out1);
            }

            /* Read the property Set streams from the POI filesystem just
             * Created. */
            POIFile[] psf2 = Util.ReadPropertySets(copy);
            for (int i = 0; i < psf2.Length; i++)
            {
                byte[] bytes1 = psf1[i].GetBytes();
                byte[] bytes2 = psf2[i].GetBytes();
                Stream in1 = new ByteArrayInputStream(bytes1);
                Stream in2 = new ByteArrayInputStream(bytes2);
                PropertySet ps1 = PropertySetFactory.Create(in1);
                PropertySet ps2 = PropertySetFactory.Create(in2);

                /* Compare the property Set stream with the corresponding one
                 * from the origin file and check whether they are equal. */
                
                Assert.AreEqual(ps1, ps2, "Equality for file " + f.Name);
            }
            out1.Close();
        }
Ejemplo n.º 6
0
        public void TestWriteTwoSections()
        {
            String STREAM_NAME = "PropertySetStream";
            String SECTION1 = "Section 1";
            String SECTION2 = "Section 2";

            FileInfo fi = TempFile.CreateTempFile(POI_FS, ".doc");
            FileStream file = new FileStream(fi.FullName, FileMode.Open, FileAccess.ReadWrite);
            //filename.deleteOnExit();
            FileStream out1 = file;

            POIFSFileSystem poiFs = new POIFSFileSystem();
            MutablePropertySet ps = new MutablePropertySet();
            ps.ClearSections();

            ClassID formatID = new ClassID();
            formatID.Bytes = new byte[]{0, 1,  2,  3,  4,  5,  6,  7,
                                     8, 9, 10, 11, 12, 13, 14, 15};
            MutableSection s1 = new MutableSection();
            s1.SetFormatID(formatID);
            s1.SetProperty(2, SECTION1);
            ps.AddSection(s1);

            MutableSection s2 = new MutableSection();
            s2.SetFormatID(formatID);
            s2.SetProperty(2, SECTION2);
            ps.AddSection(s2);

            poiFs.CreateDocument(ps.GetStream(), STREAM_NAME);
            poiFs.WriteFileSystem(out1);
            //out1.Close();

            /* Read the POIFS: */
            psa = new PropertySet[1];
            POIFSReader reader2 = new POIFSReader();
            //reader2.StreamReaded += new POIFSReaderEventHandler(reader2_StreamReaded);
            POIFSReaderListener2 prl = new POIFSReaderListener2();
            reader2.RegisterListener(prl);
            reader2.Read(file);
            Assert.IsNotNull(psa[0]);
            Section s = (Section)(psa[0].Sections[0]);
            Assert.AreEqual(s.FormatID, formatID);
            Object p = s.GetProperty(2);
            Assert.AreEqual(SECTION1, p);
            s = (Section)(psa[0].Sections[1]);
            p = s.GetProperty(2);
            Assert.AreEqual(SECTION2, p);

            file.Close();
            //File.Delete(dataDir + POI_FS);
            try
            {
                File.Delete(fi.FullName);
            }
            catch
            {
            }
        }
Ejemplo n.º 7
0
        public void TestDictionaryWithInvalidCodepage()
        {

            using (FileStream copy = File.Create(@".\Test-HPSF.ole2"))
            {
                /* Write: */
                POIFSFileSystem poiFs = new POIFSFileSystem();
                MutablePropertySet ps1 = new MutablePropertySet();
                MutableSection s = (MutableSection)ps1.Sections[0];
                Hashtable m = new Hashtable(3, 1.0f);
                m[1] = "String 1";
                m[2] = "String 2";
                m[3] = "String 3";

                try
                {
                    s.Dictionary = m;
                    s.SetFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID1);
                    s.SetProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, 12345);
                    poiFs.CreateDocument(ps1.ToInputStream(), "Test");
                    poiFs.WriteFileSystem(copy);
                    Assert.Fail("This Testcase did not detect the invalid codepage value.");
                }
                catch (IllegalPropertySetDataException)
                {
                        
                    Assert.IsTrue(true);
                }
            }
            
            
            
            if (File.Exists(@".\Test-HPSF.ole2"))
            {
                File.Delete(@".\Test-HPSF.ole2");
            }
        }
Ejemplo n.º 8
0
        public void TestShortLastBlock()
        {
            String[] files = new String[] { "ShortLastBlock.qwp", "ShortLastBlock.wps" };

            for (int i = 0; i < files.Length; i++)
            {
                // Open the file up
                POIFSFileSystem fs = new POIFSFileSystem(
                        _samples.OpenResourceAsStream(files[i])
                );

                // Write it into a temp output array
                MemoryStream baos = new MemoryStream();
                fs.WriteFileSystem(baos);

                // Check sizes
            }
        }
Ejemplo n.º 9
0
        public void TestSingleEmptyDocument()
        {
            POIFSFileSystem fs = new POIFSFileSystem();
            DirectoryEntry dir = fs.Root;
            dir.CreateDocument("Foo", new MemoryStream(new byte[] { }));

            MemoryStream output = new MemoryStream();
            fs.WriteFileSystem(output);
            byte[] temp = output.ToArray();
            Assert.IsNotNull(new POIFSFileSystem(new MemoryStream(temp)));
        }
Ejemplo n.º 10
0
        public void TestEmptyDocumentEventWithFriend()
        {
            POIFSFileSystem fs = new POIFSFileSystem();
            DirectoryEntry dir = fs.Root;
            dir.CreateDocument("Bar", 1, new AnonymousClass1());
            dir.CreateDocument("Foo", 0, new EmptyClass());

            MemoryStream output = new MemoryStream();
            fs.WriteFileSystem(output);
            Assert.IsNotNull(new POIFSFileSystem(new MemoryStream(output.ToArray())));

        }
Ejemplo n.º 11
0
        public void TestWriteWellKnown1()
        {
        POIDataSamples _samples = POIDataSamples.GetHPSFInstance();
        using (FileStream doc1 = _samples.GetFile(POI_FS))
        {

            /* Read a Test document <em>doc1</em> into a POI filesystem. */
            POIFSFileSystem poifs = new POIFSFileSystem(doc1);
            DirectoryEntry dir = poifs.Root;
            DocumentEntry siEntry = (DocumentEntry)dir.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME);
            DocumentEntry dsiEntry = (DocumentEntry)dir.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);

            /*
             * Read the summary information stream and the document summary
             * information stream from the POI filesystem.
             * 
             * Please note that the result consists of SummaryInformation and
             * DocumentSummaryInformation instances which are in memory only. To
             * make them permanent they have to be written to a POI filesystem
             * explicitly (overwriting the former contents). Then the POI filesystem
             * should be saved to a file.
             */
            DocumentInputStream dis = new DocumentInputStream(siEntry);
            PropertySet ps = new PropertySet(dis);
            SummaryInformation si = new SummaryInformation(ps);
            dis = new DocumentInputStream(dsiEntry);
            ps = new PropertySet(dis);
            DocumentSummaryInformation dsi = new DocumentSummaryInformation(ps);

            /*
             * Write all properties supported by HPSF to the summary information
             * (e.g. author, edit date, application name) and to the document
             * summary information (e.g. company, manager).
             */
            Calendar cal = new GregorianCalendar();
            //long time1 = (long)cal.GetMilliseconds(new DateTime(2000, 6, 6, 6, 6, 6));

            //long time2 = (long)cal.GetMilliseconds(new DateTime(2001, 7, 7, 7, 7, 7));
            //long time3 = (long)cal.GetMilliseconds(new DateTime(2002, 8, 8, 8, 8, 8));

            int nr = 4711;
            String P_APPLICATION_NAME = "Microsoft Office Word";
            String P_AUTHOR = "Rainer Klute";
            int P_CHAR_COUNT = 125;
            String P_COMMENTS = "";  //"Comments";
            DateTime P_CREATE_DATE_TIME = new DateTime(2006, 2, 1, 7, 36, 0);
            long P_EDIT_TIME = ++nr * 1000 * 10;
            String P_KEYWORDS = "Test HPSF SummaryInformation DocumentSummaryInformation Writing";
            String P_LAST_AUTHOR = "LastAuthor";
            DateTime? P_LAST_PRINTED = null;
            DateTime P_LAST_SAVE_DATE_TIME = new DateTime(2008, 9, 30, 9, 54, 0);
            int P_PAGE_COUNT = 1;
            String P_REV_NUMBER = "RevNumber";
            int P_SECURITY = 1;
            String P_SUBJECT = "Subject";
            String P_TEMPLATE = "Normal.dotm";
            // FIXME (byte array properties not yet implemented): byte[] P_THUMBNAIL = new byte[123];
            String P_TITLE = "This document is used for testing POI HPSF¡¯s writing capabilities for the summary information stream and the document summary information stream";
            int P_WORD_COUNT = 21;

            int P_BYTE_COUNT = ++nr;
            String P_CATEGORY = "Category";
            String P_COMPANY = "Rainer Klute IT-Consulting GmbH";
            // FIXME (byte array properties not yet implemented): byte[]  P_DOCPARTS = new byte[123];
            // FIXME (byte array properties not yet implemented): byte[]  P_HEADING_PAIR = new byte[123];
            int P_HIDDEN_COUNT = ++nr;
            int P_LINE_COUNT = ++nr;
            bool P_LINKS_DIRTY = true;
            String P_MANAGER = "Manager";
            int P_MM_CLIP_COUNT = ++nr;
            int P_NOTE_COUNT = ++nr;
            int P_PAR_COUNT = ++nr;
            String P_PRESENTATION_FORMAT = "PresentationFormat";
            bool P_SCALE = false;
            int P_SLIDE_COUNT = ++nr;
            DateTime now = DateTime.Now;

            int POSITIVE_INTEGER = 2222;
            long POSITIVE_LONG = 3333;
            Double POSITIVE_DOUBLE = 4444;
            int NEGATIVE_INTEGER = 2222;
            long NEGATIVE_LONG = 3333;
            Double NEGATIVE_DOUBLE = 4444;

            int MAX_INTEGER = int.MaxValue;
            int MIN_INTEGER = int.MinValue;
            long MAX_LONG = long.MaxValue;
            long MIN_LONG = long.MinValue;
            Double MAX_DOUBLE = Double.MaxValue;
            Double MIN_DOUBLE = Double.MinValue;

            si.ApplicationName = P_APPLICATION_NAME;
            si.Author = P_AUTHOR;
            si.CharCount = P_CHAR_COUNT;
            si.Comments = P_COMMENTS;
            si.CreateDateTime = P_CREATE_DATE_TIME;
            si.EditTime = P_EDIT_TIME;
            si.Keywords = P_KEYWORDS;
            si.LastAuthor = P_LAST_AUTHOR;
            si.LastPrinted = P_LAST_PRINTED;
            si.LastSaveDateTime = P_LAST_SAVE_DATE_TIME;
            si.PageCount = P_PAGE_COUNT;
            si.RevNumber = P_REV_NUMBER;
            si.Security = P_SECURITY;
            si.Subject = P_SUBJECT;
            si.Template = P_TEMPLATE;
            // FIXME (byte array properties not yet implemented): si.Thumbnail=P_THUMBNAIL;
            si.Title = P_TITLE;
            si.WordCount = P_WORD_COUNT;

            dsi.ByteCount = P_BYTE_COUNT;
            dsi.Category = P_CATEGORY;
            dsi.Company = P_COMPANY;
            // FIXME (byte array properties not yet implemented): dsi.Docparts=P_DOCPARTS;
            // FIXME (byte array properties not yet implemented): dsi.HeadingPair=P_HEADING_PAIR;
            dsi.HiddenCount = P_HIDDEN_COUNT;
            dsi.LineCount = P_LINE_COUNT;
            dsi.LinksDirty = P_LINKS_DIRTY;
            dsi.Manager = P_MANAGER;
            dsi.MMClipCount = P_MM_CLIP_COUNT;
            dsi.NoteCount = P_NOTE_COUNT;
            dsi.ParCount = P_PAR_COUNT;
            dsi.PresentationFormat = P_PRESENTATION_FORMAT;
            dsi.Scale = P_SCALE;
            dsi.SlideCount = P_SLIDE_COUNT;

            CustomProperties customProperties = dsi.CustomProperties;
            if (customProperties == null)
                customProperties = new CustomProperties();
            customProperties.Put("Schlüssel 1", "Wert 1");
            customProperties.Put("Schlüssel 2", "Wert 2");
            customProperties.Put("Schlüssel 3", "Wert 3");
            customProperties.Put("Schlüssel 4", "Wert 4");
            customProperties.Put("positive_int", POSITIVE_INTEGER);
            customProperties.Put("positive_long", POSITIVE_LONG);
            customProperties.Put("positive_Double", POSITIVE_DOUBLE);
            customProperties.Put("negative_int", NEGATIVE_INTEGER);
            customProperties.Put("negative_long", NEGATIVE_LONG);
            customProperties.Put("negative_Double", NEGATIVE_DOUBLE);
            customProperties.Put("Boolean", true);
            customProperties.Put("Date", now);
            customProperties.Put("max_int", MAX_INTEGER);
            customProperties.Put("min_int", MIN_INTEGER);
            customProperties.Put("max_long", MAX_LONG);
            customProperties.Put("min_long", MIN_LONG);
            customProperties.Put("max_Double", MAX_DOUBLE);
            customProperties.Put("min_Double", MIN_DOUBLE);
            dsi.CustomProperties = customProperties;

            /* Write the summary information stream and the document summary
             * information stream to the POI filesystem. */
            si.Write(dir, siEntry.Name);
            dsi.Write(dir, dsiEntry.Name);

            /* Write the POI filesystem to a (temporary) file <em>doc2</em>
             * and Close the latter. */
            using (FileStream doc2 = File.Create( @"\POI_HPSF_Test2.tmp"))
            {

                poifs.WriteFileSystem(doc2);
                //doc2.Flush();

                /*
                 * Open <em>doc2</em> for Reading and check summary information and
                 * document summary information. All properties written before must be
                 * found in the property streams of <em>doc2</em> and have the correct
                 * values.
                 */
                doc2.Flush();
                doc2.Position = 0;
                POIFSFileSystem poifs2 = new POIFSFileSystem(doc2);
                dir = poifs2.Root;
                siEntry = (DocumentEntry)dir.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME);
                dsiEntry = (DocumentEntry)dir.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);

                dis = new DocumentInputStream(siEntry);
                ps = new PropertySet(dis);
                si = new SummaryInformation(ps);
                dis = new DocumentInputStream(dsiEntry);
                ps = new PropertySet(dis);
                dsi = new DocumentSummaryInformation(ps);

                Assert.AreEqual(P_APPLICATION_NAME, si.ApplicationName);
                Assert.AreEqual(P_AUTHOR, si.Author);
                Assert.AreEqual(P_CHAR_COUNT, si.CharCount);
                Assert.AreEqual(P_COMMENTS, si.Comments);
                Assert.AreEqual(P_CREATE_DATE_TIME, si.CreateDateTime);
                Assert.AreEqual(P_EDIT_TIME, si.EditTime);
                Assert.AreEqual(P_KEYWORDS, si.Keywords);
                Assert.AreEqual(P_LAST_AUTHOR, si.LastAuthor);
                Assert.AreEqual(P_LAST_PRINTED, si.LastPrinted);
                Assert.AreEqual(P_LAST_SAVE_DATE_TIME, si.LastSaveDateTime);
                Assert.AreEqual(P_PAGE_COUNT, si.PageCount);
                Assert.AreEqual(P_REV_NUMBER, si.RevNumber);
                Assert.AreEqual(P_SECURITY, si.Security);
                Assert.AreEqual(P_SUBJECT, si.Subject);
                Assert.AreEqual(P_TEMPLATE, si.Template);
                // FIXME (byte array properties not yet implemented): Assert.AreEqual(P_THUMBNAIL, si.Thumbnail);
                Assert.AreEqual(P_TITLE, si.Title);
                Assert.AreEqual(P_WORD_COUNT, si.WordCount);

                Assert.AreEqual(P_BYTE_COUNT, dsi.ByteCount);
                Assert.AreEqual(P_CATEGORY, dsi.Category);
                Assert.AreEqual(P_COMPANY, dsi.Company);
                // FIXME (byte array properties not yet implemented): Assert.AreEqual(P_, dsi.Docparts);
                // FIXME (byte array properties not yet implemented): Assert.AreEqual(P_, dsi.HeadingPair);
                Assert.AreEqual(P_HIDDEN_COUNT, dsi.HiddenCount);
                Assert.AreEqual(P_LINE_COUNT, dsi.LineCount);
                Assert.AreEqual(P_LINKS_DIRTY, dsi.LinksDirty);
                Assert.AreEqual(P_MANAGER, dsi.Manager);
                Assert.AreEqual(P_MM_CLIP_COUNT, dsi.MMClipCount);
                Assert.AreEqual(P_NOTE_COUNT, dsi.NoteCount);
                Assert.AreEqual(P_PAR_COUNT, dsi.ParCount);
                Assert.AreEqual(P_PRESENTATION_FORMAT, dsi.PresentationFormat);
                Assert.AreEqual(P_SCALE, dsi.Scale);
                Assert.AreEqual(P_SLIDE_COUNT, dsi.SlideCount);

                CustomProperties cps = dsi.CustomProperties;
                //Assert.AreEqual(customProperties, cps);
                Assert.IsNull(cps["No value available"]);
                Assert.AreEqual("Wert 1", cps["Schlüssel 1"]);
                Assert.AreEqual("Wert 2", cps["Schlüssel 2"]);
                Assert.AreEqual("Wert 3", cps["Schlüssel 3"]);
                Assert.AreEqual("Wert 4", cps["Schlüssel 4"]);
                Assert.AreEqual(POSITIVE_INTEGER, cps["positive_int"]);
                Assert.AreEqual(POSITIVE_LONG, cps["positive_long"]);
                Assert.AreEqual(POSITIVE_DOUBLE, cps["positive_Double"]);
                Assert.AreEqual(NEGATIVE_INTEGER, cps["negative_int"]);
                Assert.AreEqual(NEGATIVE_LONG, cps["negative_long"]);
                Assert.AreEqual(NEGATIVE_DOUBLE, cps["negative_Double"]);
                Assert.AreEqual(true, cps["Boolean"]);
                Assert.AreEqual(now, cps["Date"]);
                Assert.AreEqual(MAX_INTEGER, cps["max_int"]);
                Assert.AreEqual(MIN_INTEGER, cps["min_int"]);
                Assert.AreEqual(MAX_LONG, cps["max_long"]);
                Assert.AreEqual(MIN_LONG, cps["min_long"]);
                Assert.AreEqual(MAX_DOUBLE, cps["max_Double"]);
                Assert.AreEqual(MIN_DOUBLE, cps["min_Double"]);

                /* Remove all properties supported by HPSF from the summary
                 * information (e.g. author, edit date, application name) and from the
                 * document summary information (e.g. company, manager). */
                si.RemoveApplicationName();
                si.RemoveAuthor();
                si.RemoveCharCount();
                si.RemoveComments();
                si.RemoveCreateDateTime();
                si.RemoveEditTime();
                si.RemoveKeywords();
                si.RemoveLastAuthor();
                si.RemoveLastPrinted();
                si.RemoveLastSaveDateTime();
                si.RemovePageCount();
                si.RemoveRevNumber();
                si.RemoveSecurity();
                si.RemoveSubject();
                si.RemoveTemplate();
                si.RemoveThumbnail();
                si.RemoveTitle();
                si.RemoveWordCount();

                dsi.RemoveByteCount();
                dsi.RemoveCategory();
                dsi.RemoveCompany();
                dsi.RemoveCustomProperties();
                dsi.RemoveDocparts();
                dsi.RemoveHeadingPair();
                dsi.RemoveHiddenCount();
                dsi.RemoveLineCount();
                dsi.RemoveLinksDirty();
                dsi.RemoveManager();
                dsi.RemoveMMClipCount();
                dsi.RemoveNoteCount();
                dsi.RemoveParCount();
                dsi.RemovePresentationFormat();
                dsi.RemoveScale();
                dsi.RemoveSlideCount();

                /* 
                 * <li>Write the summary information stream and the document summary
                 * information stream to the POI filesystem. */
                si.Write(dir, siEntry.Name);
                dsi.Write(dir, dsiEntry.Name);

                /* 
                 * <li>Write the POI filesystem to a (temporary) file <em>doc3</em>
                 * and Close the latter. */
                using (FileStream doc3 = File.Create( @"\POI_HPSF_Test3.tmp"))
                {

                    poifs2.WriteFileSystem(doc3);
                    doc3.Position = 0;

                    /* 
                     * Open <em>doc3</em> for Reading and check summary information
                     * and document summary information. All properties Removed before must not
                     * be found in the property streams of <em>doc3</em>.
                     */
                    POIFSFileSystem poifs3 = new POIFSFileSystem(doc3);


                    dir = poifs3.Root;
                    siEntry = (DocumentEntry)dir.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME);
                    dsiEntry = (DocumentEntry)dir.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);

                    dis = new DocumentInputStream(siEntry);
                    ps = new PropertySet(dis);
                    si = new SummaryInformation(ps);
                    dis = new DocumentInputStream(dsiEntry);
                    ps = new PropertySet(dis);
                    dsi = new DocumentSummaryInformation(ps);

                    Assert.AreEqual(null, si.ApplicationName);
                    Assert.AreEqual(null, si.Author);
                    Assert.AreEqual(0, si.CharCount);
                    Assert.IsTrue(si.WasNull);
                    Assert.AreEqual(null, si.Comments);
                    Assert.AreEqual(null, si.CreateDateTime);
                    Assert.AreEqual(0, si.EditTime);
                    Assert.IsTrue(si.WasNull);
                    Assert.AreEqual(null, si.Keywords);
                    Assert.AreEqual(null, si.LastAuthor);
                    Assert.AreEqual(null, si.LastPrinted);
                    Assert.AreEqual(null, si.LastSaveDateTime);
                    Assert.AreEqual(0, si.PageCount);
                    Assert.IsTrue(si.WasNull);
                    Assert.AreEqual(null, si.RevNumber);
                    Assert.AreEqual(0, si.Security);
                    Assert.IsTrue(si.WasNull);
                    Assert.AreEqual(null, si.Subject);
                    Assert.AreEqual(null, si.Template);
                    Assert.AreEqual(null, si.Thumbnail);
                    Assert.AreEqual(null, si.Title);
                    Assert.AreEqual(0, si.WordCount);
                    Assert.IsTrue(si.WasNull);

                    Assert.AreEqual(0, dsi.ByteCount);
                    Assert.IsTrue(dsi.WasNull);
                    Assert.AreEqual(null, dsi.Category);
                    Assert.AreEqual(null, dsi.CustomProperties);
                    // FIXME (byte array properties not yet implemented): Assert.AreEqual(null, dsi.Docparts);
                    // FIXME (byte array properties not yet implemented): Assert.AreEqual(null, dsi.HeadingPair);
                    Assert.AreEqual(0, dsi.HiddenCount);
                    Assert.IsTrue(dsi.WasNull);
                    Assert.AreEqual(0, dsi.LineCount);
                    Assert.IsTrue(dsi.WasNull);
                    Assert.AreEqual(false, dsi.LinksDirty);
                    Assert.IsTrue(dsi.WasNull);
                    Assert.AreEqual(null, dsi.Manager);
                    Assert.AreEqual(0, dsi.MMClipCount);
                    Assert.IsTrue(dsi.WasNull);
                    Assert.AreEqual(0, dsi.NoteCount);
                    Assert.IsTrue(dsi.WasNull);
                    Assert.AreEqual(0, dsi.ParCount);
                    Assert.IsTrue(dsi.WasNull);
                    Assert.AreEqual(null, dsi.PresentationFormat);
                    Assert.AreEqual(false, dsi.Scale);
                    Assert.IsTrue(dsi.WasNull);
                    Assert.AreEqual(0, dsi.SlideCount);
                    Assert.IsTrue(dsi.WasNull);
                }
            }
        }
            File.Delete( @"\POI_HPSF_Test3.tmp");
            File.Delete( @"\POI_HPSF_Test2.tmp");
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Write out this workbook to an Outputstream.  Constructs
        /// a new POI POIFSFileSystem, passes in the workbook binary representation  and
        /// Writes it out.
        /// </summary>
        /// <param name="stream">the java OutputStream you wish to Write the XLS to</param>
        public override void Write(Stream stream)
        {
            byte[] bytes = GetBytes();
            POIFSFileSystem fs = new POIFSFileSystem();

            if (this.DocumentSummaryInformation == null)
            {
                this.DocumentSummaryInformation = HPSF.PropertySetFactory.CreateDocumentSummaryInformation();
            }
            NPOI.HPSF.CustomProperties cp = this.DocumentSummaryInformation.CustomProperties;
            if(cp==null)
            {
                cp= new NPOI.HPSF.CustomProperties();
            }
            cp.Put("Generator", "NPOI");
            cp.Put("Generator Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
            this.DocumentSummaryInformation.CustomProperties = cp;
            if (this.SummaryInformation == null)
            {
                this.SummaryInformation = HPSF.PropertySetFactory.CreateSummaryInformation();
            }            
            this.SummaryInformation.ApplicationName = "NPOI";

            // For tracking what we've written out, used if we're
            //  going to be preserving nodes
            List<string> excepts = new List<string>(1);

            using (MemoryStream newMemoryStream = new MemoryStream(bytes))
            {
                // Write out the Workbook stream
                fs.CreateDocument(newMemoryStream, "Workbook");

                // Write out our HPFS properties, if we have them
                WriteProperties(fs, excepts);

                if (preserveNodes)
                {
                    // Don't Write out the old Workbook, we'll be doing our new one
                    // If the file had an "incorrect" name for the workbook stream,
                    // don't write the old one as we'll use the correct name shortly
                    excepts.AddRange(WORKBOOK_DIR_ENTRY_NAMES);

                    // Copy over all the other nodes to our new poifs
                    EntryUtils.CopyNodes(
                            new FilteringDirectoryNode(this.directory, excepts)
                            , new FilteringDirectoryNode(fs.Root, excepts)
                    );
                    // YK: preserve StorageClsid, it is important for embedded workbooks,
                    // see Bugzilla 47920
                    fs.Root.StorageClsid = (this.directory.StorageClsid);
                }
                fs.WriteFileSystem(stream);

            }
            
            bytes = null;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Write out this workbook to an Outputstream.  Constructs
        /// a new POI POIFSFileSystem, passes in the workbook binary representation  and
        /// Writes it out.
        /// </summary>
        /// <param name="stream">the java OutputStream you wish to Write the XLS to</param>
        public override void Write(Stream stream)
        {
            byte[] bytes = GetBytes();
            POIFSFileSystem fs = new POIFSFileSystem();
            // For tracking what we've written out, used if we're
            //  going to be preserving nodes
            IList excepts = new ArrayList(1);

            // Write out the Workbook stream
            fs.CreateDocument(new MemoryStream(bytes), "Workbook");

            // Write out our HPFS properties, if we have them
            WriteProperties(fs, excepts);

            if (preserveNodes)
            {
                // Don't Write out the old Workbook, we'll be doing our new one
                excepts.Add("Workbook");
                // If the file had WORKBOOK instead of Workbook, we'll Write it
                //  out correctly shortly, so don't include the old one
                excepts.Add("WORKBOOK");

                // Copy over all the other nodes to our new poifs
                CopyNodes(this.filesystem, fs, excepts);
            }
            fs.WriteFileSystem(stream);
        }
Ejemplo n.º 14
0
        public void TestAreDocumentsIdentical()
        {
            POIFSFileSystem fs = new POIFSFileSystem();
            DirectoryEntry dirA = fs.CreateDirectory("DirA");
            DirectoryEntry dirB = fs.CreateDirectory("DirB");

            DocumentEntry entryA1 = dirA.CreateDocument("Entry1", new ByteArrayInputStream(dataSmallA));
            DocumentEntry entryA1b = dirA.CreateDocument("Entry1b", new ByteArrayInputStream(dataSmallA));
            DocumentEntry entryA2 = dirA.CreateDocument("Entry2", new ByteArrayInputStream(dataSmallB));
            DocumentEntry entryB1 = dirB.CreateDocument("Entry1", new ByteArrayInputStream(dataSmallA));


            // Names must match
            Assert.AreEqual(false, entryA1.Name.Equals(entryA1b.Name));
            Assert.AreEqual(false, EntryUtils.AreDocumentsIdentical(entryA1, entryA1b));

            // Contents must match
            Assert.AreEqual(false, EntryUtils.AreDocumentsIdentical(entryA1, entryA2));

            // Parents don't matter if contents + names are the same
            Assert.AreEqual(false, entryA1.Parent.Equals(entryB1.Parent));
            Assert.AreEqual(true, EntryUtils.AreDocumentsIdentical(entryA1, entryB1));


            // Can work with NPOIFS + POIFS
            //ByteArrayOutputStream tmpO = new ByteArrayOutputStream();
            MemoryStream tmpO = new MemoryStream();
            fs.WriteFileSystem(tmpO);
            ByteArrayInputStream tmpI = new ByteArrayInputStream(tmpO.ToArray());
            NPOIFSFileSystem nfs = new NPOIFSFileSystem(tmpI);

            DirectoryEntry dN1 = (DirectoryEntry)nfs.Root.GetEntry("DirA");
            DirectoryEntry dN2 = (DirectoryEntry)nfs.Root.GetEntry("DirB");
            DocumentEntry eNA1 = (DocumentEntry)dN1.GetEntry(entryA1.Name);
            DocumentEntry eNA2 = (DocumentEntry)dN1.GetEntry(entryA2.Name);
            DocumentEntry eNB1 = (DocumentEntry)dN2.GetEntry(entryB1.Name);

            Assert.AreEqual(false, EntryUtils.AreDocumentsIdentical(eNA1, eNA2));
            Assert.AreEqual(true, EntryUtils.AreDocumentsIdentical(eNA1, eNB1));

            Assert.AreEqual(false, EntryUtils.AreDocumentsIdentical(eNA1, entryA1b));
            Assert.AreEqual(false, EntryUtils.AreDocumentsIdentical(eNA1, entryA2));

            Assert.AreEqual(true, EntryUtils.AreDocumentsIdentical(eNA1, entryA1));
            Assert.AreEqual(true, EntryUtils.AreDocumentsIdentical(eNA1, entryB1));
        }
Ejemplo n.º 15
0
        public void TestDictionary()
        {
            FileStream copy = File.Create( @"\Test-HPSF.ole2");
            //copy.deleteOnExit();

            /* Write: */
            FileStream out1 = copy;
            POIFSFileSystem poiFs = new POIFSFileSystem();
            MutablePropertySet ps1 = new MutablePropertySet();
            MutableSection s = (MutableSection)ps1.Sections[0];
            Hashtable m = new Hashtable(3, 1.0f);
            m[1] = "String 1";
            m[2] = "String 2";
            m[3] = "String 3";
            s.Dictionary = (m);
            s.SetFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID1);
            int codepage = (int)Constants.CP_UNICODE;
            s.SetProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
                          codepage);
            poiFs.CreateDocument(ps1.GetStream(), "Test");
            poiFs.WriteFileSystem(out1);

            /* Read back: */
            POIFile[] psf = Util.ReadPropertySets(copy);
            Assert.AreEqual(1, psf.Length);
            byte[] bytes = psf[0].GetBytes();
            Stream in1 = new ByteArrayInputStream(bytes);
            PropertySet ps2 = PropertySetFactory.Create(in1);

            /* Check if the result is a DocumentSummaryInformation stream, as
             * specified. */
            Assert.IsTrue(ps2.IsDocumentSummaryInformation);

            /* Compare the property Set stream with the corresponding one
             * from the origin file and check whether they are equal. */
            Assert.IsTrue(ps1.Equals(ps2));

            out1.Close();
            copy.Close();
            File.Delete( @"\Test-HPSF.ole2");

        }
Ejemplo n.º 16
0
        public void TestDictionaryWithInvalidCodepage()
        {
            try
            {
                FileStream copy = File.Create( @"\Test-HPSF.ole2");
                //copy.deleteOnExit();

                /* Write: */
                FileStream out1 = copy;
                POIFSFileSystem poiFs = new POIFSFileSystem();
                MutablePropertySet ps1 = new MutablePropertySet();
                MutableSection s = (MutableSection)ps1.Sections[0];
                Hashtable m = new Hashtable(3, 1.0f);
                m[1] = "String 1";
                m[2] = "String 2";
                m[3] = "String 3";
                s.Dictionary = (m);
                s.SetFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID1);
                int codepage = 12345;
                s.SetProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
                              codepage);
                poiFs.CreateDocument(ps1.GetStream(), "Test");
                poiFs.WriteFileSystem(out1);
                out1.Close();
                Assert.Fail("This Testcase did not detect the invalid codepage value.");
            }
            catch (IllegalPropertySetDataException)
            {
                //Assert.IsTrue(true);
            }
        }
Ejemplo n.º 17
0
        public int AddOlePackage(POIFSFileSystem poiData, String label, String fileName, String command)
        {
            DirectoryNode root = poiData.Root;
            Dictionary<String, ClassID> olemap = GetOleMap();
            foreach (KeyValuePair<String, ClassID> entry in olemap)
            {
                if (root.HasEntry(entry.Key))
                {
                    root.StorageClsid = (/*setter*/entry.Value);
                    break;
                }
            }

            MemoryStream bos = new MemoryStream();
            poiData.WriteFileSystem(bos);
            return AddOlePackage(bos.ToArray(), label, fileName, command);
        }
Ejemplo n.º 18
0
        public void TestEmptyDocumentWithFriend()
        {
            POIFSFileSystem fs = new POIFSFileSystem();
            DirectoryEntry dir = fs.Root;
            dir.CreateDocument("Bar", new MemoryStream(new byte[]{0}));
            dir.CreateDocument("Foo", new MemoryStream(new byte[]{}));

            MemoryStream output = new MemoryStream();
            fs.WriteFileSystem(output);
            Assert.IsNotNull(new POIFSFileSystem(new MemoryStream(output.ToArray())));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Write out this workbook to an Outputstream.  Constructs
        /// a new POI POIFSFileSystem, passes in the workbook binary representation  and
        /// Writes it out.
        /// </summary>
        /// <param name="stream">the java OutputStream you wish to Write the XLS to</param>
        public override void Write(Stream stream)
        {
            byte[] bytes = GetBytes();
            POIFSFileSystem fs = new POIFSFileSystem();
            
            // For tracking what we've written out, used if we're
            //  going to be preserving nodes
            List<string> excepts = new List<string>(1);

            using (MemoryStream newMemoryStream = new MemoryStream(bytes))
            {
                // Write out the Workbook stream
                fs.CreateDocument(newMemoryStream, "Workbook");

                // Write out our HPFS properties, if we have them
                WriteProperties(fs, excepts);

                if (preserveNodes)
                {
                    // Don't Write out the old Workbook, we'll be doing our new one
                    excepts.Add("Workbook");
                    // If the file had WORKBOOK instead of Workbook, we'll Write it
                    //  out correctly shortly, so don't include the old one
                    excepts.Add("WORKBOOK");

                    // Copy over all the other nodes to our new poifs
                    POIUtils.CopyNodes(directory, fs.Root, excepts);
                    // YK: preserve StorageClsid, it is important for embedded workbooks,
                    // see Bugzilla 47920
                    fs.Root.StorageClsid = (this.directory.StorageClsid);
                }
                fs.WriteFileSystem(stream);

            }
            
            bytes = null;
        }
Ejemplo n.º 20
0
        public void TestEmptyDocumentBug11744()
        {
            byte[] TestData = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            POIFSFileSystem fs = new POIFSFileSystem();
            fs.CreateDocument(new MemoryStream(new byte[0]), "Empty");
            fs.CreateDocument(new MemoryStream(TestData), "NotEmpty");
            MemoryStream output = new MemoryStream();
            fs.WriteFileSystem(output);

            // This line caused the error.
            fs = new POIFSFileSystem(new MemoryStream(output.ToArray()));

            DocumentEntry entry = (DocumentEntry)fs.Root.GetEntry("Empty");
            Assert.AreEqual(0, entry.Size, "Expected zero size");
            byte[] actualReadbackData;
            actualReadbackData = NPOI.Util.IOUtils.ToByteArray(new DocumentInputStream(entry));
            Assert.AreEqual(0, actualReadbackData.Length, "Expected zero read from stream");

            entry = (DocumentEntry)fs.Root.GetEntry("NotEmpty");
            actualReadbackData = NPOI.Util.IOUtils.ToByteArray(new DocumentInputStream(entry));
            Assert.AreEqual(TestData.Length, entry.Size, "Expected size was wrong");
            Assert.IsTrue(
                    Arrays.Equals(TestData,actualReadbackData), "Expected different data Read from stream");
        }
Ejemplo n.º 21
0
        public void TestNoFormatID()
        {
            FileInfo fi = TempFile.CreateTempFile(POI_FS, ".doc");
            using (FileStream file = new FileStream(fi.FullName, FileMode.Open, FileAccess.ReadWrite))
            {
                //FileStream filename = File.OpenRead(dataDir + POI_FS);
                //filename.deleteOnExit();

                /* Create a mutable property Set with a section that does not have the
                 * formatID Set: */
                FileStream out1 = file;
                POIFSFileSystem poiFs = new POIFSFileSystem();
                MutablePropertySet ps = new MutablePropertySet();
                ps.ClearSections();
                ps.AddSection(new MutableSection());

                /* Write it to a POIFS and the latter to disk: */
                try
                {
                    MemoryStream psStream = new MemoryStream();
                    ps.Write(psStream);
                    psStream.Close();
                    byte[] streamData = psStream.ToArray();
                    poiFs.CreateDocument(new MemoryStream(streamData),
                                         SummaryInformation.DEFAULT_STREAM_NAME);
                    poiFs.WriteFileSystem(out1);
                    out1.Close();
                    Assert.Fail("Should have thrown a NoFormatIDException.");
                }
                catch (Exception ex)
                {
                    Assert.IsTrue(ex is NoFormatIDException);
                }
                finally
                {
                    out1.Close();
                }
            }
            try
            {
                File.Delete(fi.FullName);
            }
            catch
            {
            }
        }
Ejemplo n.º 22
0
        /**
         * Writes out the word file that is represented by an instance of this class.
         *
         * @param out The OutputStream to write to.
         * @throws IOException If there is an unexpected IOException from the passed
         *         in OutputStream.
         */
        public override void Write(Stream out1)
        {
            // Initialize our streams for writing.
            HWPFFileSystem docSys = new HWPFFileSystem();
            HWPFStream mainStream = docSys.GetStream("WordDocument");
            HWPFStream tableStream = docSys.GetStream("1Table");
            //HWPFOutputStream dataStream = docSys.GetStream("Data");
            int tableOffset = 0;

            // FileInformationBlock fib = (FileInformationBlock)_fib.Clone();
            // clear the offSets and sizes in our FileInformationBlock.
            _fib.ClearOffsetsSizes();

            // determine the FileInformationBLock size
            int fibSize = _fib.GetSize();
            fibSize += POIFSConstants.SMALLER_BIG_BLOCK_SIZE -
                (fibSize % POIFSConstants.SMALLER_BIG_BLOCK_SIZE);

            // preserve space for the FileInformationBlock because we will be writing
            // it after we write everything else.
            byte[] placeHolder = new byte[fibSize];
            mainStream.Write(placeHolder);
            int mainOffset = mainStream.Offset;

            // write out the StyleSheet.
            _fib.SetFcStshf(tableOffset);
            _ss.WriteTo(tableStream);
            _fib.SetLcbStshf(tableStream.Offset - tableOffset);
            tableOffset = tableStream.Offset;

            // get fcMin and fcMac because we will be writing the actual text with the
            // complex table.
            int fcMin = mainOffset;

            // write out the Complex table, includes text.
            _fib.SetFcClx(tableOffset);
            _cft.WriteTo(mainStream, tableStream);
            _fib.SetLcbClx(tableStream.Offset - tableOffset);
            tableOffset = tableStream.Offset;
            int fcMac = mainStream.Offset;

            // write out the CHPBinTable.
            _fib.SetFcPlcfbteChpx(tableOffset);
            _cbt.WriteTo(docSys, fcMin);
            _fib.SetLcbPlcfbteChpx(tableStream.Offset - tableOffset);
            tableOffset = tableStream.Offset;


            // write out the PAPBinTable.
            _fib.SetFcPlcfbtePapx(tableOffset);
            _pbt.WriteTo(mainStream, tableStream, _cft.GetTextPieceTable());
            _fib.SetLcbPlcfbtePapx(tableStream.Offset - tableOffset);
            tableOffset = tableStream.Offset;
            /*
              * plcfendRef (endnote reference position table) Written immediately
              * after the previously recorded table if the document contains endnotes
              * 
              * plcfendTxt (endnote text position table) Written immediately after
              * the plcfendRef if the document contains endnotes
              * 
              * Microsoft Office Word 97-2007 Binary File Format (.doc)
              * Specification; Page 24 of 210
              */
            _endnotesTables.WriteRef(_fib, tableStream);
            _endnotesTables.WriteTxt(_fib, tableStream);
            tableOffset = tableStream.Offset;


            /*
             * plcffndRef (footnote reference position table) Written immediately
             * after the stsh if the document contains footnotes
             * 
             * plcffndTxt (footnote text position table) Written immediately after
             * the plcffndRef if the document contains footnotes
             * 
             * Microsoft Office Word 97-2007 Binary File Format (.doc)
             * Specification; Page 24 of 210
             */
            _footnotesTables.WriteRef(_fib, tableStream);
            _footnotesTables.WriteTxt(_fib, tableStream);
            tableOffset = tableStream.Offset;


            // write out the SectionTable.
            _fib.SetFcPlcfsed(tableOffset);
            _st.WriteTo(docSys, fcMin);
            _fib.SetLcbPlcfsed(tableStream.Offset - tableOffset);
            tableOffset = tableStream.Offset;

            // write out the list tables
            if (_lt != null)
            {
                _fib.SetFcPlcfLst(tableOffset);
                _lt.WriteListDataTo(tableStream);
                _fib.SetLcbPlcfLst(tableStream.Offset - tableOffset);
            }

            /*
             * plflfo (more list formats) Written immediately after the end of the
             * plcflst and its accompanying data, if there are any lists defined in
             * the document. This consists first of a PL of LFO records, followed by
             * the allocated data (if any) hanging off the LFOs. The allocated data
             * consists of the array of LFOLVLFs for each LFO (and each LFOLVLF is
             * immediately followed by some LVLs).
             * 
             * Microsoft Office Word 97-2007 Binary File Format (.doc)
             * Specification; Page 26 of 210
             */

            if (_lt != null)
            {
                _fib.SetFcPlfLfo(tableStream.Offset);
                _lt.WriteListOverridesTo(tableStream);
                _fib.SetLcbPlfLfo(tableStream.Offset - tableOffset);
                tableOffset = tableStream.Offset;
            }

            /*
  * sttbfBkmk (table of bookmark name strings) Written immediately after
  * the previously recorded table, if the document contains bookmarks.
  * 
  * Microsoft Office Word 97-2007 Binary File Format (.doc)
  * Specification; Page 27 of 210
  */
            if (_bookmarksTables != null)
            {
                _bookmarksTables.WriteSttbfBkmk(_fib, tableStream);
                tableOffset = tableStream.Offset;
            }

            // write out the saved-by table.
            if (_sbt != null)
            {
                _fib.SetFcSttbSavedBy(tableOffset);
                _sbt.WriteTo(tableStream);
                _fib.SetLcbSttbSavedBy(tableStream.Offset - tableOffset);

                tableOffset = tableStream.Offset;
            }

            // write out the revision mark authors table.
            if (_rmat != null)
            {
                _fib.SetFcSttbfRMark(tableOffset);
                _rmat.WriteTo(tableStream);
                _fib.SetLcbSttbfRMark(tableStream.Offset - tableOffset);

                tableOffset = tableStream.Offset;
            }

            // write out the FontTable.
            _fib.SetFcSttbfffn(tableOffset);
            _ft.WriteTo(docSys);
            _fib.SetLcbSttbfffn(tableStream.Offset - tableOffset);
            tableOffset = tableStream.Offset;

            // write out the DocumentProperties.
            _fib.SetFcDop(tableOffset);
            byte[] buf = new byte[_dop.GetSize()];
            _fib.SetLcbDop(_dop.GetSize());
            _dop.Serialize(buf, 0);
            tableStream.Write(buf);



            // set some variables in the FileInformationBlock.
            _fib.SetFcMin(fcMin);
            _fib.SetFcMac(fcMac);
            _fib.SetCbMac(mainStream.Offset);

            // make sure that the table, doc and data streams use big blocks.
            byte[] mainBuf = mainStream.ToArray();
            if (mainBuf.Length < 4096)
            {
                byte[] tempBuf = new byte[4096];
                Array.Copy(mainBuf, 0, tempBuf, 0, mainBuf.Length);
                mainBuf = tempBuf;
            }

            // write out the FileInformationBlock.
            //_fib.Serialize(mainBuf, 0);
            _fib.WriteTo(mainBuf, tableStream);

            byte[] tableBuf = tableStream.ToArray();
            if (tableBuf.Length < 4096)
            {
                byte[] tempBuf = new byte[4096];
                Array.Copy(tableBuf, 0, tempBuf, 0, tableBuf.Length);
                tableBuf = tempBuf;
            }

            byte[] dataBuf = _dataStream;
            if (dataBuf == null)
            {
                dataBuf = new byte[4096];
            }
            if (dataBuf.Length < 4096)
            {
                byte[] tempBuf = new byte[4096];
                Array.Copy(dataBuf, 0, tempBuf, 0, dataBuf.Length);
                dataBuf = tempBuf;
            }


            // spit out the Word document.
            POIFSFileSystem pfs = new POIFSFileSystem();
            pfs.CreateDocument(new MemoryStream(mainBuf), "WordDocument");
            pfs.CreateDocument(new MemoryStream(tableBuf), "1Table");
            pfs.CreateDocument(new MemoryStream(dataBuf), "Data");
            WriteProperties(pfs);

            pfs.WriteFileSystem(out1);
        }
Ejemplo n.º 23
0
        public void TestWriteEmptyPropertySet()
        {
            FileInfo fi = TempFile.CreateTempFile(POI_FS, ".doc");
            using (FileStream file = new FileStream(fi.FullName, FileMode.Open, FileAccess.ReadWrite))
            {
                //filename.deleteOnExit();

                /* Create a mutable property Set and Write it to a POIFS: */
                FileStream out1 = file;
                POIFSFileSystem poiFs = new POIFSFileSystem();
                MutablePropertySet ps = new MutablePropertySet();
                MutableSection s = (MutableSection)ps.Sections[0];
                s.SetFormatID(SectionIDMap.SUMMARY_INFORMATION_ID);

                MemoryStream psStream = new MemoryStream();
                ps.Write(psStream);
                psStream.Close();
                byte[] streamData = psStream.ToArray();
                poiFs.CreateDocument(new MemoryStream(streamData),
                                     SummaryInformation.DEFAULT_STREAM_NAME);
                poiFs.WriteFileSystem(out1);
                //out1.Close();
                file.Position = 0;
                /* Read the POIFS: */
                POIFSReader reader3 = new POIFSReader();
                reader3.StreamReaded += new POIFSReaderEventHandler(reader3_StreamReaded);
                reader3.Read(file);
                file.Close();
                //File.Delete(dataDir + POI_FS);
            }
            try
            {
                File.Delete(fi.FullName);
            }
            catch
            {
            }
        }
Ejemplo n.º 24
0
        public void TestBATandXBAT()
        {
            byte[] hugeStream = new byte[8 * 1024 * 1024];
            POIFSFileSystem fs = new POIFSFileSystem();
            fs.Root.CreateDocument("BIG", new MemoryStream(hugeStream));

            MemoryStream baos = new MemoryStream();
            fs.WriteFileSystem(baos);
            byte[] fsData = baos.ToArray();


            // Check the header was written properly
            Stream inp = new MemoryStream(fsData);
            HeaderBlock header = new HeaderBlock(inp);
            Assert.AreEqual(109 + 21, header.BATCount);
            Assert.AreEqual(1, header.XBATCount);

            ByteBuffer xbatData = ByteBuffer.CreateBuffer(512);
            xbatData.Write(fsData, (1 + header.XBATIndex) * 512, 512);

            xbatData.Position = 0;

            BATBlock xbat = BATBlock.CreateBATBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, xbatData);

            for (int i = 0; i < 21; i++)
            {
                Assert.IsTrue(xbat.GetValueAt(i) != POIFSConstants.UNUSED_BLOCK);
            }

            for (int i = 21; i < 127; i++)
                Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, xbat.GetValueAt(i));

            Assert.AreEqual(POIFSConstants.END_OF_CHAIN, xbat.GetValueAt(127));

            RawDataBlockList blockList = new RawDataBlockList(inp, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS);
            Assert.AreEqual(fsData.Length / 512, blockList.BlockCount() + 1);
            new BlockAllocationTableReader(header.BigBlockSize,
                                            header.BATCount,
                                            header.BATArray,
                                            header.XBATCount,
                                            header.XBATIndex,
                                            blockList);
            Assert.AreEqual(fsData.Length / 512, blockList.BlockCount() + 1);

            //fs = null;
            //fs = new POIFSFileSystem(new MemoryStream(fsData));


            //DirectoryNode root = fs.Root;
            //Assert.AreEqual(1, root.EntryCount);
            //DocumentNode big = (DocumentNode)root.GetEntry("BIG");
            //Assert.AreEqual(hugeStream.Length, big.Size);

        }
Ejemplo n.º 25
0
        public void TestWriteSimplePropertySet()
        {
            String AUTHOR = "Rainer Klute";
            String TITLE = "Test Document";

            FileInfo fi = TempFile.CreateTempFile(POI_FS, ".doc");
            FileStream file = new FileStream(fi.FullName, FileMode.Open, FileAccess.ReadWrite);

            FileStream out1 = file;
            POIFSFileSystem poiFs = new POIFSFileSystem();

            MutablePropertySet ps = new MutablePropertySet();
            MutableSection si = new MutableSection();
            si.SetFormatID(SectionIDMap.SUMMARY_INFORMATION_ID);
            ps.Sections[0] = si;

            MutableProperty p = new MutableProperty();
            p.ID = PropertyIDMap.PID_AUTHOR;
            p.Type = Variant.VT_LPWSTR;
            p.Value = AUTHOR;
            si.SetProperty(p);
            si.SetProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPSTR, TITLE);

            poiFs.CreateDocument(ps.GetStream(),
                                 SummaryInformation.DEFAULT_STREAM_NAME);
            poiFs.WriteFileSystem(out1);
            //out1.Close();
            file.Position = 0;

            POIFSReader reader1 = new POIFSReader();
            //reader1.StreamReaded += new POIFSReaderEventHandler(reader1_StreamReaded);
            POIFSReaderListener1 psl = new POIFSReaderListener1();
            reader1.RegisterListener(psl);
            reader1.Read(file);
            Assert.IsNotNull(psa[0]);
            Assert.IsTrue(psa[0].IsSummaryInformation);

            Section s = (Section)(psa[0].Sections[0]);
            Object p1 = s.GetProperty(PropertyIDMap.PID_AUTHOR);
            Object p2 = s.GetProperty(PropertyIDMap.PID_TITLE);
            Assert.AreEqual(AUTHOR, p1);
            Assert.AreEqual(TITLE, p2);
            file.Close();
            try
            {
                File.Delete(fi.FullName);
            }
            catch
            {
            }
        }