Exemple #1
0
        public void TestRead()
        {
            XWPFDocument            sampleDoc = XWPFTestDataSamples.OpenSampleDocument("VariousPictures.docx");
            IList <XWPFPictureData> pictures  = sampleDoc.AllPictures;

            Assert.AreEqual(5, pictures.Count);
            String[] ext = { "wmf", "png", "emf", "emf", "jpeg" };
            for (int i = 0; i < pictures.Count; i++)
            {
                Assert.AreEqual(ext[i], pictures[(i)].SuggestFileExtension());
            }

            int num = pictures.Count;

            byte[] pictureData = XWPFTestDataSamples.GetImage("nature1.jpg");

            String relationId = sampleDoc.AddPictureData(pictureData, (int)PictureType.JPEG);

            // picture list was updated
            Assert.AreEqual(num + 1, pictures.Count);
            XWPFPictureData pict = (XWPFPictureData)sampleDoc.GetRelationById(relationId);

            Assert.AreEqual("jpeg", pict.SuggestFileExtension());
            Assert.IsTrue(Arrays.Equals(pictureData, pict.Data));
        }
        public override bool Equals(object obj)
        {
            if (obj == this)
            {
                return(true);
            }
            if (obj == null || !(obj is XWPFPictureData))
            {
                return(false);
            }
            XWPFPictureData xwpfPictureData = (XWPFPictureData)obj;
            PackagePart     packagePart1    = xwpfPictureData.GetPackagePart();
            PackagePart     packagePart2    = this.GetPackagePart();

            if (packagePart1 != null && packagePart2 == null || packagePart1 == null && packagePart2 != null)
            {
                return(false);
            }
            if (packagePart2 != null)
            {
                OPCPackage package1 = packagePart1.Package;
                OPCPackage package2 = packagePart2.Package;
                if (package1 != null && package2 == null || package1 == null && package2 != null || package2 != null && !package2.Equals((object)package1))
                {
                    return(false);
                }
            }
            if (!this.Checksum.Equals(xwpfPictureData.Checksum))
            {
                return(false);
            }
            return(Arrays.Equals((object)this.GetData(), (object)xwpfPictureData.GetData()));
        }
Exemple #3
0
        public void TestRegisterPackagePictureData()
        {
            XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_1.docx");

            /* manually assemble a new image package part*/
            OPCPackage      opcPckg      = doc.Package;
            XWPFRelation    jpgRelation  = XWPFRelation.IMAGE_JPEG;
            PackagePartName partName     = PackagingUriHelper.CreatePartName(jpgRelation.DefaultFileName.Replace('#', '2'));
            PackagePart     newImagePart = opcPckg.CreatePart(partName, jpgRelation.ContentType);

            byte[] nature1 = XWPFTestDataSamples.GetImage("abstract4.jpg");
            Stream os      = newImagePart.GetOutputStream();

            os.Write(nature1, 0, nature1.Length);
            os.Close();
            XWPFHeader          xwpfHeader   = doc.HeaderList[(0)];
            PackageRelationship relationship = xwpfHeader.GetPackagePart().AddRelationship(partName, TargetMode.Internal, jpgRelation.Relation);
            XWPFPictureData     newPicData   = new XWPFPictureData(newImagePart, relationship);

            /* new part is now Ready to rumble */

            Assert.IsFalse(xwpfHeader.AllPictures.Contains(newPicData));
            Assert.IsFalse(doc.AllPictures.Contains(newPicData));
            Assert.IsFalse(doc.AllPackagePictures.Contains(newPicData));

            doc.RegisterPackagePictureData(newPicData);

            Assert.IsFalse(xwpfHeader.AllPictures.Contains(newPicData));
            Assert.IsFalse(doc.AllPictures.Contains(newPicData));
            Assert.IsTrue(doc.AllPackagePictures.Contains(newPicData));

            doc.Package.Revert();
        }
Exemple #4
0
        /**
         * Adds a picture to the document.
         *
         * @param pictureData       The picture data
         * @param format            The format of the picture.
         *
         * @return the index to this picture (0 based), the Added picture can be obtained from {@link #getAllPictures()} .
         * @throws InvalidFormatException
         */
        public String AddPictureData(byte[] pictureData, int format)
        {
            XWPFPictureData xwpfPicData = document.FindPackagePictureData(pictureData, format);
            POIXMLRelation  relDesc     = XWPFPictureData.RELATIONS[format];

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

                document.RegisterPackagePictureData(xwpfPicData);
                pictures.Add(xwpfPicData);
                return(GetRelationId(xwpfPicData));
            }
            else if (!GetRelations().Contains(xwpfPicData))
            {
                /*
                 * Part already existed, but was not related so far. Create
                 * relationship to the already existing part and update
                 * POIXMLDocumentPart data.
                 */
                PackagePart picDataPart = xwpfPicData.GetPackagePart();
                // TODO add support for TargetMode.EXTERNAL relations.
                RelationPart rp = AddRelation(null, XWPFRelation.IMAGES, xwpfPicData);
                pictures.Add(xwpfPicData);
                return(rp.Relationship.Id);
            }
            else
            {
                /* Part already existed, Get relation id and return it */
                return(GetRelationId(xwpfPicData));
            }
        }
Exemple #5
0
        public void TestBug51770()
        {
            XWPFDocument           doc    = XWPFTestDataSamples.OpenSampleDocument("Bug51170.docx");
            XWPFHeaderFooterPolicy policy = doc.GetHeaderFooterPolicy();
            XWPFHeader             header = policy.GetDefaultHeader();

            foreach (XWPFParagraph paragraph in header.Paragraphs)
            {
                foreach (XWPFRun run in paragraph.Runs)
                {
                    foreach (XWPFPicture picture in run.GetEmbeddedPictures())
                    {
                        if (paragraph.Document != null)
                        {
                            System.Console.WriteLine(picture.GetCTPicture());
                            XWPFPictureData data = picture.GetPictureData();
                            if (data != null)
                            {
                                System.Console.WriteLine(data.FileName);
                            }
                        }
                    }
                }
            }
        }
Exemple #6
0
        public XWPFPicture AddPicture(Stream pictureData, int pictureType, string filename, int width, int height)
        {
            XWPFDocument    document     = this.paragraph.GetDocument();
            string          id           = document.AddPictureData(pictureData, pictureType);
            XWPFPictureData relationById = (XWPFPictureData)document.GetRelationById(id);

            try
            {
                CT_Inline  ctInline = this.run.AddNewDrawing().AddNewInline();
                XmlElement element  = new XmlDocument().CreateElement("pic", "pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");
                ctInline.graphic             = new CT_GraphicalObject();
                ctInline.graphic.graphicData = new CT_GraphicalObjectData();
                ctInline.graphic.graphicData.AddPicElement((XmlElement)element.Clone());
                ctInline.distT = 0U;
                ctInline.distR = 0U;
                ctInline.distB = 0U;
                ctInline.distL = 0U;
                CT_NonVisualDrawingProps visualDrawingProps1 = ctInline.AddNewDocPr();
                long num = this.GetParagraph().GetDocument().GetDrawingIdManager().ReserveNew();
                visualDrawingProps1.id    = (uint)num;
                visualDrawingProps1.name  = "Drawing " + (object)num;
                visualDrawingProps1.descr = filename;
                CT_PositiveSize2D ctPositiveSize2D1 = ctInline.AddNewExtent();
                ctPositiveSize2D1.cx = (long)width;
                ctPositiveSize2D1.cy = (long)height;
                NPOI.OpenXmlFormats.Dml.Picture.CT_Picture ctPicture = this.GetCTPictures((object)ctInline.graphic.graphicData)[0];
                CT_PictureNonVisual      pictureNonVisual            = ctPicture.AddNewNvPicPr();
                CT_NonVisualDrawingProps visualDrawingProps2         = pictureNonVisual.AddNewCNvPr();
                visualDrawingProps2.id    = 0U;
                visualDrawingProps2.name  = "Picture " + (object)num;
                visualDrawingProps2.descr = filename;
                pictureNonVisual.AddNewCNvPicPr().AddNewPicLocks().noChangeAspect = true;
                CT_BlipFillProperties blipFillProperties = ctPicture.AddNewBlipFill();
                blipFillProperties.AddNewBlip().embed    = relationById.GetPackageRelationship().Id;
                blipFillProperties.AddNewStretch().AddNewFillRect();
                CT_ShapeProperties ctShapeProperties = ctPicture.AddNewSpPr();
                CT_Transform2D     ctTransform2D     = ctShapeProperties.AddNewXfrm();
                CT_Point2D         ctPoint2D         = ctTransform2D.AddNewOff();
                ctPoint2D.x = 0L;
                ctPoint2D.y = 0L;
                CT_PositiveSize2D ctPositiveSize2D2 = ctTransform2D.AddNewExt();
                ctPositiveSize2D2.cx = (long)width;
                ctPositiveSize2D2.cy = (long)height;
                CT_PresetGeometry2D presetGeometry2D = ctShapeProperties.AddNewPrstGeom();
                presetGeometry2D.prst = ST_ShapeType.rect;
                presetGeometry2D.AddNewAvLst();
                XWPFPicture xwpfPicture = new XWPFPicture(ctPicture, this);
                this.pictures.Add(xwpfPicture);
                return(xwpfPicture);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("", ex);
            }
        }
Exemple #7
0
 internal override void OnDocumentRead()
 {
     foreach (POIXMLDocumentPart relation in this.GetRelations())
     {
         if (relation is XWPFPictureData)
         {
             XWPFPictureData picData = (XWPFPictureData)relation;
             this.pictures.Add(picData);
             this.document.RegisterPackagePictureData(picData);
         }
     }
 }
Exemple #8
0
        public void TestFindPackagePictureData()
        {
            XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_1.docx");

            byte[]          nature1 = XWPFTestDataSamples.GetImage("nature1.gif");
            XWPFPictureData part    = doc.FindPackagePictureData(nature1, (int)PictureType.GIF);

            Assert.IsNotNull(part);
            Assert.IsTrue(doc.AllPictures.Contains(part));
            Assert.IsTrue(doc.AllPackagePictures.Contains(part));
            doc.Package.Revert();
        }
Exemple #9
0
 internal override void OnDocumentRead()
 {
     foreach (POIXMLDocumentPart poixmlDocumentPart in GetRelations())
     {
         if (poixmlDocumentPart is XWPFPictureData)
         {
             XWPFPictureData xwpfPicData = (XWPFPictureData)poixmlDocumentPart;
             pictures.Add(xwpfPicData);
             document.RegisterPackagePictureData(xwpfPicData);
         }
     }
 }
Exemple #10
0
 public XWPFPicture AddSvg(Stream svgData, Stream altPictureData, int altPictureType, String filename, int width, int height)
 {
     return(AddPicture(altPictureData, altPictureType, filename, width, height, (doc, blip) =>
     {
         String relationId = doc.AddPictureData(svgData, (int)PictureType.SVG);
         XWPFPictureData picData = (XWPFPictureData)doc.GetRelationById(relationId);
         var extLst = new CT_OfficeArtExtensionList();
         var extItem = new CT_OfficeArtExtension();
         extItem.uri = "{96DAC541-7B7A-43D3-8B79-37D633B846F1}";
         extItem.Any = "<asvg:svgBlip xmlns:asvg=\"http://schemas.microsoft.com/office/drawing/2016/SVG/main\" r:embed=\"" + picData.GetPackageRelationship().Id + "\"/>";
         extLst.ext.Add(extItem);
         blip.extLst = extLst;
     }));
 }
Exemple #11
0
        public string AddPictureData(byte[] pictureData, int format)
        {
            XWPFPictureData packagePictureData = this.document.FindPackagePictureData(pictureData, format);
            POIXMLRelation  descriptor         = XWPFPictureData.RELATIONS[format];

            if (packagePictureData == null)
            {
                int             nextPicNameNumber = this.document.GetNextPicNameNumber(format);
                XWPFPictureData relationship      = (XWPFPictureData)this.CreateRelationship(descriptor, (POIXMLFactory)XWPFFactory.GetInstance(), nextPicNameNumber);
                PackagePart     packagePart       = relationship.GetPackagePart();
                Stream          stream            = (Stream)null;
                try
                {
                    stream = packagePart.GetOutputStream();
                    stream.Write(pictureData, 0, pictureData.Length);
                }
                catch (IOException ex)
                {
                    throw new POIXMLException((Exception)ex);
                }
                finally
                {
                    try
                    {
                        stream.Close();
                    }
                    catch (IOException ex)
                    {
                    }
                }
                this.document.RegisterPackagePictureData(relationship);
                this.pictures.Add(relationship);
                return(this.GetRelationId((POIXMLDocumentPart)relationship));
            }
            if (this.GetRelations().Contains((POIXMLDocumentPart)packagePictureData))
            {
                return(this.GetRelationId((POIXMLDocumentPart)packagePictureData));
            }
            PackagePart     packagePart1 = packagePictureData.GetPackagePart();
            TargetMode      targetMode   = TargetMode.Internal;
            PackagePartName partName     = packagePart1.PartName;
            string          relation     = descriptor.Relation;
            string          id           = this.GetPackagePart().AddRelationship(partName, targetMode, relation).Id;

            this.AddRelation(id, (POIXMLDocumentPart)packagePictureData);
            this.pictures.Add(packagePictureData);
            return(id);
        }
Exemple #12
0
        public void TestPictureHandlingComplex()
        {
            XWPFDocument doc        = XWPFTestDataSamples.OpenSampleDocument("issue_51265_3.docx");
            XWPFHeader   xwpfHeader = doc.HeaderList[(0)];

            Assert.AreEqual(3, doc.AllPictures.Count);
            Assert.AreEqual(3, xwpfHeader.AllPictures.Count);
            Assert.AreEqual(5, doc.AllPackagePictures.Count);

            byte[]             nature1 = XWPFTestDataSamples.GetImage("nature1.jpg");
            String             id      = doc.AddPictureData(nature1, (int)PictureType.JPEG);
            POIXMLDocumentPart part1   = xwpfHeader.GetRelationById("rId1");
            XWPFPictureData    part2   = (XWPFPictureData)doc.GetRelationById(id);

            Assert.AreSame(part1, part2);

            doc.Package.Revert();
        }
Exemple #13
0
        public void RegisterPackagePictureData(XWPFPictureData picData)
        {
            List <XWPFPictureData> xwpfPictureDataList = (List <XWPFPictureData>)null;

            if (this.packagePictures.ContainsKey(picData.Checksum))
            {
                xwpfPictureDataList = this.packagePictures[picData.Checksum];
            }
            if (xwpfPictureDataList == null)
            {
                xwpfPictureDataList = new List <XWPFPictureData>(1);
                this.packagePictures.Add(picData.Checksum, xwpfPictureDataList);
            }
            if (xwpfPictureDataList.Contains(picData))
            {
                return;
            }
            xwpfPictureDataList.Add(picData);
        }
Exemple #14
0
        public XWPFPictureData FindPackagePictureData(byte[] pictureData, int format)
        {
            long                   checksum            = IOUtils.CalculateChecksum(pictureData);
            XWPFPictureData        xwpfPictureData     = (XWPFPictureData)null;
            List <XWPFPictureData> xwpfPictureDataList = (List <XWPFPictureData>)null;

            if (this.packagePictures.ContainsKey(checksum))
            {
                xwpfPictureDataList = this.packagePictures[checksum];
            }
            if (xwpfPictureDataList != null)
            {
                IEnumerator <XWPFPictureData> enumerator = (IEnumerator <XWPFPictureData>)xwpfPictureDataList.GetEnumerator();
                while (enumerator.MoveNext() && xwpfPictureData == null)
                {
                    XWPFPictureData current = enumerator.Current;
                    if (Arrays.Equals((object)pictureData, (object)current.GetData()))
                    {
                        xwpfPictureData = current;
                    }
                }
            }
            return(xwpfPictureData);
        }
Exemple #15
0
 public void RegisterPackagePictureData(XWPFPictureData picData)
 {
     List<XWPFPictureData> list = null;
     if(packagePictures.ContainsKey(picData.Checksum))
       list = packagePictures[(picData.Checksum)];
     if (list == null)
     {
         list = new List<XWPFPictureData>(1);
         packagePictures.Add(picData.Checksum, list);
     }
     if (!list.Contains(picData))
     {
         list.Add(picData);
     }
 }
Exemple #16
0
        /**
         * Adds a picture to the run. This method handles
         *  attaching the picture data to the overall file.
         *
         * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_EMF
         * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_WMF
         * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_PICT
         * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_JPEG
         * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_PNG
         * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_DIB
         *
         * @param pictureData The raw picture data
         * @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG}
         * @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
         * @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
         * @throws NPOI.Openxml4j.exceptions.InvalidFormatException
         * @throws IOException
         */
        public XWPFPicture AddPicture(Stream pictureData, int pictureType, String filename, int width, int height)
        {
            XWPFDocument doc = parent.Document;

            // Add the picture + relationship
            String          relationId = doc.AddPictureData(pictureData, pictureType);
            XWPFPictureData picData    = (XWPFPictureData)doc.GetRelationById(relationId);

            // Create the Drawing entry for it
            CT_Drawing Drawing = run.AddNewDrawing();
            CT_Inline  inline  = Drawing.AddNewInline();

            // Do the fiddly namespace bits on the inline
            // (We need full control of what goes where and as what)
            //CT_GraphicalObject tmp = new CT_GraphicalObject();
            //String xml =
            //    "<a:graphic xmlns:a=\"" + "http://schemas.openxmlformats.org/drawingml/2006/main" + "\">" +
            //    "<a:graphicData uri=\"" + "http://schemas.openxmlformats.org/drawingml/2006/picture" + "\">" +
            //    "<pic:pic xmlns:pic=\"" + "http://schemas.openxmlformats.org/drawingml/2006/picture" + "\" />" +
            //    "</a:graphicData>" +
            //    "</a:graphic>";
            //inline.Set((xml));

            XmlDocument xmlDoc = new XmlDocument();

            //XmlElement el = xmlDoc.CreateElement("pic", "pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");

            inline.graphic                 = new CT_GraphicalObject();
            inline.graphic.graphicData     = new CT_GraphicalObjectData();
            inline.graphic.graphicData.uri = "http://schemas.openxmlformats.org/drawingml/2006/picture";


            // Setup the inline
            inline.distT = (0);
            inline.distR = (0);
            inline.distB = (0);
            inline.distL = (0);

            NPOI.OpenXmlFormats.Dml.WordProcessing.CT_NonVisualDrawingProps docPr = inline.AddNewDocPr();
            long id = parent.Document.DrawingIdManager.ReserveNew();

            docPr.id = (uint)(id);
            /* This name is not visible in Word 2010 anywhere. */
            docPr.name  = ("Drawing " + id);
            docPr.descr = (filename);

            NPOI.OpenXmlFormats.Dml.WordProcessing.CT_PositiveSize2D extent = inline.AddNewExtent();
            extent.cx = (width);
            extent.cy = (height);

            // Grab the picture object
            NPOI.OpenXmlFormats.Dml.Picture.CT_Picture pic = new OpenXmlFormats.Dml.Picture.CT_Picture();

            // Set it up
            NPOI.OpenXmlFormats.Dml.Picture.CT_PictureNonVisual nvPicPr = pic.AddNewNvPicPr();

            NPOI.OpenXmlFormats.Dml.CT_NonVisualDrawingProps cNvPr = nvPicPr.AddNewCNvPr();
            /* use "0" for the id. See ECM-576, 20.2.2.3 */
            cNvPr.id = (0);
            /* This name is not visible in Word 2010 anywhere */
            cNvPr.name  = ("Picture " + id);
            cNvPr.descr = (filename);

            CT_NonVisualPictureProperties cNvPicPr = nvPicPr.AddNewCNvPicPr();

            cNvPicPr.AddNewPicLocks().noChangeAspect = true;

            CT_BlipFillProperties blipFill = pic.AddNewBlipFill();
            CT_Blip blip = blipFill.AddNewBlip();

            blip.embed = (picData.GetPackageRelationship().Id);
            blipFill.AddNewStretch().AddNewFillRect();

            CT_ShapeProperties spPr = pic.AddNewSpPr();
            CT_Transform2D     xfrm = spPr.AddNewXfrm();

            CT_Point2D off = xfrm.AddNewOff();

            off.x = (0);
            off.y = (0);

            NPOI.OpenXmlFormats.Dml.CT_PositiveSize2D ext = xfrm.AddNewExt();
            ext.cx = (width);
            ext.cy = (height);

            CT_PresetGeometry2D prstGeom = spPr.AddNewPrstGeom();

            prstGeom.prst = (ST_ShapeType.rect);
            prstGeom.AddNewAvLst();

            using (var ms = new MemoryStream())
            {
                StreamWriter sw = new StreamWriter(ms);
                pic.Write(sw, "pic:pic");
                sw.Flush();
                ms.Position = 0;
                var sr     = new StreamReader(ms);
                var picXml = sr.ReadToEnd();
                inline.graphic.graphicData.AddPicElement(picXml);
            }
            // Finish up
            XWPFPicture xwpfPicture = new XWPFPicture(pic, this);

            pictures.Add(xwpfPicture);
            return(xwpfPicture);
        }
Exemple #17
0
        public override bool Equals(Object obj)
        {
            /**
             * In case two objects ARE Equal, but its not the same instance, this
             * implementation will always run through the whole
             * byte-array-comparison before returning true. If this will turn into a
             * performance issue, two possible approaches are available:<br>
             * a) Use the Checksum only and take the risk that two images might have
             * the same CRC32 sum, although they are not the same.<br>
             * b) Use a second (or third) Checksum algorithm to minimise the chance
             * that two images have the same Checksums but are not equal (e.g.
             * CRC32, MD5 and SHA-1 Checksums, Additionally compare the
             * data-byte-array lengths).
             */
            if (obj == this)
            {
                return(true);
            }

            if (obj == null)
            {
                return(false);
            }

            if (!(obj is XWPFPictureData))
            {
                return(false);
            }

            XWPFPictureData picData            = (XWPFPictureData)obj;
            PackagePart     foreignPackagePart = picData.GetPackagePart();
            PackagePart     ownPackagePart     = this.GetPackagePart();

            if ((foreignPackagePart != null && ownPackagePart == null) ||
                (foreignPackagePart == null && ownPackagePart != null))
            {
                return(false);
            }

            if (ownPackagePart != null)
            {
                OPCPackage foreignPackage = foreignPackagePart.Package;
                OPCPackage ownPackage     = ownPackagePart.Package;

                if ((foreignPackage != null && ownPackage == null) ||
                    (foreignPackage == null && ownPackage != null))
                {
                    return(false);
                }
                if (ownPackage != null)
                {
                    if (!ownPackage.Equals(foreignPackage))
                    {
                        return(false);
                    }
                }
            }

            long foreignChecksum = picData.Checksum;
            long localChecksum   = Checksum;

            if (!(localChecksum.Equals(foreignChecksum)))
            {
                return(false);
            }
            return(Arrays.Equals(this.Data, picData.Data));
        }
Exemple #18
0
        public void TestRegisterPackagePictureData()
        {
            XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_1.docx");

            /* manually assemble a new image package part*/
            OPCPackage opcPckg = doc.Package;
            XWPFRelation jpgRelation = XWPFRelation.IMAGE_JPEG;
            PackagePartName partName = PackagingUriHelper.CreatePartName(jpgRelation.DefaultFileName.Replace('#', '2'));
            PackagePart newImagePart = opcPckg.CreatePart(partName, jpgRelation.ContentType);
            byte[] nature1 = XWPFTestDataSamples.GetImage("abstract4.jpg");
            Stream os = newImagePart.GetOutputStream();
            os.Write(nature1, 0, nature1.Length);
            os.Close();
            XWPFHeader xwpfHeader = doc.HeaderList[(0)];
            PackageRelationship relationship = xwpfHeader.GetPackagePart().AddRelationship(partName, TargetMode.Internal, jpgRelation.Relation);
            XWPFPictureData newPicData = new XWPFPictureData(newImagePart, relationship);
            /* new part is now Ready to rumble */

            Assert.IsFalse(xwpfHeader.AllPictures.Contains(newPicData));
            Assert.IsFalse(doc.AllPictures.Contains(newPicData));
            Assert.IsFalse(doc.AllPackagePictures.Contains(newPicData));

            doc.RegisterPackagePictureData(newPicData);

            Assert.IsFalse(xwpfHeader.AllPictures.Contains(newPicData));
            Assert.IsFalse(doc.AllPictures.Contains(newPicData));
            Assert.IsTrue(doc.AllPackagePictures.Contains(newPicData));

            doc.Package.Revert();
        }
Exemple #19
0
 internal override void OnDocumentRead()
 {
     try
     {
         DocumentDocument documentDocument = DocumentDocument.Parse(this.GetPackagePart().GetInputStream());
         this.ctDocument = documentDocument.Document;
         this.InitFootnotes();
         foreach (object obj in this.ctDocument.body.Items)
         {
             if (obj is CT_P)
             {
                 XWPFParagraph xwpfParagraph = new XWPFParagraph((CT_P)obj, (IBody)this);
                 this.bodyElements.Add((IBodyElement)xwpfParagraph);
                 this.paragraphs.Add(xwpfParagraph);
             }
             else if (obj is CT_Tbl)
             {
                 XWPFTable xwpfTable = new XWPFTable((CT_Tbl)obj, (IBody)this);
                 this.bodyElements.Add((IBodyElement)xwpfTable);
                 this.tables.Add(xwpfTable);
             }
         }
         if (documentDocument.Document.body.sectPr != null)
         {
             this.headerFooterPolicy = new XWPFHeaderFooterPolicy(this);
         }
         foreach (POIXMLDocumentPart relation1 in this.GetRelations())
         {
             string relationshipType = relation1.GetPackageRelationship().RelationshipType;
             if (relationshipType.Equals(XWPFRelation.STYLES.Relation))
             {
                 this.styles = (XWPFStyles)relation1;
                 this.styles.OnDocumentRead();
             }
             else if (relationshipType.Equals(XWPFRelation.NUMBERING.Relation))
             {
                 this.numbering = (XWPFNumbering)relation1;
                 this.numbering.OnDocumentRead();
             }
             else if (relationshipType.Equals(XWPFRelation.FOOTER.Relation))
             {
                 XWPFFooter xwpfFooter = (XWPFFooter)relation1;
                 this.footers.Add(xwpfFooter);
                 xwpfFooter.OnDocumentRead();
             }
             else if (relationshipType.Equals(XWPFRelation.HEADER.Relation))
             {
                 XWPFHeader xwpfHeader = (XWPFHeader)relation1;
                 this.headers.Add(xwpfHeader);
                 xwpfHeader.OnDocumentRead();
             }
             else if (relationshipType.Equals(XWPFRelation.COMMENT.Relation))
             {
                 foreach (CT_Comment comment in CommentsDocument.Parse(relation1.GetPackagePart().GetInputStream()).Comments.comment)
                 {
                     this.comments.Add(new XWPFComment(comment, this));
                 }
             }
             else if (relationshipType.Equals(XWPFRelation.SETTINGS.Relation))
             {
                 this.Settings = (XWPFSettings)relation1;
                 this.Settings.OnDocumentRead();
             }
             else if (relationshipType.Equals(XWPFRelation.IMAGES.Relation))
             {
                 XWPFPictureData picData = (XWPFPictureData)relation1;
                 picData.OnDocumentRead();
                 this.RegisterPackagePictureData(picData);
                 this.pictures.Add(picData);
             }
             else if (relationshipType.Equals(XWPFRelation.GLOSSARY_DOCUMENT.Relation))
             {
                 foreach (POIXMLDocumentPart relation2 in relation1.GetRelations())
                 {
                     try
                     {
                         relation2.OnDocumentRead();
                     }
                     catch (Exception ex)
                     {
                         throw new POIXMLException(ex);
                     }
                 }
             }
         }
         this.InitHyperlinks();
     }
     catch (XmlException ex)
     {
         throw new POIXMLException((Exception)ex);
     }
 }
Exemple #20
0
        public void TestNew()
        {
            XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("EmptyDocumentWithHeaderFooter.docx");

            byte[] jpegData = XWPFTestDataSamples.GetImage("nature1.jpg");
            Assert.IsNotNull(jpegData);
            byte[] gifData = XWPFTestDataSamples.GetImage("nature1.gif");
            Assert.IsNotNull(gifData);
            byte[] pngData = XWPFTestDataSamples.GetImage("nature1.png");
            Assert.IsNotNull(pngData);

            IList <XWPFPictureData> pictures = doc.AllPictures;

            Assert.AreEqual(0, pictures.Count);

            // Document shouldn't have any image relationships
            Assert.AreEqual(13, doc.GetPackagePart().Relationships.Size);
            foreach (PackageRelationship rel in doc.GetPackagePart().Relationships)
            {
                if (rel.RelationshipType.Equals(XSSFRelation.IMAGE_JPEG.Relation))
                {
                    Assert.Fail("Shouldn't have JPEG yet");
                }
            }

            // Add the image
            String relationId = doc.AddPictureData(jpegData, (int)PictureType.JPEG);

            Assert.AreEqual(1, pictures.Count);
            XWPFPictureData jpgPicData = (XWPFPictureData)doc.GetRelationById(relationId);

            Assert.AreEqual("jpeg", jpgPicData.SuggestFileExtension());
            Assert.IsTrue(Arrays.Equals(jpegData, jpgPicData.Data));

            // Ensure it now has one
            Assert.AreEqual(14, doc.GetPackagePart().Relationships.Size);
            PackageRelationship jpegRel = null;

            foreach (PackageRelationship rel in doc.GetPackagePart().Relationships)
            {
                if (rel.RelationshipType.Equals(XWPFRelation.IMAGE_JPEG.Relation))
                {
                    if (jpegRel != null)
                    {
                        Assert.Fail("Found 2 jpegs!");
                    }
                    jpegRel = rel;
                }
            }
            Assert.IsNotNull(jpegRel, "JPEG Relationship not found");

            // Check the details
            Assert.AreEqual(XWPFRelation.IMAGE_JPEG.Relation, jpegRel.RelationshipType);
            Assert.AreEqual("/word/document.xml", jpegRel.Source.PartName.ToString());
            Assert.AreEqual("/word/media/image1.jpeg", jpegRel.TargetUri.OriginalString);

            XWPFPictureData pictureDataByID = doc.GetPictureDataByID(jpegRel.Id);

            Assert.IsTrue(Arrays.Equals(jpegData, pictureDataByID.Data));

            // Save an re-load, check it appears
            doc = XWPFTestDataSamples.WriteOutAndReadBack(doc);
            Assert.AreEqual(1, doc.AllPictures.Count);
            Assert.AreEqual(1, doc.AllPackagePictures.Count);

            // verify the picture that we read back in
            pictureDataByID = doc.GetPictureDataByID(jpegRel.Id);
            Assert.IsTrue(Arrays.Equals(jpegData, pictureDataByID.Data));
        }