コード例 #1
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);
                            }
                        }
                    }
                }
            }
        }
コード例 #2
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));
        }
コード例 #3
0
ファイル: TestXWPFDocument.cs プロジェクト: xewn/Npoi.Core
        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();
        }
コード例 #4
0
ファイル: XWPFHeaderFooter.cs プロジェクト: xewn/Npoi.Core
 internal override void OnDocumentRead()
 {
     foreach (POIXMLDocumentPart poixmlDocumentPart in GetRelations())
     {
         if (poixmlDocumentPart is XWPFPictureData)
         {
             XWPFPictureData xwpfPicData = (XWPFPictureData)poixmlDocumentPart;
             pictures.Add(xwpfPicData);
             document.RegisterPackagePictureData(xwpfPicData);
         }
     }
 }
コード例 #5
0
ファイル: TestXWPFDocument.cs プロジェクト: xewn/Npoi.Core
        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();
        }
コード例 #6
0
ファイル: TestXWPFDocument.cs プロジェクト: xewn/Npoi.Core
        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();
        }
コード例 #7
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));
        }
コード例 #8
0
ファイル: XWPFHeaderFooter.cs プロジェクト: xewn/Npoi.Core
        /**
         * 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.Dispose();
                        }
                    }
                    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.
                TargetMode          targetMode = TargetMode.Internal;
                PackagePartName     partName   = picDataPart.PartName;
                String              relation   = relDesc.Relation;
                PackageRelationship relShip    = GetPackagePart().AddRelationship(partName, targetMode, relation);
                String              id         = relShip.Id;
                AddRelation(id, xwpfPicData);
                pictures.Add(xwpfPicData);
                return(id);
            }
            else
            {
                /* Part already existed, Get relation id and return it */
                return(GetRelationId(xwpfPicData));
            }
        }
コード例 #9
0
        /**
         * Adds a picture to the run. This method handles
         *  attaching the picture data to the overall file.
         *
         * @see Npoi.Core.XWPF.UserModel.Document#PICTURE_TYPE_EMF
         * @see Npoi.Core.XWPF.UserModel.Document#PICTURE_TYPE_WMF
         * @see Npoi.Core.XWPF.UserModel.Document#PICTURE_TYPE_PICT
         * @see Npoi.Core.XWPF.UserModel.Document#PICTURE_TYPE_JPEG
         * @see Npoi.Core.XWPF.UserModel.Document#PICTURE_TYPE_PNG
         * @see Npoi.Core.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.Core.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));

            XDocument xmlDoc = new XDocument();

            //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.Core.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.Core.OpenXmlFormats.Dml.WordProcessing.CT_PositiveSize2D extent = inline.AddNewExtent();
            extent.cx = (width);
            extent.cy = (height);

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

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

            Npoi.Core.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.Core.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);
        }
コード例 #10
0
ファイル: XWPFPictureData.cs プロジェクト: ruo2012/Npoi.Core
        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));
        }