Пример #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));
        }
Пример #2
0
        public void TestPictureHandlingSimpleFile()
        {
            XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_1.docx");

            Assert.AreEqual(1, doc.AllPackagePictures.Count);
            byte[] newPic = XWPFTestDataSamples.GetImage("abstract4.jpg");
            String id1    = doc.AddPictureData(newPic, (int)PictureType.JPEG);

            Assert.AreEqual(2, doc.AllPackagePictures.Count);
            /* copy data, to avoid instance-Equality */
            byte[] newPicCopy = Arrays.CopyOf(newPic, newPic.Length);
            String id2        = doc.AddPictureData(newPicCopy, (int)PictureType.JPEG);

            Assert.AreEqual(id1, id2);
            doc.Package.Revert();
        }
Пример #3
0
        public void TestAddPicture()
        {
            XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx");

            byte[] jpeg       = XWPFTestDataSamples.GetImage("nature1.jpg");
            String relationId = doc.AddPictureData(jpeg, (int)PictureType.JPEG);

            byte[] newJpeg = ((XWPFPictureData)doc.GetRelationById(relationId)).Data;
            Assert.AreEqual(newJpeg.Length, jpeg.Length);
            for (int i = 0; i < jpeg.Length; i++)
            {
                Assert.AreEqual(newJpeg[i], jpeg[i]);
            }
        }
Пример #4
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();
        }
Пример #5
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));
        }
Пример #6
0
        public void TestAllPictureFormats()
        {
            XWPFDocument doc = new XWPFDocument();

            doc.AddPictureData(new byte[10], (int)PictureType.EMF);
            doc.AddPictureData(new byte[11], (int)PictureType.WMF);
            doc.AddPictureData(new byte[12], (int)PictureType.PICT);
            doc.AddPictureData(new byte[13], (int)PictureType.JPEG);
            doc.AddPictureData(new byte[14], (int)PictureType.PNG);
            doc.AddPictureData(new byte[15], (int)PictureType.DIB);
            doc.AddPictureData(new byte[16], (int)PictureType.GIF);
            doc.AddPictureData(new byte[17], (int)PictureType.TIFF);
            doc.AddPictureData(new byte[18], (int)PictureType.EPS);
            doc.AddPictureData(new byte[19], (int)PictureType.BMP);
            doc.AddPictureData(new byte[20], (int)PictureType.WPG);

            Assert.AreEqual(11, doc.AllPictures.Count);

            doc = XWPFTestDataSamples.WriteOutAndReadBack(doc);
            Assert.AreEqual(11, doc.AllPictures.Count);
        }
Пример #7
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);
        }
        /// <summary>
        /// 表格中查找替换
        /// </summary>
        /// <param name="CurCell"></param>
        /// <param name="PMember"></param>
        /// <param name="PResumes"></param>
        /// <param name="PRelations"></param>
        /// <param name="PPrizePunishs"></param>
        /// <param name="PAppraises"></param>
        private void ReplaceKeyInCell(XWPFDocument WDoc, XWPFTableCell CurCell, Lib.MemberInfoEntity PMember, List <MemberResume> PResumes, List <MemberRelations> PRelations, List <MemberPrizePunish> PPrizePunishs, List <MemberAppraise> PAppraises)
        {
            for (int i = 0; i < CurCell.Paragraphs.Count; i++)
            {
                XWPFParagraph CurPara = CurCell.Paragraphs[i];
                //头像
                if (CurPara.ParagraphText.Trim().Contains("[HeadImage]"))
                {
                    while (CurPara.Runs.Count > 0)
                    {
                        CurPara.RemoveRun(0);
                    }

                    if (_FixedDocVM.HeadImage != null && _FixedDocVM.HeadImage.StreamSource != null)
                    {
                        XWPFRun imageCellRun = CurPara.CreateRun();

                        //必须将流位置指针设置到开始处,否则显示不出来。
                        _FixedDocVM.HeadImage.StreamSource.Position = 0;

                        var picID = WDoc.AddPictureData(_FixedDocVM.HeadImage.StreamSource, (int)PictureType.PNG);

                        CreatePictureInLine(imageCellRun, picID, 100, 140);
                        // CreatePictureWithAnchor(imageCellRun, picID, 90, 120);
                    }
                    break;
                }
                //简历
                if (CurPara.ParagraphText.Trim().Contains("[Resume]"))
                {
                    if (PResumes != null && PResumes.Count > 0)
                    {
                        for (int pr = 0; pr < PResumes.Count; pr++)
                        {
                            string EndDateStr = PResumes[pr].EndDate.ToString("yyy.MM");
                            if (PResumes[pr].EndDate.Year == 1)
                            {
                                EndDateStr = "今";
                            }
                            string tempValue = $"{PResumes[pr].BeginDate:yyyy.MM}--{EndDateStr}  {PResumes[pr].Content}";
                            if (pr == 0)
                            {
                                CurPara.ReplaceText("[Resume]", tempValue);
                            }
                            else
                            {
                                XWPFParagraph NewParagraph = CurCell.AddParagraph();
                                XWPFRun       NewRun       = NewParagraph.CreateRun();
                                NewRun.FontFamily = CurPara.Runs[0].FontFamily;
                                NewRun.FontSize   = CurPara.Runs[0].FontSize;
                                NewRun.SetText(tempValue);
                            }
                        }
                    }
                    else
                    {
                        while (CurPara.Runs.Count > 0)
                        {
                            CurPara.RemoveRun(0);
                        }
                    }
                    break;
                }
                //奖情惩况
                if (CurPara.ParagraphText.Trim().Contains("[PrizePunish]"))
                {
                    if (PPrizePunishs != null && PPrizePunishs.Count > 0)
                    {
                        for (int pr = 0; pr < PPrizePunishs.Count; pr++)
                        {
                            string tempValue = $"{PPrizePunishs[pr].OccurDate:yyyy.MM}  {PPrizePunishs[pr].PrizrOrPunishUnit} {PPrizePunishs[pr].PrizrOrPunishName}";
                            if (pr == 0)
                            {
                                CurPara.ReplaceText("[PrizePunish]", tempValue);
                            }
                            else
                            {
                                XWPFParagraph NewParagraph = CurCell.AddParagraph();
                                XWPFRun       NewRun       = NewParagraph.CreateRun();
                                NewRun.FontFamily = CurPara.Runs[0].FontFamily;
                                NewRun.FontSize   = CurPara.Runs[0].FontSize;
                                NewRun.SetText(tempValue);
                            }
                        }
                    }
                    else
                    {
                        while (CurPara.Runs.Count > 0)
                        {
                            CurPara.RemoveRun(0);
                        }
                    }
                    break;
                }

                //近三年考核情况
                if (CurPara.ParagraphText.Trim().Contains("[Appraise]"))
                {
                    if (PAppraises != null && PAppraises.Count > 0)
                    {
                        for (int pr = 0; pr < PAppraises.Count; pr++)
                        {
                            string tempValue = $"{PAppraises[pr].Year:yyyy}  {PAppraises[pr].Result}";
                            if (pr == 0)
                            {
                                CurPara.ReplaceText("[Appraise]", tempValue);
                            }
                            else
                            {
                                XWPFParagraph NewParagraph = CurCell.AddParagraph();
                                XWPFRun       NewRun       = NewParagraph.CreateRun();
                                NewRun.FontFamily = CurPara.Runs[0].FontFamily;
                                NewRun.FontSize   = CurPara.Runs[0].FontSize;
                                NewRun.SetText(tempValue);
                            }
                        }
                    }
                    else
                    {
                        while (CurPara.Runs.Count > 0)
                        {
                            CurPara.RemoveRun(0);
                        }
                    }
                    break;
                }

                //主要社会关系
                if (CurPara.ParagraphText.Trim().Contains("[Relations"))
                {
                    string tempValue = "";
                    for (int p = 1; p <= 7; p++)
                    {
                        for (int k = 0; k <= 4; k++)
                        {
                            if (CurPara.ParagraphText.Trim().Equals($"[Relations{p}{k}]"))
                            {
                                if (PRelations != null && PRelations.Count >= p)
                                {
                                    switch (k)
                                    {
                                    case 0:
                                        tempValue = $"{PRelations[p - 1].Relation}";
                                        break;

                                    case 1:
                                        tempValue = $"{PRelations[p - 1].Name}";
                                        break;

                                    case 2:
                                        tempValue = $"{PRelations[p - 1].Birthday:yyyy.MM}";
                                        break;

                                    case 3:
                                        tempValue = $"{PRelations[p - 1].PoliticalStatus}";
                                        break;

                                    case 4:
                                        tempValue = $"{PRelations[p - 1].UnitName} {PRelations[p - 1].Role} {PRelations[p - 1].Remark}";
                                        break;
                                    }
                                }
                                CurPara.ReplaceText($"[Relations{p}{k}]", tempValue == null ? "" : tempValue.Trim());
                                break;
                            }
                        }
                    }
                }

                //基本信息
                {
                    Type           t  = PMember.GetType();
                    PropertyInfo[] pi = t.GetProperties();
                    foreach (PropertyInfo p in pi)
                    {
                        if (CurPara.ParagraphText.Trim().Contains($"[{p.Name}]"))
                        {
                            string CurValue = p.GetValue(PMember)?.ToString();
                            if (string.IsNullOrWhiteSpace(CurValue))
                            {
                                CurValue = "";
                            }
                            else
                            {
                                DateTime tempDate;
                                switch (p.Name)
                                {
                                case "Birthday":
                                    tempDate = DateTime.Parse(CurValue);
                                    CurValue = $"{tempDate:yyyy.MM}";
                                    XWPFParagraph NewParagraph = CurCell.AddParagraph();
                                    NewParagraph.Alignment = ParagraphAlignment.CENTER;
                                    XWPFRun NewRun = NewParagraph.CreateRun();
                                    NewRun.FontFamily = CurPara.Runs[0].FontFamily;
                                    NewRun.FontSize   = CurPara.Runs[0].FontSize;
                                    NewRun.SetText($"({DateTime.Now.Year - tempDate.Year}岁)");
                                    break;

                                case "JoinCPC":
                                    tempDate = DateTime.Parse(CurValue);
                                    CurValue = $"{tempDate:yyyy.MM}";
                                    break;

                                case "BeginWork":
                                    tempDate = DateTime.Parse(CurValue);
                                    CurValue = $"{tempDate:yyyy.MM}";
                                    break;
                                }
                            }
                            CurPara.ReplaceText("[" + p.Name + "]", CurValue);
                            break;
                        }
                    }
                }
            }
        }