public void DisplayImage(ImagePart ip)
        {
            try
            {
                Stream stream = ip.GetStream();

                if (ip.Uri.ToString().EndsWith(".svg"))
                {
                    MessageBox.Show("Format not currently supported.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    pbImage.Image    = pbImage.ErrorImage;
                    pbImage.SizeMode = PictureBoxSizeMode.CenterImage;
                }
                else
                {
                    Image imgStream = Image.FromStream(stream);
                    pbImage.Image = imgStream;

                    if (imgStream.Height > pbImage.Size.Height || imgStream.Width > pbImage.Size.Width)
                    {
                        pbImage.SizeMode = PictureBoxSizeMode.Zoom;
                    }
                    else
                    {
                        pbImage.SizeMode = PictureBoxSizeMode.CenterImage;
                    }
                }

                pbImage.Visible = true;
            }
            catch (Exception ex)
            {
                LoggingHelper.Log("ViewImages::UnableToDisplayImage : " + ex.Message);
            }
        }
        private string WriteImageFile(WordprocessingDocument document, string subdirectory, string unique, string name)
        {
            Assert.ArgumentNotNull(document, "document");
            Assert.ArgumentNotNullOrEmpty(subdirectory, "subdirectory");
            Assert.ArgumentNotNullOrEmpty(unique, "unique");
            Assert.ArgumentNotNullOrEmpty(name, "name");
            ImagePart imagePart = (ImagePart)document.MainDocumentPart.GetPartById(unique);

            Assert.IsNotNull(imagePart, "imagePart " + unique);
            Assert.IsNotNull(imagePart.Uri, "imagePart.Uri");
            string url = imagePart.Uri.ToString();
            int    pos = url.LastIndexOf(".", StringComparison.Ordinal);

            Assert.IsTrue(pos > -1, "pos");
            string ext = url.Substring(pos);

            Assert.IsNotNullOrEmpty(ext, "ext");
            Stream stream = imagePart.GetStream();
            long   length = stream.Length;

            byte[] byteStream = new byte[length];
            stream.Read(byteStream, 0, (int)length);
            string     path    = subdirectory + "\\" + name + "." + unique + ext;
            FileStream fstream = new FileStream(path, FileMode.OpenOrCreate);

            fstream.Write(byteStream, 0, (int)length);
            fstream.Close();
            return(path);
        }
Пример #3
0
        static void Main(string[] args)
        {
            String wordPath   = @"C:\Users\dxw\Desktop\123";  //word在哪里
            String jpgPathPro = @"C:\Users\dxw\Desktop\jpg\"; //jpg放哪里
            var    files      = Directory.GetFiles(wordPath, "*.docx");

            //在当前文件夹中遍历所有文档
            foreach (var file in files)
            {
                WordprocessingDocument docx = WordprocessingDocument.Open(file, true);
                foreach (var image in docx.MainDocumentPart.Document.Body.Descendants <ImageData>())
                {
                    ImagePart p      = docx.MainDocumentPart.GetPartById(image.RelationshipId) as ImagePart;
                    int       hash   = p.GetHashCode();
                    Stream    stream = p.GetStream();
                    byte[]    bytes  = new byte[stream.Length];
                    stream.Read(bytes, 0, bytes.Length);
                    stream.Seek(0, SeekOrigin.Begin);
                    string       jpgPath = jpgPathPro + hash + ".wmf";
                    FileStream   fs      = new FileStream(jpgPath, FileMode.Create);
                    BinaryWriter bw      = new BinaryWriter(fs);
                    bw.Write(bytes);
                    bw.Close();
                    fs.Close();
                }
            }
        }
Пример #4
0
        private void ShapeIsPicture(PageLayer _page, pp.Shape _shape, EAnimation _animation, string _idShape)
        {
            EImageContent eImage = new EImageContent();

            eImage.Name       = "Image";
            eImage.ID         = _idShape;
            eImage.Width      = _shape.Width * Utils.tlw;
            eImage.Height     = _shape.Height * Utils.tlh;
            eImage.Top        = _shape.Top * Utils.tlh;
            eImage.Left       = _shape.Left * Utils.tlw;
            eImage.Angle      = _shape.Rotation;
            eImage.ZOder      = (int)_shape.ZOrderPosition;
            eImage.Animations = _animation;
            eImage.RectCrop   = new ESuperPoint();
            var lstPic = Utils.slidePart.Slide.Descendants <DocumentFormat.OpenXml.Presentation.Picture>().Select(p => p);

            P.Picture picTag    = GetPictureTag(lstPic, _shape.Id.ToString());
            string    rID       = picTag.BlipFill.Blip.Embed.Value;
            ImagePart part      = (ImagePart)Utils.slidePart.GetPartById(rID);
            string    pathImage = Path.Combine((System.Windows.Application.Current as IAppGlobal).DocumentTempFolder, ObjectElementsHelper.RandomString(13) + Path.GetExtension(part.Uri.ToString()));

            Utils.CopyStream(part.GetStream(), pathImage);
            eImage.Image      = new Image();
            eImage.Image.Path = pathImage;
            _page.Children.Add(eImage);
        }
Пример #5
0
 public ImageData(ImagePart part)
 {
     ContentType = part.ContentType;
     using (Stream s = part.GetStream(FileMode.Open, FileAccess.Read))
     {
         Image = new byte[s.Length];
         s.Read(Image, 0, (int)s.Length);
     }
 }
Пример #6
0
        /// <summary>
        /// 根据图片信息保存图片 并返回图片的完整名字
        /// </summary>
        /// <param name="DOI">文章的DOI</param>
        /// <param name="contentType">图片的类型</param>
        /// <param name="imgindex">图片在文章中的位置</param>
        /// <param name="img">Image类的一个对象</param>
        /// <returns></returns>
        public string SaveImage(string DOI, string contentType, int imgindex, ImagePart imgpart)
        {
            string filenamewithoutsuffix = CreateImgName(DOI, imgindex);
            string suffix   = GetSuffix(contentType);
            string filename = filenamewithoutsuffix + "." + suffix;
            Image  img      = Image.FromStream(imgpart.GetStream());

            img.Save(filename);
            return(filename);
        }
Пример #7
0
        static Queue <NonnullRichTextBuilder> ReadAllLinesDocx(string path)
        {
            Queue <NonnullRichTextBuilder> richTexts = new Queue <NonnullRichTextBuilder>();
            WordprocessingDocument         doc       = null;

            try
            {
                doc = WordprocessingDocument.Open(path, false);
            }
            catch (OpenXmlPackageException)
            {
                return(richTexts);
            }
            catch (System.IO.IOException)
            {
                return(richTexts);
            }
            Body body = doc.MainDocumentPart.Document.Body;

            foreach (Paragraph paragraph in body.ChildElements.OfType <Paragraph>())
            {
                DocumentFormat.OpenXml.Drawing.Blip hasImage =
                    paragraph.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                if (hasImage == null)
                {
                    richTexts.Enqueue(new NonnullRichTextBuilder(paragraph.InnerText));
                }
                else
                {
                    List <object> runs = new List <object>();
                    foreach (Run docRun in paragraph.ChildElements.OfType <Run>())
                    {
                        DocumentFormat.OpenXml.Drawing.Blip imgContainer =
                            docRun.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                        if (imgContainer == null)
                        {
                            runs.Add(docRun.InnerText);
                        }
                        else
                        {
                            string           imgId      = imgContainer.Embed.Value;
                            ImagePart        imgPart    = doc.MainDocumentPart.GetPartById(imgId) as ImagePart;
                            System.IO.Stream imgStream  = imgPart.GetStream();
                            byte[]           imgInBytes = new byte[imgStream.Length];
                            imgStream.Read(imgInBytes, 0, (int)imgStream.Length);
                            runs.Add(imgInBytes);
                        }
                    }
                    NonnullRichTextBuilder richTextRuns = new NonnullRichTextBuilder(CompactRuns(runs));
                    richTexts.Enqueue(richTextRuns);
                }
            }
            doc.Close();
            return(richTexts);
        }
Пример #8
0
        private static MDSlide ParseSlidePart(IList <SlidePart> slideParts, int slideIndex)
        {
            var slidePart = slideParts[slideIndex];

            if (slidePart == null)
            {
                throw new ArgumentNullException("slidePart");
            }
            if (slidePart.Slide == null)
            {
                throw new ArgumentNullException("slidePart.Slide");
            }

            SlideType slideType = GetSlideType(slidePart, slideIndex);
            MDSlide   slide     = AssignSlide(slideType);

            // Extract texts
            var shapes = slidePart.Slide.Descendants <Shape>().Where(s => s.Descendants <Drawing.Paragraph>().Any());

            foreach (Shape shape in shapes)
            {
                if (string.IsNullOrWhiteSpace(shape.InnerText))
                {
                    continue;
                }
                slide.AddShapes(GetShapes(shape));
            }

            // Extract images
            var pictures = slidePart.Slide.Descendants <Picture>().ToList();

            foreach (var picture in pictures)
            {
                string    rId       = picture.BlipFill.Blip.Embed.Value;
                ImagePart imagePart = (ImagePart)slidePart.Slide.SlidePart.GetPartById(rId);
                Image     image     = Image.FromStream(imagePart.GetStream());

                SaveImageToFile(image, slideIndex);
                MDShapeImage mdImage = GetImage(slideIndex, image, picture);
                presentationImageIndex++;

                slide.AddShape(mdImage);
            }

            // Extract graphics
            var graphics = slidePart.Slide.Descendants <GraphicFrame>().ToList();

            foreach (var graphic in graphics)
            {
                // TODO: Find a way to export graphics as images
            }

            return(slide);
        }
Пример #9
0
        /// <summary>
        /// Sets the document background image
        /// </summary>
        /// <param name="imagePath">Path of the background image</param>
        public static OpenXmlPowerToolsDocument SetImage(WmlDocument doc, string imagePath)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    XDocument mainDocument = document.MainDocumentPart.GetXDocument();

                    // Adds the image to the package
                    ImagePart imagePart   = document.MainDocumentPart.AddImagePart(ImagePartType.Bmp);
                    Stream    imageStream = new StreamReader(imagePath).BaseStream;
                    byte[]    imageBytes  = new byte[imageStream.Length];
                    imageStream.Read(imageBytes, 0, imageBytes.Length);
                    imagePart.GetStream().Write(imageBytes, 0, imageBytes.Length);

                    // Creates a "background" element relating the image and the document

                    // If the background element already exists, deletes it
                    XElement backgroundElement = BackgroundElement(document);
                    if (backgroundElement != null)
                    {
                        backgroundElement.Remove();
                    }

                    // Background element construction
                    mainDocument.Root.Add(
                        new XElement(ns + "background",
                                     new XAttribute(ns + "color", defaultBackgroundColor),
                                     new XElement(vmlns + "background",
                                                  new XAttribute(vmlns + "id", defaultVmlBackgroundImageId),
                                                  new XAttribute(officens + "bwmode", defaultBWMode),
                                                  new XAttribute(officens + "targetscreensize", defaultTargetScreenSize),
                                                  new XElement(vmlns + "fill",
                                                               new XAttribute(relationshipsns + "id", document.MainDocumentPart.GetIdOfPart(imagePart)),
                                                               new XAttribute("recolor", defaultImageRecolor),
                                                               new XAttribute("type", defaultImageType)
                                                               )
                                                  )
                                     )
                        );


                    // Enables background displaying by adding "displayBackgroundShape" tag
                    if (SettingAccessor.DisplayBackgroundShapeElements(document) == null)
                    {
                        SettingAccessor.AddBackgroundShapeElement(document);
                    }

                    document.MainDocumentPart.PutXDocument();
                }
                return(streamDoc.GetModifiedDocument());
            }
        }
Пример #10
0
        /// <summary>
        /// Get image by r:id
        /// </summary>
        /// <param name="rid">Relationship ID.</param>
        /// <returns>Return System.Drawing.Image object if found, otherwise return null.</returns>
        public Image GetImageById(String rid)
        {
            OpenXmlPart part = this.doc.MainDocumentPart.GetPartById(rid);

            if (part != null)
            {
                ImagePart img = this.doc.MainDocumentPart.ImageParts.FirstOrDefault(c => c.Uri.Equals(part.Uri));
                if (img != null)
                {
                    return(Image.FromStream(img.GetStream(System.IO.FileMode.Open, System.IO.FileAccess.Read)));
                }
            }
            return(null);
        }
Пример #11
0
        /// <summary>
        /// Sets the document background image
        /// </summary>
        /// <param name="imagePath">Path of the background image</param>
        public void SetImage(string imagePath)
        {
            XDocument mainDocument = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart);

            // Adds the image to the package
            ImagePart imagePart   = parentDocument.Document.MainDocumentPart.AddImagePart(ImagePartType.Bmp);
            Stream    imageStream = new StreamReader(imagePath).BaseStream;

            byte[] imageBytes = new byte[imageStream.Length];
            imageStream.Read(imageBytes, 0, imageBytes.Length);
            imagePart.GetStream().Write(imageBytes, 0, imageBytes.Length);

            // Creates a "background" element relating the image and the document

            // If the background element already exists, deletes it
            XElement backgroundElement = BackgroundElement();

            if (backgroundElement != null)
            {
                backgroundElement.Remove();
            }

            // Background element construction
            mainDocument.Root.Add(
                new XElement(ns + "background",
                             new XAttribute(ns + "color", defaultBackgroundColor),
                             new XElement(vmlns + "background",
                                          new XAttribute(vmlns + "id", defaultVmlBackgroundImageId),
                                          new XAttribute(officens + "bwmode", defaultBWMode),
                                          new XAttribute(officens + "targetscreensize", defaultTargetScreenSize),
                                          new XElement(vmlns + "fill",
                                                       new XAttribute(relationshipsns + "id", parentDocument.Document.MainDocumentPart.GetIdOfPart(imagePart)),
                                                       new XAttribute("recolor", defaultImageRecolor),
                                                       new XAttribute("type", defaultImageType)
                                                       )
                                          )
                             )
                );


            // Enables background displaying by adding "displayBackgroundShape" tag
            if (parentDocument.Setting.DisplayBackgroundShapeElements() == null)
            {
                parentDocument.Setting.AddBackgroundShapeElement();
            }
        }
        public void replaceOriginalImage(string newImagePath, string imageID)
        {
            // go through the document and pull out the inline image elements
            IEnumerable <Drawing> imageElements = from run in m_mainDocPart.Document.Descendants <DocumentFormat.OpenXml.Wordprocessing.Run>()
                                                  where run.Descendants <Drawing>().First() != null
                                                  select run.Descendants <Drawing>().First();

            ImagePart imagePart = (ImagePart)m_mainDocPart.GetPartById(imageID);

            m_imageInBytes = File.ReadAllBytes(newImagePath);
            BinaryWriter writer = new BinaryWriter(imagePart.GetStream());

            writer.Write(m_imageInBytes);
            writer.Close();

            m_wordProcessingDocument.Close();
        }
Пример #13
0
        private List <OpenXmlImportImages> GetOpenXmlImportImages(SheetEx sheet, WorkbookPart workbookPart)
        {
            WorksheetPart wsPart                = (WorksheetPart)workbookPart.GetPartById(sheet.SheetId);
            DrawingsPart  drawingPart           = wsPart.GetPartsOfType <DrawingsPart>().ToList().FirstOrDefault();
            List <OpenXmlImportImages> pictures = new List <OpenXmlImportImages>();

            if (drawingPart != null)
            {
                foreach (var part in drawingPart.Parts)
                {
                    OpenXmlImportImages pic     = new OpenXmlImportImages();
                    ImagePart           imgPart = (ImagePart)part.OpenXmlPart;
                    pic.Image = StreamToBytes(imgPart.GetStream());
                    pic.RefId = part.RelationshipId;
                    pictures.Add(pic);
                }

                var worksheetDrawings = drawingPart.WorksheetDrawing.Where(c => c.ChildElements.Any
                                                                               (a => a.GetType().FullName == "DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture")).ToList();
                foreach (var worksheetDrawing in worksheetDrawings)
                {
                    if (worksheetDrawing.GetType().FullName ==
                        "DocumentFormat.OpenXml.Drawing.Spreadsheet.TwoCellAnchor")
                    {
                        TwoCellAnchor anchor = (TwoCellAnchor)worksheetDrawing;
                        DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picDef =
                            (DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture)
                            anchor.ChildElements.FirstOrDefault(c => c.GetType().FullName ==
                                                                "DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture");
                        if (picDef != null)
                        {
                            var embed = picDef.BlipFill.Blip.Embed;
                            if (embed != null)
                            {
                                var picMapping = pictures.FirstOrDefault(c => c.RefId == embed.InnerText);
                                picMapping.FromCol = int.Parse(anchor.FromMarker.ColumnId.InnerText);
                                picMapping.FromRow = int.Parse(anchor.FromMarker.RowId.InnerText);
                            }
                        }
                    }
                }
            }
            return(pictures);
        }
Пример #14
0
        public string GetImageInHtmlBase64Format(WordprocessingDocument wordprocessingDocument, Paragraph paragraph, ImagePart image)
        {
            if (image == null)
            {
                return(null);
            }

            var  stream = image.GetStream();
            long length = stream.Length;

            byte[] byteStream = new byte[length];
            stream.Read(byteStream, 0, (int)length);

            string base64     = System.Convert.ToBase64String(byteStream);
            string dataString = "<img src=data:" + image.ContentType.ToString() + ";" + "base64," + base64 + ">";


            return(dataString);
        }
        /// <summary>
        /// Updates the image in an image placeholder
        /// </summary>
        /// <param name="placeholderName">Image placeholder tag name</param>
        /// <param name="newImage">physical path to the new image file</param>
        public void UpdateImage(string placeholderName, string newImage)
        {
            // Get the id of the image placeholder
            string relId = GetImageRelID(placeholderName);

            // Get the Imagepart
            ImagePart imagePart = (ImagePart)mainDocPart.GetPartById(relId);

            // Read the new image file
            byte[] imageBytes = File.ReadAllBytes(newImage);

            // Create a writer to the imagepart
            BinaryWriter writer = new BinaryWriter(imagePart.GetStream());

            // Overwrite the current image in the docx file package
            writer.Write(imageBytes);

            // Close the imagepart
            writer.Close();
        }
Пример #16
0
        private List <string> ExtractImages(Body content, MainDocumentPart wDoc, string imageFolderPath)
        {
            List <string> imageList = new List <string>();

            foreach (DocumentFormat.OpenXml.Wordprocessing.Paragraph par in content.Descendants <DocumentFormat.OpenXml.Wordprocessing.Paragraph>())
            {
                ParagraphProperties paragraphProperties = par.ParagraphProperties;
                for (int i = 0; i < par.Descendants <Run>().Count(); i++)
                {
                    Run     run   = par.Descendants <Run>().ElementAt(i);
                    Drawing image =
                        run.Descendants <Drawing>().FirstOrDefault();
                    if (image != null)
                    {
                        var       imageFirst    = image.Inline.Graphic.GraphicData.Descendants <DocumentFormat.OpenXml.Drawing.Pictures.Picture>().FirstOrDefault();
                        var       blip          = imageFirst.BlipFill.Blip.Embed.Value;
                        ImagePart img           = (ImagePart)wDoc.Document.MainDocumentPart.GetPartById(blip);
                        string    imageFileName = string.Empty;
                        string    imageFilePath = string.Empty;
                        using (Image toSaveImage = Bitmap.FromStream(img.GetStream()))
                        {
                            imageFileName = "Img_" + imageCount;
                            imageFilePath = imageFolderPath + "\\" + imageFileName + ".png";
                            try
                            {
                                toSaveImage.Save(imageFilePath, ImageFormat.Png);
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                        imageList.Add(imageFilePath);
                        Run run2 = par.Descendants <Run>().ElementAt(i - 1);
                        run2.AppendChild(new Text(" Images/" + imageFileName + ".png"));
                        image.Remove();
                        imageCount++;
                    }
                }
            }
            return(imageList);
        }
Пример #17
0
        public void ReplaceImage(string destinationFile, string mapImageUrl, string imageId)
        {
            WordprocessingDocument m_wordProcessingDocument = WordprocessingDocument.Open(destinationFile, true);
            MainDocumentPart       m_mainDocPart            = m_wordProcessingDocument.MainDocumentPart;

            // go through the document and pull out the inline image elements
            IEnumerable <Drawing> imageElements = from run in m_mainDocPart.Document.Descendants <DocumentFormat.OpenXml.Wordprocessing.Run>()
                                                  where run.Descendants <Drawing>().First() != null
                                                  select run.Descendants <Drawing>().First();

            ImagePart imagePart = (ImagePart)m_mainDocPart.GetPartById(imageId);

            var webClient = new WebClient();

            byte[]       m_imageInBytes = webClient.DownloadData(mapImageUrl);
            BinaryWriter writer         = new BinaryWriter(imagePart.GetStream());

            writer.Write(m_imageInBytes);
            writer.Close();

            m_wordProcessingDocument.Close();
        }
Пример #18
0
        public void FillContent(XElement contentControl, IContentItem item)
        {
            if (!(item is ImageContent))
            {
                _processResult = ProcessResult.NotHandledResult;
                return;
            }

            var field = item as ImageContent;

            // If there isn't a field with that name, add an error to the error string,
            // and continue with next field.
            if (contentControl == null)
            {
                _processResult.Errors.Add(String.Format("Field Content Control '{0}' not found.",
                                                        field.Name));
                return;
            }


            var blip = contentControl.DescendantsAndSelf(A.blip).First();

            if (blip == null)
            {
                _processResult.Errors.Add(String.Format("Image to replace for '{0}' not found.",
                                                        field.Name));
                return;
            }

            var imageId = blip.Attribute(R.embed).Value;

            ImagePart imagePart = (ImagePart)_context.WordDocument.MainDocumentPart.GetPartById(imageId);

            using (BinaryWriter writer = new BinaryWriter(imagePart.GetStream()))
            {
                writer.Write(field.Binary);
            }
        }
Пример #19
0
        private static (long width, long height) CalcuateImageSizeInEmus(ImagePart imagePart, SectionProperties sectionProperties)
        {
            // Get a BitmapImage from the image part.
            var bitmapImage = new BitmapImage();

            using (var stream = imagePart.GetStream(FileMode.Open, FileAccess.Read))
            {
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = stream;
                bitmapImage.EndInit();
            }

            // Calculate width and height in EMUs.
            // https://stackoverflow.com/questions/8082980/inserting-image-into-docx-using-openxml-and-setting-the-size
            // https://startbigthinksmall.wordpress.com/2010/01/04/points-inches-and-emus-measuring-units-in-office-open-xml/
            const int EMUsPerInch  = 914400;
            var       widthInEmus  = (long)(bitmapImage.PixelWidth / bitmapImage.DpiX * EMUsPerInch);
            var       heightInEmus = (long)(bitmapImage.PixelHeight / bitmapImage.DpiY * EMUsPerInch);

            // Calculate content area width in EMUs.
            var pageSize   = sectionProperties.GetFirstChild <PageSize>();
            var pageMargin = sectionProperties.GetFirstChild <PageMargin>();

            const double DXAsPerInch = 1440;  // 1 inch = 72 points = 72 x 20 DXAs
            var          maxContentAreaWidthInDxa  = pageSize.Width - pageMargin.Left - pageMargin.Right;
            var          maxContentAreaWidthInEmus = (long)(maxContentAreaWidthInDxa / DXAsPerInch * EMUsPerInch);

            // Adjust the image size to content area width.
            if (widthInEmus > maxContentAreaWidthInEmus)
            {
                var ratio = (double)heightInEmus / widthInEmus;
                widthInEmus  = maxContentAreaWidthInEmus;
                heightInEmus = (long)(widthInEmus * ratio);
            }

            return(width : widthInEmus, height : heightInEmus);
        }
Пример #20
0
        protected Drawing AddImagePart(Uri imageUrl, string imageSource, string alt, Size preferredSize)
        {
            if (imageObjId == UInt32.MinValue)
            {
                // In order to add images in the document, we need to asisgn an unique id
                // to each Drawing object. So we'll loop through all of the existing <wp:docPr> elements
                // to find the largest Id, then increment it for each new image.

                drawingObjId = 1;                 // 1 is the minimum ID set by MS Office.
                imageObjId   = 1;
                foreach (var d in mainPart.Document.Body.Descendants <Drawing>())
                {
                    if (d.Inline == null)
                    {
                        continue;                                       // fix some rare issue where Inline is null (reported by scwebgroup)
                    }
                    if (d.Inline.DocProperties.Id > drawingObjId)
                    {
                        drawingObjId = d.Inline.DocProperties.Id;
                    }

                    var nvPr = d.Inline.Graphic.GraphicData.GetFirstChild <pic.NonVisualPictureProperties>();
                    if (nvPr != null && nvPr.NonVisualDrawingProperties.Id > imageObjId)
                    {
                        imageObjId = nvPr.NonVisualDrawingProperties.Id;
                    }
                }
                if (drawingObjId > 1)
                {
                    drawingObjId++;
                }
                if (imageObjId > 1)
                {
                    imageObjId++;
                }
            }

            // Cache all the ImagePart processed to avoid downloading the same image.
            CachedImagePart imagePart = null;

            // if imageUrl is null, we may consider imageSource is a DataUri.
            // thus, no need to download and cache anything
            if (imageUrl == null || !knownImageParts.TryGetValue(imageUrl, out imagePart))
            {
                HtmlImageInfo iinfo = new HtmlImageInfo()
                {
                    Size = preferredSize
                };
                ImageProvisioningProvider provider = new ImageProvisioningProvider(this.WebProxy, iinfo);

                if (imageUrl == null)
                {
                    provider.DownloadData(DataUri.Parse(imageSource));
                }
                else if (this.ImageProcessing == ImageProcessing.ManualProvisioning)
                {
                    // as HtmlImageInfo is a class, the EventArgs will act as a proxy
                    ProvisionImageEventArgs args = new ProvisionImageEventArgs(imageUrl, iinfo);
                    OnProvisionImage(args);

                    // did the user want to ignore this image?
                    if (args.Cancel)
                    {
                        return(null);
                    }
                }

                // Automatic Processing or the user did not supply himself the image and did not cancel the provisioning.
                // We download ourself the image.
                if (iinfo.RawData == null && imageUrl.IsAbsoluteUri)
                {
                    provider.DownloadData(imageUrl);
                }

                if (iinfo.RawData == null || !provider.Provision(imageUrl))
                {
                    return(null);
                }

                ImagePart ipart = mainPart.AddImagePart(iinfo.Type.Value);
                imagePart = new CachedImagePart()
                {
                    Part = ipart
                };
                imagePart.Width  = iinfo.Size.Width;
                imagePart.Height = iinfo.Size.Height;

                using (Stream outputStream = ipart.GetStream(FileMode.Create))
                {
                    outputStream.Write(iinfo.RawData, 0, iinfo.RawData.Length);
                    outputStream.Seek(0L, SeekOrigin.Begin);
                }

                if (imageUrl != null)                 // don't need to cache inlined-image
                {
                    knownImageParts.Add(imageUrl, imagePart);
                }
            }

            if (preferredSize.IsEmpty)
            {
                preferredSize.Width  = imagePart.Width;
                preferredSize.Height = imagePart.Height;
            }
            else if (preferredSize.Width <= 0 || preferredSize.Height <= 0)
            {
                Size actualSize = new Size(imagePart.Width, imagePart.Height);
                preferredSize = ImageHeader.KeepAspectRatio(actualSize, preferredSize);
            }

            string imagePartId  = mainPart.GetIdOfPart(imagePart.Part);
            long   widthInEmus  = new Unit(UnitMetric.Pixel, preferredSize.Width).ValueInEmus;
            long   heightInEmus = new Unit(UnitMetric.Pixel, preferredSize.Height).ValueInEmus;

            ++drawingObjId;
            ++imageObjId;

            var img = new Drawing(
                new wp.Inline(
                    new wp.Extent()
            {
                Cx = widthInEmus, Cy = heightInEmus
            },
                    new wp.EffectExtent()
            {
                LeftEdge = 19050L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L
            },
                    new wp.DocProperties()
            {
                Id = drawingObjId, Name = imageSource, Description = string.Empty
            },
                    new wp.NonVisualGraphicFrameDrawingProperties {
                GraphicFrameLocks = new a.GraphicFrameLocks()
                {
                    NoChangeAspect = true
                }
            },
                    new a.Graphic(
                        new a.GraphicData(
                            new pic.Picture(
                                new pic.NonVisualPictureProperties {
                NonVisualDrawingProperties = new pic.NonVisualDrawingProperties()
                {
                    Id = imageObjId, Name = imageSource, Description = alt
                },
                NonVisualPictureDrawingProperties = new pic.NonVisualPictureDrawingProperties(
                    new a.PictureLocks()
                {
                    NoChangeAspect = true, NoChangeArrowheads = true
                })
            },
                                new pic.BlipFill(
                                    new a.Blip()
            {
                Embed = imagePartId
            },
                                    new a.SourceRectangle(),
                                    new a.Stretch(
                                        new a.FillRectangle())),
                                new pic.ShapeProperties(
                                    new a.Transform2D(
                                        new a.Offset()
            {
                X = 0L, Y = 0L
            },
                                        new a.Extents()
            {
                Cx = widthInEmus, Cy = heightInEmus
            }),
                                    new a.PresetGeometry(
                                        new a.AdjustValueList()
                                        )
            {
                Preset = a.ShapeTypeValues.Rectangle
            }
                                    )
            {
                BlackWhiteMode = a.BlackWhiteModeValues.Auto
            })
                            )
            {
                Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
            })
                    )
            {
                DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U
            }
                );

            return(img);
        }
Пример #21
0
        private IRun CreateImage(ImagePart imagePart, PictureModel model)
        {
            string relationshipId = GetIdOfPart(imagePart);

            long imageWidth  = 990000L;
            long imageHeight = 792000L;

#if __WPF__ || __IOS__
            using (var bm = new System.Drawing.Bitmap(imagePart.GetStream()))
#endif
#if __ANDROID__
            using (var bm = Android.Graphics.BitmapFactory.DecodeStream(imagePart.GetStream()))
#endif
            {
                long bmWidth  = (long)bm.Width;
                long bmHeight = (long)bm.Height;

                // Redimensionnement de l'image car trop grande en largeur:
                if (model.MaxWidth.HasValue && model.MaxWidth.Value < bmWidth)
                {
                    long ratio = model.MaxWidth.Value * 100L / bmWidth;

                    bmWidth  = (long)((double)bmWidth * ((double)ratio / 100D));
                    bmHeight = (long)((double)bmHeight * ((double)ratio / 100D));
                }

                // Redimensionnement de l'image car trop grande en hauteur:
                if (model.MaxHeight.HasValue && model.MaxHeight.Value < bmHeight)
                {
                    long ratio = model.MaxHeight.Value * 100L / bmHeight;

                    bmWidth  = (long)((double)bmWidth * ((double)ratio / 100D));
                    bmHeight = (long)((double)bmHeight * ((double)ratio / 100D));
                }

#if __WPF__ || __IOS__
                imageWidth  = bmWidth * (long)((float)914400 / bm.HorizontalResolution);
                imageHeight = bmHeight * (long)((float)914400 / bm.VerticalResolution);
#endif
#if __ANDROID__
                // TODO : Check this method
                imageWidth  = bmWidth * (long)((float)914400 / (long)bm.Density);
                imageHeight = bmHeight * (long)((float)914400 / (long)bm.Density);
#endif
            }

            var result = new Run();

            var runProperties = new RunProperties();
            runProperties.Append(new NoProof());
            result.Append(runProperties);

            var graphicFrameLocks = new A.GraphicFrameLocks()
            {
                NoChangeAspect = true
            };
            graphicFrameLocks.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");

            var picture = new PIC.Picture(
                new PIC.NonVisualPictureProperties(
                    new PIC.NonVisualDrawingProperties()
            {
                Id   = (UInt32Value)0U,
                Name = "New Bitmap Image.jpg"
            },
                    new PIC.NonVisualPictureDrawingProperties()),
                new PIC.BlipFill(
                    new A.Blip()
            {
                Embed            = relationshipId,
                CompressionState =
                    A.BlipCompressionValues.Print
            },
                    new A.Stretch(
                        new A.FillRectangle())),
                new PIC.ShapeProperties(
                    new A.Transform2D(
                        new A.Offset()
            {
                X = 0L, Y = 0L
            },
                        new A.Extents()
            {
                Cx = imageWidth, Cy = imageHeight
            }),
                    new A.PresetGeometry(
                        new A.AdjustValueList()
                        )
            {
                Preset = A.ShapeTypeValues.Rectangle
            }));
            picture.AddNamespaceDeclaration("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");

            var graphic = new A.Graphic(
                new A.GraphicData(
                    picture
                    )
            {
                Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
            });
            graphic.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");

            result.Append(new DocumentFormat.OpenXml.Wordprocessing.Drawing(
                              new DW.Inline(
                                  new DW.Extent()
            {
                Cx = imageWidth, Cy = imageHeight
            },
                                  new DW.EffectExtent()
            {
                LeftEdge   = 0L,
                TopEdge    = 0L,
                RightEdge  = 0L,
                BottomEdge = 0L
            },
                                  new DW.DocProperties()
            {
                Id   = (UInt32Value)1U,
                Name = "Picture 1"
            },
                                  new DW.NonVisualGraphicFrameDrawingProperties(graphicFrameLocks),
                                  graphic
                                  )
            {
                DistanceFromTop    = (UInt32Value)0U,
                DistanceFromBottom = (UInt32Value)0U,
                DistanceFromLeft   = (UInt32Value)0U,
                DistanceFromRight  = (UInt32Value)0U,
                EditId             = "50D07946"
            }));
            return(new PlatformRun(result));
        }
Пример #22
0
        /// <summary>
        /// Lấy màu Image Slide
        /// </summary>
        /// <param name="slide"></param>
        /// <param name="openXmlPart"></param>
        /// <param name="blipFill"></param>
        /// <returns></returns>
        private ImageColor GetImageColor(pp.FillFormat fill, OpenXmlPart openXmlPart, BlipFill blipFill)
        {
            ImagePart part = null;
            IEnumerable <DocumentFormat.OpenXml.Presentation.Picture> lstPic = null;

            if (openXmlPart is SlidePart slidePart)
            {
                lstPic = slidePart.Slide.Descendants <DocumentFormat.OpenXml.Presentation.Picture>().Select(p => p);
                if (lstPic != null)
                {
                    string rID = blipFill.Blip.Embed.Value;
                    part = (ImagePart)slidePart.GetPartById(rID);
                }
            }
            else if (openXmlPart is SlideMasterPart slideMasterPart)
            {
                lstPic = slideMasterPart.SlideMaster.Descendants <DocumentFormat.OpenXml.Presentation.Picture>().Select(p => p);
                if (lstPic != null)
                {
                    string rID = blipFill.Blip.Embed.Value;
                    part = (ImagePart)slideMasterPart.GetPartById(rID);
                }
            }
            else if (openXmlPart is SlideLayoutPart slideLayoutPart)
            {
                lstPic = slideLayoutPart.SlideLayout.Descendants <DocumentFormat.OpenXml.Presentation.Picture>().Select(p => p);
                if (lstPic != null)
                {
                    string rID = blipFill.Blip.Embed.Value;
                    part = (ImagePart)slideLayoutPart.GetPartById(rID);
                }
            }
            if (lstPic != null && part != null)
            {
                string pathImage = System.IO.Path.Combine((System.Windows.Application.Current as IAppGlobal).DocumentTempFolder, ObjectElementsHelper.RandomString(13) + System.IO.Path.GetExtension(part.Uri.ToString()));
                Utils.CopyStream(part.GetStream(), pathImage);
                ImageColor imageColor = new ImageColor();
                imageColor.Source           = new Core.Model.Image(pathImage);
                imageColor.Opacity          = 1 - fill.Transparency;
                imageColor.OffsetX          = fill.TextureOffsetX;
                imageColor.OffsetY          = fill.TextureOffsetY;
                imageColor.IsTiled          = fill.TextureTile == MsoTriState.msoTrue;
                imageColor.Alignment        = ConvertImageAligment(fill.TextureAlignment);
                imageColor.ScaleX           = fill.TextureHorizontalScale;
                imageColor.ScaleY           = fill.TextureVerticalScale;
                imageColor.RotateWidthShape = fill.RotateWithObject == MsoTriState.msoTrue;
                foreach (var item in blipFill)
                {
                    if (item is Stretch stretch)
                    {
                        if (stretch.FillRectangle.Top != null)
                        {
                            imageColor.OffsetTop = stretch.FillRectangle.Top / 100000;
                        }
                        if (stretch.FillRectangle.Left != null)
                        {
                            imageColor.OffsetLeft = stretch.FillRectangle.Left / 100000;
                        }
                        if (stretch.FillRectangle.Right != null)
                        {
                            imageColor.OffsetRight = stretch.FillRectangle.Right / 100000;
                        }
                        if (stretch.FillRectangle.Bottom != null)
                        {
                            imageColor.OffsetBottom = stretch.FillRectangle.Bottom / 100000;
                        }
                    }
                }
                return(imageColor);
            }
            return(null);
        }
Пример #23
0
    public static ExcelEntity ReadExcelDetail(SpreadsheetDocument excel, List <string> sheetName, string file)
    {
        ExcelEntity ee = new ExcelEntity();

        #region SheetStyle公用样式表
        #region 主题色
        ThemePart themPart  = excel.WorkbookPart.ThemePart;
        var       themColor = ThemeColor.GetThemeColorList(themPart);
        #endregion

        //获取样式设置
        Stylesheet styleSheet = excel.WorkbookPart.WorkbookStylesPart.Stylesheet;
        #region 样式列表
        CellFormats            cellFormats     = styleSheet.CellFormats;
        List <CellFormatsList> cellFormatsList = new List <CellFormatsList>();
        int index = 0;
        foreach (CellFormat cell in cellFormats.ChildElements)
        {
            if (cell != null)
            {
                CellFormatsList cfl = new CellFormatsList();
                cfl.styleIndex = index;
                if (cell.NumberFormatId != null)
                {
                    cfl.numFmtId = int.Parse(cell.NumberFormatId);
                }
                if (cell.FontId != null)
                {
                    cfl.fontId = int.Parse(cell.FontId);
                }
                if (cell.FillId != null)
                {
                    cfl.fillId = int.Parse(cell.FillId);
                }
                if (cell.BorderId != null)
                {
                    cfl.borderId = int.Parse(cell.BorderId);
                }
                if (cell.ApplyAlignment != null)
                {
                    cfl.applyAlignment = int.Parse(cell.ApplyAlignment);
                }
                if (cell.ApplyBorder != null)
                {
                    cfl.applyBorder = int.Parse(cell.ApplyBorder);
                }
                if (cell.ApplyFont != null)
                {
                    cfl.applyFont = int.Parse(cell.ApplyFont);
                }
                if (cell.ApplyNumberFormat != null)
                {
                    cfl.applyNumberFormat = int.Parse(cell.ApplyNumberFormat);
                }
                if (cell.Alignment != null)
                {
                    string ver = cell.Alignment.Vertical;
                    string hor = cell.Alignment.Horizontal;
                    if (!string.IsNullOrEmpty(ver))
                    {
                        if (ver == "center")
                        {
                            cfl.vertical = "htMiddle";
                        }
                        else
                        {
                            cfl.vertical = "ht" + ver.Substring(0, 1).ToUpper() + ver.Substring(1, ver.Length - 1);
                        }
                    }
                    else
                    {
                        cfl.vertical = "htBottom";
                    }
                    if (!string.IsNullOrEmpty(hor))
                    {
                        cfl.horizontal = "ht" + hor.Substring(0, 1).ToUpper() + hor.Substring(1, hor.Length - 1);
                    }
                    else
                    {
                        cfl.horizontal = "htLeft";
                    }
                }
                cellFormatsList.Add(cfl);
                index++;
            }
        }
        ee.CellFormatsList = cellFormatsList;
        #endregion

        #region 数据类型列表
        NumberingFormats   numberFormats = styleSheet.NumberingFormats;
        List <NumFmtsList> numFmtList    = new List <NumFmtsList>();
        if (numberFormats != null)
        {
            foreach (NumberingFormat cell in numberFormats.ChildElements)
            {
                NumFmtsList nfl = new NumFmtsList();
                if (cell.NumberFormatId != null)
                {
                    nfl.numFmtId = (int)cell.NumberFormatId.Value;
                }
                if (cell.FormatCode != null)
                {
                    nfl.formatCode = cell.FormatCode.Value;
                }
                numFmtList.Add(nfl);
            }
        }
        ee.NumFmtsList = numFmtList;
        #endregion

        #region 字体样式
        Fonts            fonts     = styleSheet.Fonts;
        List <FontsList> fontsList = new List <FontsList>();
        foreach (Font cell in fonts.ChildElements)
        {
            FontsList fl = new FontsList();
            if (cell.FontSize != null)
            {
                fl.fontsize = cell.FontSize.Val + "px";
            }
            if (cell.FontName != null)
            {
                fl.fontname = cell.FontName.Val;
            }
            if (cell.Color != null)
            {
                if (cell.Color.Rgb != null && !string.IsNullOrEmpty(cell.Color.Rgb.ToString()))
                {
                    fl.color = "#" + cell.Color.Rgb.ToString().Substring(2, 6);
                }
            }
            if (cell.Italic != null)
            {
                fl.italic = "italic";
            }
            if (cell.Bold != null)
            {
                fl.bold = "bold";
            }
            if (cell.Underline != null)
            {
                fl.underline = "underline";
            }
            fontsList.Add(fl);
        }
        ee.FontsList = fontsList;
        #endregion

        #region 填充色样式
        Fills            fills     = styleSheet.Fills;
        List <FillsList> fillsList = new List <FillsList>();
        foreach (Fill cell in fills.ChildElements)
        {
            FillsList fl = new FillsList();
            if (cell.PatternFill != null)
            {
                fl.patternType = cell.PatternFill.PatternType;
                if (cell.PatternFill.ForegroundColor != null)
                {
                    if (cell.PatternFill.ForegroundColor.Rgb != null)
                    {
                        fl.fgColor = "#" + cell.PatternFill.ForegroundColor.Rgb.ToString().Substring(2, 6);
                    }
                    if (cell.PatternFill.ForegroundColor.Theme != null)
                    {
                        UInt32Value themeIndex = cell.PatternFill.ForegroundColor.Theme;
                        DoubleValue tint       = cell.PatternFill.ForegroundColor.Tint;
                        if (tint != null)
                        {
                            var newColor = ThemeColor.ThemColorDeal(themeIndex, tint, themColor[themeIndex]);
                            fl.fgColor = "#" + newColor.Name.Substring(2, 6);
                            fl.fgColor = "#" + newColor.Name.Substring(2, 6);
                        }
                        else
                        {
                            fl.fgColor = "#" + themColor[themeIndex];
                            fl.fgColor = "#" + themColor[themeIndex];
                        }
                    }
                }
            }
            fillsList.Add(fl);
        }
        ee.FillsList = fillsList;
        #endregion

        #region 边框样式
        Borders            borders     = styleSheet.Borders;
        List <BordersList> bordersList = new List <BordersList>();
        var defaultBorderStyle         = "1px solid #000";
        foreach (Border cell in borders.ChildElements)
        {
            BordersList bl = new BordersList();
            if (cell.LeftBorder != null)
            {
                if (cell.LeftBorder.Style != null)
                {
                    bl.left = defaultBorderStyle;
                }
            }
            if (cell.RightBorder != null)
            {
                if (cell.RightBorder.Style != null)
                {
                    bl.right = defaultBorderStyle;
                }
            }
            if (cell.TopBorder != null)
            {
                if (cell.TopBorder.Style != null)
                {
                    bl.top = defaultBorderStyle;
                }
            }
            if (cell.BottomBorder != null)
            {
                if (cell.BottomBorder.Style != null)
                {
                    bl.bottom = defaultBorderStyle;
                }
            }
            if (cell.DiagonalBorder != null)
            {
                if (cell.DiagonalBorder.Style != null)
                {
                    bl.diagonal = cell.DiagonalBorder.Style;
                }
            }
            bordersList.Add(bl);
        }
        ee.BordersList = bordersList;
        #endregion
        #endregion

        List <SheetDataList> sheetDataList = new List <SheetDataList>();
        List <PictureInfo>   pictures      = null;
        for (int i = 0; i < sheetName.Count; i++)
        {
            SheetDataList sdl         = new SheetDataList();
            int           RowCount    = 0;
            int           ColumnCount = 0;
            //得到工作表dimension
            WorksheetPart worksheet = ExcelHelper.GetWorksheetPartByName(excel, sheetName[i]);

            #region 获取单个Sheet表的数据

            #region //批注
            WorksheetCommentsPart   comments     = worksheet.WorksheetCommentsPart;
            List <CommentCellsList> commentLists = new List <CommentCellsList>();
            if (comments != null)
            {
                CommentList commentList = (CommentList)comments.Comments.ChildElements[1];
                //批注列表
                foreach (Comment comment in commentList.ChildElements)
                {
                    CommentCellsList ccl = new CommentCellsList();
                    //坐标
                    var cell      = GetCellXY(comment.Reference).Split('_');
                    var columnRow = int.Parse(cell[0].ToString()) - 1;
                    var columnCol = GetColumnIndex(cell[1]);
                    //批注内容
                    var commentVal = comment.InnerText;
                    ccl.row     = columnRow;
                    ccl.col     = columnCol;
                    ccl.comment = comment.InnerText;
                    //var commentCell = "{\"Row\":\""+ columnRow + "\",\"Col\":\"" + columnCol + ",\"Comment\":\"" + commentVal + "\"}";
                    commentLists.Add(ccl);
                }
            }
            sdl.Comments = commentLists;
            #endregion

            #region //获取合并单元格
            IEnumerable <MergeCells> mergeCells    = worksheet.Worksheet.Elements <MergeCells>();
            List <MergeCellsList>    mergeCellList = new List <MergeCellsList>();
            if (mergeCells.Count() > 0)
            {
                for (int k = 0; k < mergeCells.First().ChildElements.Count; k++)
                {
                    MergeCell      mergeCell = (MergeCell)mergeCells.First().ChildElements[k];
                    var            reference = mergeCell.Reference.ToString().Split(':');
                    var            startCell = GetCellXY(reference[0]).Split('_');
                    var            endCell   = GetCellXY(reference[1]).Split('_');
                    MergeCellsList mcl       = new MergeCellsList();
                    mcl.row     = int.Parse(startCell[0]) - 1;
                    mcl.rowspan = int.Parse(endCell[0]) - int.Parse(startCell[0]) + 1;
                    mcl.col     = GetColumnIndex(startCell[1]);
                    mcl.colspan = GetColumnIndex(endCell[1]) - mcl.col + 1;
                    //mcl.reference = mergeCell.Reference.ToString();
                    mergeCellList.Add(mcl);
                }
            }
            sdl.MergeCells = mergeCellList;
            #endregion

            //获取超链接列表
            //var hyperlinks = worksheet.RootElement.Descendants<Hyperlinks>().First().Cast<Hyperlink>();

            #region //读取图片
            DrawingsPart drawingPart = worksheet.GetPartsOfType <DrawingsPart>().ToList().FirstOrDefault();
            pictures = new List <PictureInfo>();
            if (drawingPart != null)
            {
                int tempIndex = 1;
                foreach (var part in drawingPart.Parts)
                {
                    PictureInfo          pic     = new PictureInfo();
                    ImagePart            imgPart = (ImagePart)part.OpenXmlPart;
                    System.Drawing.Image img1    = System.Drawing.Image.FromStream(imgPart.GetStream());

                    var      newFilename = Guid.NewGuid().ToString("N") + ".png";
                    string[] sArray      = Regex.Split(file, "UserFile", RegexOptions.IgnoreCase);
                    string   newFilePath = sArray[0] + "_Temp\\" + newFilename;
                    img1.Save(newFilePath);
                    //pic.Image = img1;
                    pic.RefId     = part.RelationshipId;//"rId" + imgPart.Uri.ToString().Split('/')[3].Split('.')[0].Substring(5);
                    pic.ImageUrl  = newFilePath;
                    pic.ImageName = newFilename;
                    pic.ImgHeight = img1.Height;
                    pic.ImgWidth  = img1.Width;
                    pictures.Add(pic);
                    tempIndex++;
                }
                //获取图片定位
                var worksheetDrawings = drawingPart.WorksheetDrawing.Where(c => c.ChildElements.Any
                                                                               (a => a.GetType().FullName == "DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture")).ToList();
                foreach (var worksheetDrawing in worksheetDrawings)
                {
                    if (worksheetDrawing.GetType().FullName ==
                        "DocumentFormat.OpenXml.Drawing.Spreadsheet.TwoCellAnchor")
                    {
                        TwoCellAnchor anchor = (TwoCellAnchor)worksheetDrawing;
                        DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picDef =
                            (DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture)
                            anchor.ChildElements.FirstOrDefault(c => c.GetType().FullName ==
                                                                "DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture");
                        if (picDef != null)
                        {
                            var embed = picDef.BlipFill.Blip.Embed;
                            if (embed != null)
                            {
                                var picMapping = pictures.FirstOrDefault(c => c.RefId == embed.InnerText);
                                picMapping.FromCol = int.Parse(anchor.FromMarker.ColumnId.InnerText);
                                picMapping.FromRow = int.Parse(anchor.FromMarker.RowId.InnerText);
                            }
                        }
                        // anchor.FromMarker.RowId + anchor.FromMarker.ColumnId
                    }
                }
            }
            sdl.PictureList = pictures;
            #endregion

            #region 读取表格数据
            List <SheetDatas> sheetDatas = new List <SheetDatas>();
            if (worksheet.Rows().Count() > 0)
            {
                RowCount = int.Parse((worksheet.Rows().Last()).RowId);
            }
            int TempColumn = 0;
            foreach (OpenXmlPowerTools.Row row in worksheet.Rows())
            {
                foreach (OpenXmlPowerTools.Cell cell in row.Cells())
                {
                    #region 读取超链接
                    //var hyperlink = hyperlinks.SingleOrDefault(c => c.Reference.Value == cell.Column);

                    //if (hyperlink != null)
                    //{
                    //    var hyperlinksRelation = worksheet.HyperlinkRelationships.SingleOrDefault(c => c.Id == hyperlink.Id);
                    //    if (hyperlinksRelation != null)
                    //    {
                    //        //这是最终我们需要的超链接
                    //        var url = hyperlinksRelation.Uri.ToString();
                    //    }
                    //}
                    #endregion

                    TempColumn = (row.Cells().Last()).ColumnIndex;
                    if (ColumnCount < TempColumn)
                    {
                        ColumnCount = TempColumn + 1;
                    }

                    SheetDatas sheetData = new SheetDatas();
                    sheetData.RowId        = int.Parse(row.RowId);
                    sheetData.ColumnId     = cell.ColumnIndex;
                    sheetData.Column       = cell.Column;
                    sheetData.Type         = cell.Type;
                    sheetData.Value        = cell.Value;
                    sheetData.SharedString = cell.SharedString;
                    sheetData.Formula      = cell.Formula;
                    sheetData.StyleId      = cell.Style;

                    #region 样式赋值
                    if (sheetData.StyleId != null)
                    {
                        CellFormatsList cfl = cellFormatsList[(int)sheetData.StyleId];
                        sheetData.FontName           = fontsList[cfl.fontId].fontname;
                        sheetData.FontSize           = fontsList[cfl.fontId].fontsize;
                        sheetData.FontColor          = fontsList[cfl.fontId].color;
                        sheetData.FontBold           = fontsList[cfl.fontId].bold;
                        sheetData.Italic             = fontsList[cfl.fontId].italic;
                        sheetData.Underline          = fontsList[cfl.fontId].underline;
                        sheetData.AligmentVertical   = cfl.vertical;
                        sheetData.AligmentHorizontal = cfl.horizontal;

                        sheetData.FillType            = fillsList[cfl.fillId].patternType;
                        sheetData.FillForegroundColor = fillsList[cfl.fillId].fgColor;
                        sheetData.FillBackgroundColor = fillsList[cfl.fillId].bgColor;

                        sheetData.LeftBorder     = bordersList[cfl.borderId].left;
                        sheetData.RightBorder    = bordersList[cfl.borderId].right;
                        sheetData.TopBorder      = bordersList[cfl.borderId].top;
                        sheetData.BottomBorder   = bordersList[cfl.borderId].bottom;
                        sheetData.DiagonalBorder = bordersList[cfl.borderId].diagonal;
                    }
                    #endregion

                    if (cell.Style != null)
                    {
                        var cellf = cellFormatsList[(int)cell.Style];
                        if (cellf.applyNumberFormat > 0 && cell.Type == null && cell.Value != null)
                        {
                            //for (int n = 0; n < numFmtList.Count; n++)
                            //{
                            //    if (numFmtList[n].numFmtId == cellf.numFmtId|| cellf.numFmtId == 14)
                            //    {
                            //        sheetData.Type = "s";
                            //        sheetData.SharedString = DateTime.FromOADate(double.Parse(cell.Value)).ToShortDateString();
                            //        break;
                            //    }
                            //}
                            if (cellf.numFmtId == 58)
                            {
                                sheetData.Type         = "s";
                                sheetData.SharedString = DateTime.FromOADate(double.Parse(cell.Value)).ToString("M月d日");
                            }
                            else if (cellf.numFmtId == 14)
                            {
                                sheetData.Type         = "s";
                                sheetData.SharedString = DateTime.FromOADate(double.Parse(cell.Value)).ToShortDateString();
                            }
                            else
                            {
                                for (int n = 0; n < numFmtList.Count; n++)
                                {
                                    if (numFmtList[n].numFmtId == cellf.numFmtId)
                                    {
                                        sheetData.Type         = "s";
                                        sheetData.SharedString = DateTime.FromOADate(double.Parse(cell.Value)).ToShortDateString();
                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            sheetData.Value = cell.Value;
                        }
                    }

                    sheetDatas.Add(sheetData);
                }
            }
            if (ColumnCount < 5)
            {
                ColumnCount = 5;
            }
            if (RowCount < 20)
            {
                RowCount = 20;
            }
            sdl.SheetData = sheetDatas;
            #endregion

            sdl.SheetName   = sheetName[i];
            sdl.SheetId     = "sheet" + (i + 1);
            sdl.TotalRow    = (RowCount + 1);
            sdl.TotalColumn = ColumnCount;
            sheetDataList.Add(sdl);
            //htmlStr = EMW.API.Serializer.ObjectToString(sheetDataList);//
            //htmlStr = "{\"SheetData\":" + htmlStr + ",\"Comments\":" + EMW.API.Serializer.ObjectToString(commentLists) + ",\"MergeCells\":" + EMW.API.Serializer.ObjectToString(mergeCellList) + ",\"TotalRow\":" + (RowCount + 1) + ",\"TotalColumn\":" + ColumnCount + ",\"SheetName\":\"" + sheetName[i] + "\"}";
            //htmlSheet.Add(htmlStr);
            #endregion
        }
        ee.SheetDataList = sheetDataList;
        return(ee);
    }
Пример #24
0
        private static XElement ProcessImage(WordprocessingDocument wordDoc,
                                             XElement element, Func <ImageInfo, XElement> imageHandler)
        {
            if (element.Name == W.drawing)
            {
                XElement containerElement = element.Elements()
                                            .Where(e => e.Name == WP.inline || e.Name == WP.anchor)
                                            .FirstOrDefault();
                if (containerElement != null)
                {
                    int?extentCx = (int?)containerElement.Elements(WP.extent)
                                   .Attributes(NoNamespace.cx).FirstOrDefault();
                    int?extentCy = (int?)containerElement.Elements(WP.extent)
                                   .Attributes(NoNamespace.cy).FirstOrDefault();
                    string altText = (string)containerElement.Elements(WP.docPr)
                                     .Attributes(NoNamespace.descr).FirstOrDefault();
                    if (altText == null)
                    {
                        altText = (string)containerElement.Elements(WP.docPr)
                                  .Attributes(NoNamespace.name).FirstOrDefault();
                    }
                    if (altText == null)
                    {
                        altText = "";
                    }

                    XElement blipFill = containerElement.Elements(A.graphic)
                                        .Elements(A.graphicData)
                                        .Elements(Pic._pic).Elements(Pic.blipFill).FirstOrDefault();
                    if (blipFill != null)
                    {
                        string imageRid = (string)blipFill.Elements(A.blip).Attributes(R.embed)
                                          .FirstOrDefault();
                        ImagePart imagePart = (ImagePart)wordDoc.MainDocumentPart
                                              .GetPartById(imageRid);
                        string contentType = imagePart.ContentType;
                        if (contentType == "image/png" ||
                            contentType == "image/gif" ||
                            contentType == "image/tiff" ||
                            contentType == "image/jpeg")
                        {
                            using (Stream partStream = imagePart.GetStream())
                                using (Bitmap bitmap = new Bitmap(partStream))
                                {
                                    if (extentCx != null && extentCy != null)
                                    {
                                        ImageInfo imageInfo = new ImageInfo()
                                        {
                                            Bitmap            = bitmap,
                                            ImgStyleAttribute = new XAttribute(HtmlNoNamespace.style,
                                                                               string.Format("width: {0}in; height: {1}in",
                                                                                             (float)extentCx / (float)ImageInfo.EmusPerInch,
                                                                                             (float)extentCy / (float)ImageInfo.EmusPerInch)),
                                            ContentType    = contentType,
                                            DrawingElement = element,
                                            AltText        = altText,
                                        };
                                        return(imageHandler(imageInfo));
                                    }
                                    ImageInfo imageInfo2 = new ImageInfo()
                                    {
                                        Bitmap         = bitmap,
                                        ContentType    = contentType,
                                        DrawingElement = element,
                                        AltText        = altText,
                                    };
                                    return(imageHandler(imageInfo2));
                                };
                        }
                    }
                }
            }
            if (element.Name == W.pict)
            {
                string imageRid = (string)element.Elements(VML.shape)
                                  .Elements(VML.imagedata).Attributes(R.id).FirstOrDefault();
                string style = (string)element.Elements(VML.shape)
                               .Attributes(HtmlNoNamespace.style).FirstOrDefault();
                if (imageRid != null)
                {
                    try
                    {
                        ImagePart imagePart = (ImagePart)wordDoc.MainDocumentPart
                                              .GetPartById(imageRid);
                        string contentType = imagePart.ContentType;
                        if (contentType == "image/png" ||
                            contentType == "image/gif" ||
                            contentType == "image/tiff" ||
                            contentType == "image/jpeg")
                        {
                            //string style = element.
                            using (Stream partStream = imagePart.GetStream())
                                using (Bitmap bitmap = new Bitmap(partStream))
                                {
                                    ImageInfo imageInfo = new ImageInfo()
                                    {
                                        Bitmap         = bitmap,
                                        ContentType    = contentType,
                                        DrawingElement = element,
                                    };
                                    if (style != null)
                                    {
                                        float?   widthInPoints  = null;
                                        float?   heightInPoints = null;
                                        string[] tokens         = style.Split(';');
                                        var      widthString    = tokens
                                                                  .Select(t => new
                                        {
                                            Name  = t.Split(':').First(),
                                            Value = t.Split(':').Skip(1)
                                                    .Take(1).FirstOrDefault(),
                                        })
                                                                  .Where(p => p.Name == "width")
                                                                  .Select(p => p.Value)
                                                                  .FirstOrDefault();
                                        if (widthString != null &&
                                            widthString.Substring(widthString.Length - 2) == "pt")
                                        {
                                            float w;
                                            if (float.TryParse(widthString.Substring(0,
                                                                                     widthString.Length - 2), out w))
                                            {
                                                widthInPoints = w;
                                            }
                                        }
                                        var heightString = tokens
                                                           .Select(t => new
                                        {
                                            Name  = t.Split(':').First(),
                                            Value = t.Split(':').Skip(1).Take(1).FirstOrDefault(),
                                        })
                                                           .Where(p => p.Name == "height")
                                                           .Select(p => p.Value)
                                                           .FirstOrDefault();
                                        if (heightString != null &&
                                            heightString.Substring(heightString.Length - 2) == "pt")
                                        {
                                            float h;
                                            if (float.TryParse(heightString.Substring(0,
                                                                                      heightString.Length - 2), out h))
                                            {
                                                heightInPoints = h;
                                            }
                                        }
                                        if (widthInPoints != null && heightInPoints != null)
                                        {
                                            imageInfo.ImgStyleAttribute = new XAttribute(
                                                HtmlNoNamespace.style, string.Format(
                                                    "width: {0}pt; height: {1}pt",
                                                    widthInPoints, heightInPoints));
                                        }
                                    }
                                    return(imageHandler(imageInfo));
                                };
                        }
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        return(null);
                    }
                }
            }
            return(null);
        }
        public void writepPr(CharacterRun cr, ParagraphRun pr, ParagraphRun9 pr9, int IndentLevel, bool isTitle, bool isDefault)
        {
            //TextMasterStyleAtom defaultStyle = _ctx.Ppt.DocumentRecord.FirstChildWithType<b2xtranslator.PptFileFormat.Environment>().FirstChildWithType<TextMasterStyleAtom>();

            this._writer.WriteStartElement("a", "lvl" + (IndentLevel + 1).ToString() + "pPr", OpenXmlNamespaces.DrawingML);

            //marL
            if (pr.LeftMarginPresent && !isDefault)
            {
                this._writer.WriteAttributeString("marL", Utils.MasterCoordToEMU((int)pr.LeftMargin).ToString());
            }
            //marR
            //lvl
            if (pr.IndentLevel > 0)
            {
                this._writer.WriteAttributeString("lvl", pr.IndentLevel.ToString());
            }
            //indent
            if (pr.IndentPresent && !isDefault)
            {
                this._writer.WriteAttributeString("indent", (-1 * (Utils.MasterCoordToEMU((int)(pr.LeftMargin - pr.Indent)))).ToString());
            }
            //algn
            if (pr.AlignmentPresent)
            {
                switch (pr.Alignment)
                {
                case 0x0000:     //Left
                    this._writer.WriteAttributeString("algn", "l");
                    break;

                case 0x0001:     //Center
                    this._writer.WriteAttributeString("algn", "ctr");
                    break;

                case 0x0002:     //Right
                    this._writer.WriteAttributeString("algn", "r");
                    break;

                case 0x0003:     //Justify
                    this._writer.WriteAttributeString("algn", "just");
                    break;

                case 0x0004:     //Distributed
                    this._writer.WriteAttributeString("algn", "dist");
                    break;

                case 0x0005:     //ThaiDistributed
                    this._writer.WriteAttributeString("algn", "thaiDist");
                    break;

                case 0x0006:     //JustifyLow
                    this._writer.WriteAttributeString("algn", "justLow");
                    break;
                }
            }
            //defTabSz
            if (pr.DefaultTabSizePresent)
            {
                this._writer.WriteAttributeString("defTabSz", Utils.MasterCoordToEMU((int)pr.DefaultTabSize).ToString());
            }
            //rtl
            if (pr.TextDirectionPresent)
            {
                switch (pr.TextDirection)
                {
                case 0x0000:
                    this._writer.WriteAttributeString("rtl", "0");
                    break;

                case 0x0001:
                    this._writer.WriteAttributeString("rtl", "1");
                    break;
                }
            }
            else
            {
                this._writer.WriteAttributeString("rtl", "0");
            }
            //eaLnkBrk
            //fontAlgn
            if (pr.FontAlignPresent)
            {
                switch (pr.FontAlign)
                {
                case 0x0000:     //Roman
                    this._writer.WriteAttributeString("fontAlgn", "base");
                    break;

                case 0x0001:     //Hanging
                    this._writer.WriteAttributeString("fontAlgn", "t");
                    break;

                case 0x0002:     //Center
                    this._writer.WriteAttributeString("fontAlgn", "ctr");
                    break;

                case 0x0003:     //UpholdFixed
                    this._writer.WriteAttributeString("fontAlgn", "b");
                    break;
                }
            }
            //latinLnBrk
            //hangingPunct


            //lnSpc
            //spcBef
            if (pr.SpaceBeforePresent)
            {
                this._writer.WriteStartElement("a", "spcBef", OpenXmlNamespaces.DrawingML);
                if (pr.SpaceBefore < 0)
                {
                    this._writer.WriteStartElement("a", "spcPts", OpenXmlNamespaces.DrawingML);
                    this._writer.WriteAttributeString("val", (-1 * 12 * pr.SpaceBefore).ToString()); //TODO: the 12 is wrong
                    this._writer.WriteEndElement();                                                  //spcPct
                }
                else
                {
                    this._writer.WriteStartElement("a", "spcPct", OpenXmlNamespaces.DrawingML);
                    this._writer.WriteAttributeString("val", (1000 * pr.SpaceBefore).ToString());
                    this._writer.WriteEndElement(); //spcPct
                }
                this._writer.WriteEndElement();     //spcBef
                this.lastSpaceBefore = (int)pr.SpaceBefore;
            }
            else
            {
                if (this.lastSpaceBefore != 0)
                {
                    this._writer.WriteStartElement("a", "spcBef", OpenXmlNamespaces.DrawingML);
                    if (this.lastSpaceBefore < 0)
                    {
                        this._writer.WriteStartElement("a", "spcPts", OpenXmlNamespaces.DrawingML);
                        this._writer.WriteAttributeString("val", (-1 * 12 * this.lastSpaceBefore).ToString()); //TODO: the 12 is wrong
                        this._writer.WriteEndElement();                                                        //spcPct
                    }
                    else
                    {
                        this._writer.WriteStartElement("a", "spcPct", OpenXmlNamespaces.DrawingML);
                        this._writer.WriteAttributeString("val", (1000 * this.lastSpaceBefore).ToString());
                        this._writer.WriteEndElement(); //spcPct
                    }
                    this._writer.WriteEndElement();     //spcBef
                }
            }
            //spcAft
            if (pr.SpaceAfterPresent)
            {
                this._writer.WriteStartElement("a", "spcAft", OpenXmlNamespaces.DrawingML);
                if (pr.SpaceAfter < 0)
                {
                    this._writer.WriteStartElement("a", "spcPts", OpenXmlNamespaces.DrawingML);
                    this._writer.WriteAttributeString("val", (-1 * pr.SpaceAfter).ToString()); //TODO: this has to be verified!
                    this._writer.WriteEndElement();                                            //spcPct
                }
                else
                {
                    this._writer.WriteStartElement("a", "spcPct", OpenXmlNamespaces.DrawingML);
                    this._writer.WriteAttributeString("val", pr.SpaceAfter.ToString());
                    this._writer.WriteEndElement(); //spcPct
                }
                this._writer.WriteEndElement();     //spcAft
            }
            //EG_TextBulletColor
            //EG_TextBulletSize
            //EG_TextBulletTypeFace
            //EG_TextBullet


            bool bulletwritten = false;

            if (pr9 != null)
            {
                if (pr9.BulletBlipReferencePresent)
                {
                    foreach (var progtags in this._ctx.Ppt.DocumentRecord.FirstChildWithType <List>().AllChildrenWithType <ProgTags>())
                    {
                        foreach (var bintags in progtags.AllChildrenWithType <ProgBinaryTag>())
                        {
                            foreach (var data in bintags.AllChildrenWithType <ProgBinaryTagDataBlob>())
                            {
                                foreach (var blips in data.AllChildrenWithType <BlipCollection9Container>())
                                {
                                    if (blips.Children.Count > pr9.bulletblipref & pr9.bulletblipref > -1)
                                    {
                                        ImagePart imgPart = null;

                                        var b = ((BlipEntityAtom)blips.Children[pr9.bulletblipref]).blip;

                                        if (b == null)
                                        {
                                            var mb = ((BlipEntityAtom)blips.Children[pr9.bulletblipref]).mblip;
                                            imgPart = this._parentSlideMapping.targetPart.AddImagePart(ShapeTreeMapping.getImageType(mb.TypeCode));
                                            imgPart.TargetDirectory = "..\\media";
                                            var outStream    = imgPart.GetStream();
                                            var decompressed = mb.Decrompress();
                                            outStream.Write(decompressed, 0, decompressed.Length);
                                            //outStream.Write(mb.m_pvBits, 0, mb.m_pvBits.Length);
                                        }
                                        else
                                        {
                                            imgPart = this._parentSlideMapping.targetPart.AddImagePart(ShapeTreeMapping.getImageType(b.TypeCode));
                                            imgPart.TargetDirectory = "..\\media";
                                            var outStream = imgPart.GetStream();
                                            outStream.Write(b.m_pvBits, 0, b.m_pvBits.Length);
                                        }

                                        this._writer.WriteStartElement("a", "buBlip", OpenXmlNamespaces.DrawingML);
                                        this._writer.WriteStartElement("a", "blip", OpenXmlNamespaces.DrawingML);
                                        this._writer.WriteAttributeString("r", "embed", OpenXmlNamespaces.Relationships, imgPart.RelIdToString);
                                        this._writer.WriteEndElement(); //blip
                                        this._writer.WriteEndElement(); //buBlip
                                        bulletwritten = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (!bulletwritten & !isTitle)
            {
                if (pr.BulletFlagsFieldPresent & (pr.BulletFlags & (ushort)ParagraphMask.HasBullet) == 0)
                {
                    this._writer.WriteElementString("a", "buNone", OpenXmlNamespaces.DrawingML, "");
                }
                else
                {
                    if (pr.BulletColorPresent && (!(pr.BulletFlagsFieldPresent && (pr.BulletFlags & 1 << 2) == 0)))
                    {
                        writeBuClr((RegularContainer)this._Master, pr.BulletColor, ref this.lastBulletColor);
                    }
                    else if (this.lastBulletColor.Length > 0)
                    {
                        this._writer.WriteStartElement("a", "buClr", OpenXmlNamespaces.DrawingML);
                        this._writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                        this._writer.WriteAttributeString("val", this.lastBulletColor);
                        this._writer.WriteEndElement();
                        this._writer.WriteEndElement(); //buClr
                    }

                    if (pr.BulletSizePresent)
                    {
                        if (pr.BulletSize > 0 && pr.BulletSize != 100)
                        {
                            this._writer.WriteStartElement("a", "buSzPct", OpenXmlNamespaces.DrawingML);
                            this._writer.WriteAttributeString("val", (pr.BulletSize * 1000).ToString());
                            this._writer.WriteEndElement(); //buSzPct
                        }
                        else
                        {
                            //TODO
                        }
                    }



                    if (pr.BulletFontPresent)
                    {
                        this._writer.WriteStartElement("a", "buFont", OpenXmlNamespaces.DrawingML);
                        var fonts  = this._ctx.Ppt.DocumentRecord.FirstChildWithType <b2xtranslator.PptFileFormat.Environment>().FirstChildWithType <FontCollection>();
                        var entity = fonts.entities[(int)pr.BulletTypefaceIdx];
                        if (entity.TypeFace.IndexOf('\0') > 0)
                        {
                            this._writer.WriteAttributeString("typeface", entity.TypeFace.Substring(0, entity.TypeFace.IndexOf('\0')));
                        }
                        else
                        {
                            this._writer.WriteAttributeString("typeface", entity.TypeFace);
                        }
                        this._writer.WriteEndElement(); //buChar
                        this.lastBulletFont = entity.TypeFace;
                    }
                    else if (this.lastBulletFont.Length > 0)
                    {
                        this._writer.WriteStartElement("a", "buFont", OpenXmlNamespaces.DrawingML);
                        if (this.lastBulletFont.IndexOf('\0') > 0)
                        {
                            this._writer.WriteAttributeString("typeface", this.lastBulletFont.Substring(0, this.lastBulletFont.IndexOf('\0')));
                        }
                        else
                        {
                            this._writer.WriteAttributeString("typeface", this.lastBulletFont);
                        }
                        this._writer.WriteEndElement(); //buChar
                    }
                    if (pr.BulletCharPresent)
                    {
                        this._writer.WriteStartElement("a", "buChar", OpenXmlNamespaces.DrawingML);
                        this._writer.WriteAttributeString("char", pr.BulletChar.ToString());
                        this._writer.WriteEndElement(); //buChar
                        this.lastBulletChar = pr.BulletChar.ToString();
                    }
                    else if (this.lastBulletChar.Length > 0)
                    {
                        this._writer.WriteStartElement("a", "buChar", OpenXmlNamespaces.DrawingML);
                        this._writer.WriteAttributeString("char", this.lastBulletChar);
                        this._writer.WriteEndElement(); //buChar
                    }
                }
            }

            //tabLst
            //defRPr
            //extLst

            new CharacterRunPropsMapping(this._ctx, this._writer).Apply(cr, "defRPr", (RegularContainer)this._Master, ref this.lastColor, ref this.lastSize, ref this.lastTypeface, "", "", null, IndentLevel, null, null, 0, false);

            this._writer.WriteEndElement(); //lvlXpPr
        }
Пример #26
0
        /// <summary>
        /// Create the image to integrate
        /// </summary>
        /// <param name="imagePart"></param>
        /// <param name="model"></param>
        /// <param name="mainDocumentPart"></param>
        /// <returns></returns>
        private static OpenXmlElement CreateImage(ImagePart imagePart, Models.Image model, OpenXmlPart mainDocumentPart)
        {
            string relationshipId = mainDocumentPart.GetIdOfPart(imagePart);

            long imageWidth;
            long imageHeight;

            using (var image = SixLabors.ImageSharp.Image.Load(imagePart.GetStream()))
            {
                long bmWidth  = image.Width;
                long bmHeight = image.Height;

                // Resize width
                if (model.Width.HasValue)
                {
                    long ratio = model.Width.Value * 100L / bmWidth;

                    bmWidth  = (long)(bmWidth * (ratio / 100D));
                    bmHeight = (long)(bmHeight * (ratio / 100D));
                }

                // Resize width if too big
                if (model.MaxWidth.HasValue && model.MaxWidth.Value < bmWidth)
                {
                    long ratio = model.MaxWidth.Value * 100L / bmWidth;

                    bmWidth  = (long)(bmWidth * (ratio / 100D));
                    bmHeight = (long)(bmHeight * (ratio / 100D));
                }

                // Resize height
                if (model.Height.HasValue)
                {
                    long ratio = model.Height.Value * 100L / bmHeight;

                    bmWidth  = (long)(bmWidth * (ratio / 100D));
                    bmHeight = (long)(bmHeight * (ratio / 100D));
                }

                // Resize height if too big
                if (model.MaxHeight.HasValue && model.MaxHeight.Value < bmHeight)
                {
                    long ratio = model.MaxHeight.Value * 100L / bmHeight;

                    bmWidth  = (long)(bmWidth * (ratio / 100D));
                    bmHeight = (long)(bmHeight * (ratio / 100D));
                }

                var xResolution = image.MetaData.HorizontalResolution;
                var yResolution = image.MetaData.VerticalResolution;

                // The resolution may come in differents units, convert it to pixels per inch
                if (image.MetaData.ResolutionUnits == PixelResolutionUnit.PixelsPerMeter)
                {
                    xResolution *= 0.0254;
                    yResolution *= 0.0254;
                }
                else if (image.MetaData.ResolutionUnits == PixelResolutionUnit.PixelsPerCentimeter)
                {
                    xResolution *= 2.54;
                    yResolution *= 2.54;
                }

                imageWidth  = bmWidth * (long)(914400 / xResolution);
                imageHeight = bmHeight * (long)(914400 / yResolution);
            }

            var result = new Run();

            var runProperties = new RunProperties();

            runProperties.AppendChild(new NoProof());
            result.AppendChild(runProperties);

            var graphicFrameLocks = new A.GraphicFrameLocks()
            {
                NoChangeAspect = true
            };

            graphicFrameLocks.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");

            var picture = new PIC.Picture(
                new PIC.NonVisualPictureProperties(
                    new PIC.NonVisualDrawingProperties()
            {
                Id   = 0U,
                Name = "New Bitmap Image.jpg"
            },
                    new PIC.NonVisualPictureDrawingProperties()),
                new PIC.BlipFill(
                    new A.Blip()
            {
                Embed            = relationshipId,
                CompressionState =
                    A.BlipCompressionValues.Print
            },
                    new A.Stretch(new A.FillRectangle())),
                new PIC.ShapeProperties(
                    new A.Transform2D(
                        new A.Offset()
            {
                X = 0L, Y = 0L
            },
                        new A.Extents()
            {
                Cx = imageWidth, Cy = imageHeight
            }),
                    new A.PresetGeometry(new A.AdjustValueList())
            {
                Preset = A.ShapeTypeValues.Rectangle
            }));

            picture.AddNamespaceDeclaration("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");

            var graphic = new A.Graphic(
                new A.GraphicData(
                    picture
                    )
            {
                Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
            });

            graphic.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");

            result.Append(new DocumentFormat.OpenXml.Wordprocessing.Drawing(
                              new DW.Inline(
                                  new DW.Extent()
            {
                Cx = imageWidth, Cy = imageHeight
            },
                                  new DW.EffectExtent()
            {
                LeftEdge   = 0L,
                TopEdge    = 0L,
                RightEdge  = 0L,
                BottomEdge = 0L
            },
                                  new DW.DocProperties()
            {
                Id   = 1U,
                Name = "Picture 1"
            },
                                  new DW.NonVisualGraphicFrameDrawingProperties(graphicFrameLocks),
                                  graphic
                                  )
            {
                DistanceFromTop    = 0U,
                DistanceFromBottom = 0U,
                DistanceFromLeft   = 0U,
                DistanceFromRight  = 0U
            }));
            return(result);
        }
Пример #27
0
        /// <summary>
        /// Copies the picture from the binary stream to the zip archive
        /// and creates the relationships for the image.
        /// </summary>
        /// <param name="pict">The PictureDescriptor</param>
        /// <returns>The created ImagePart</returns>
        protected ImagePart copyPicture(BlipStoreEntry bse)
        {
            //create the image part
            ImagePart imgPart = null;

            if (bse != null)
            {
                switch (bse.btWin32)
                {
                case BlipStoreEntry.BlipType.msoblipEMF:
                    imgPart = _targetPart.AddImagePart(ImagePart.ImageType.Emf);
                    break;

                case BlipStoreEntry.BlipType.msoblipWMF:
                    imgPart = _targetPart.AddImagePart(ImagePart.ImageType.Wmf);
                    break;

                case BlipStoreEntry.BlipType.msoblipJPEG:
                case BlipStoreEntry.BlipType.msoblipCMYKJPEG:
                    imgPart = _targetPart.AddImagePart(ImagePart.ImageType.Jpeg);
                    break;

                case BlipStoreEntry.BlipType.msoblipPNG:
                    imgPart = _targetPart.AddImagePart(ImagePart.ImageType.Png);
                    break;

                case BlipStoreEntry.BlipType.msoblipTIFF:
                    imgPart = _targetPart.AddImagePart(ImagePart.ImageType.Tiff);
                    break;

                case BlipStoreEntry.BlipType.msoblipPICT:
                case BlipStoreEntry.BlipType.msoblipERROR:
                case BlipStoreEntry.BlipType.msoblipUNKNOWN:
                case BlipStoreEntry.BlipType.msoblipLastClient:
                case BlipStoreEntry.BlipType.msoblipFirstClient:
                case BlipStoreEntry.BlipType.msoblipDIB:
                    //throw new MappingException("Cannot convert picture of type " + bse.btWin32);
                    break;
                }

                if (imgPart != null)
                {
                    Stream outStream = imgPart.GetStream();

                    //write the blip
                    if (bse.Blip != null)
                    {
                        switch (bse.btWin32)
                        {
                        case BlipStoreEntry.BlipType.msoblipEMF:
                        case BlipStoreEntry.BlipType.msoblipWMF:

                            //it's a meta image
                            MetafilePictBlip metaBlip = (MetafilePictBlip)bse.Blip;

                            //meta images can be compressed
                            byte[] decompressed = metaBlip.Decrompress();
                            outStream.Write(decompressed, 0, decompressed.Length);

                            break;

                        case BlipStoreEntry.BlipType.msoblipJPEG:
                        case BlipStoreEntry.BlipType.msoblipCMYKJPEG:
                        case BlipStoreEntry.BlipType.msoblipPNG:
                        case BlipStoreEntry.BlipType.msoblipTIFF:

                            //it's a bitmap image
                            BitmapBlip bitBlip = (BitmapBlip)bse.Blip;
                            outStream.Write(bitBlip.m_pvBits, 0, bitBlip.m_pvBits.Length);

                            break;
                        }
                    }
                }
            }
            return(imgPart);
        }
Пример #28
0
    /// <summary>
    /// 读取Excel中数据,包括样式
    /// </summary>
    /// <param name="excel"></param>
    /// <param name="sheetName"></param>
    /// <param name="file"></param>
    /// <returns></returns>
    public static List <SheetDataList> ReadExcelDetailTest(SpreadsheetDocument excel, List <string> sheetName, string file)
    {
        try
        {
            #region //获取样式设置
            Stylesheet styleSheet = excel.WorkbookPart.WorkbookStylesPart.Stylesheet;

            //获取Excel文件主题色
            ThemePart themPart  = excel.WorkbookPart.ThemePart;
            var       themColor = ThemeColor.GetThemeColorList(themPart);

            #region 样式列表
            CellFormats            cellFormats     = styleSheet.CellFormats;
            List <CellFormatsList> cellFormatsList = new List <CellFormatsList>();
            int index = 0;
            foreach (CellFormat cell in cellFormats.ChildElements)
            {
                if (cell != null)
                {
                    CellFormatsList cfl = new CellFormatsList();
                    cfl.styleIndex = index;
                    if (cell.NumberFormatId != null)
                    {
                        cfl.numFmtId = int.Parse(cell.NumberFormatId);
                    }
                    if (cell.FontId != null)
                    {
                        cfl.fontId = int.Parse(cell.FontId);
                    }
                    if (cell.FillId != null)
                    {
                        cfl.fillId = int.Parse(cell.FillId);
                    }
                    if (cell.BorderId != null)
                    {
                        cfl.borderId = int.Parse(cell.BorderId);
                    }
                    if (cell.ApplyAlignment != null)
                    {
                        cfl.applyAlignment = int.Parse(cell.ApplyAlignment);
                    }
                    if (cell.ApplyBorder != null)
                    {
                        cfl.applyBorder = int.Parse(cell.ApplyBorder);
                    }
                    if (cell.ApplyFont != null)
                    {
                        cfl.applyFont = int.Parse(cell.ApplyFont);
                    }
                    if (cell.ApplyNumberFormat != null)
                    {
                        cfl.applyNumberFormat = int.Parse(cell.ApplyNumberFormat);
                    }
                    if (cell.Alignment != null)
                    {
                        string ver = cell.Alignment.Vertical;
                        string hor = cell.Alignment.Horizontal;
                        string wra = cell.Alignment.WrapText;
                        if (!string.IsNullOrEmpty(ver))
                        {
                            if (ver == "center")
                            {
                                cfl.vertical = "htMiddle";
                            }
                            else
                            {
                                cfl.vertical = "ht" + ver.Substring(0, 1).ToUpper() + ver.Substring(1, ver.Length - 1);
                            }
                        }
                        else
                        {
                            cfl.vertical = "htBottom";
                        }
                        if (!string.IsNullOrEmpty(hor))
                        {
                            cfl.horizontal = "ht" + hor.Substring(0, 1).ToUpper() + hor.Substring(1, hor.Length - 1);
                        }
                        else
                        {
                            cfl.horizontal = "htLeft";
                        }
                        cfl.wraptext = wra;
                    }
                    cellFormatsList.Add(cfl);
                    index++;
                }
            }
            #endregion

            #region 数据类型列表
            NumberingFormats   numberFormats = styleSheet.NumberingFormats;
            List <NumFmtsList> numFmtList    = new List <NumFmtsList>();
            if (numberFormats != null)
            {
                foreach (NumberingFormat cell in numberFormats.ChildElements)
                {
                    NumFmtsList nfl = new NumFmtsList();
                    if (cell.NumberFormatId != null)
                    {
                        nfl.numFmtId = (int)cell.NumberFormatId.Value;
                    }
                    if (cell.FormatCode != null)
                    {
                        nfl.formatCode = cell.FormatCode.Value;
                    }
                    numFmtList.Add(nfl);
                }
            }
            #endregion

            #region 字体样式
            Fonts            fonts     = styleSheet.Fonts;
            List <FontsList> fontsList = new List <FontsList>();
            foreach (Font cell in fonts.ChildElements)
            {
                FontsList fl = new FontsList();
                if (cell.FontSize != null)
                {
                    fl.fontsize = cell.FontSize.Val + "px";
                }
                if (cell.FontName != null)
                {
                    fl.fontname = cell.FontName.Val;
                }
                if (cell.Color != null)
                {
                    if (cell.Color.Rgb != null && !string.IsNullOrEmpty(cell.Color.Rgb.ToString()))
                    {
                        fl.color = "#" + cell.Color.Rgb.ToString().Substring(2, 6);
                    }
                }
                if (cell.Italic != null)
                {
                    fl.italic = "italic";
                }
                if (cell.Bold != null)
                {
                    fl.bold = "bold";
                }
                if (cell.Underline != null)
                {
                    fl.underline = "underline";
                }
                fontsList.Add(fl);
            }
            #endregion

            #region 填充色样式
            Fills            fills     = styleSheet.Fills;
            List <FillsList> fillsList = new List <FillsList>();
            foreach (Fill cell in fills.ChildElements)
            {
                FillsList fl = new FillsList();
                if (cell.PatternFill != null)
                {
                    fl.patternType = cell.PatternFill.PatternType;
                    if (cell.PatternFill.ForegroundColor != null)
                    {
                        if (cell.PatternFill.ForegroundColor.Rgb != null)
                        {
                            fl.fgColor = "#" + cell.PatternFill.ForegroundColor.Rgb.ToString().Substring(2, 6);
                        }
                        if (cell.PatternFill.ForegroundColor.Theme != null)
                        {
                            UInt32Value themeIndex = cell.PatternFill.ForegroundColor.Theme;
                            DoubleValue tint       = cell.PatternFill.ForegroundColor.Tint;
                            if (tint != null)
                            {
                                var newColor = ThemeColor.ThemColorDeal(themeIndex, tint, themColor[themeIndex]);
                                fl.fgColor = "#" + newColor.Name.Substring(2, 6);
                                fl.fgColor = "#" + newColor.Name.Substring(2, 6);
                            }
                            else
                            {
                                fl.fgColor = "#" + themColor[themeIndex];
                                fl.fgColor = "#" + themColor[themeIndex];
                            }
                        }
                    }
                }
                fillsList.Add(fl);
            }
            #endregion

            #region 边框样式
            Borders            borders     = styleSheet.Borders;
            List <BordersList> bordersList = new List <BordersList>();
            var defaultBorderStyle         = "1px solid #000";
            foreach (Border cell in borders.ChildElements)
            {
                BordersList bl = new BordersList();
                if (cell.LeftBorder != null)
                {
                    if (cell.LeftBorder.Style != null)
                    {
                        bl.left = defaultBorderStyle;
                    }
                }
                if (cell.RightBorder != null)
                {
                    if (cell.RightBorder.Style != null)
                    {
                        bl.right = defaultBorderStyle;
                    }
                }
                if (cell.TopBorder != null)
                {
                    if (cell.TopBorder.Style != null)
                    {
                        bl.top = defaultBorderStyle;
                    }
                }
                if (cell.BottomBorder != null)
                {
                    if (cell.BottomBorder.Style != null)
                    {
                        bl.bottom = defaultBorderStyle;
                    }
                }
                if (cell.DiagonalBorder != null)
                {
                    if (cell.DiagonalBorder.Style != null)
                    {
                        bl.diagonal = cell.DiagonalBorder.Style;
                    }
                }
                bordersList.Add(bl);
            }
            #endregion

            #endregion

            List <SheetDataList> listSDL  = new List <SheetDataList>();
            List <PictureInfo>   pictures = null;
            //获取多个Sheet数据和样式
            for (int i = 0; i < sheetName.Count; i++)
            {
                //总行数和总列数
                int           RowCount = 0, ColumnCount = 0;
                SheetDataList sdl = new SheetDataList();
                //获取一个工作表的数据
                WorksheetPart worksheet = ExcelHelper.GetWorksheetPartByName(excel, sheetName[i]);

                #region //批注
                WorksheetCommentsPart   comments     = worksheet.WorksheetCommentsPart;
                List <CommentCellsList> commentLists = new List <CommentCellsList>();
                if (comments != null)
                {
                    CommentList commentList = (CommentList)comments.Comments.ChildElements[1];
                    //批注列表
                    foreach (Comment comment in commentList.ChildElements)
                    {
                        CommentCellsList ccl = new CommentCellsList();
                        //坐标
                        var cell      = GetCellXY(comment.Reference).Split('_');
                        var columnRow = int.Parse(cell[0].ToString()) - 1;
                        var columnCol = GetColumnIndex(cell[1]);
                        //批注内容
                        var commentVal = comment.InnerText;
                        ccl.row     = columnRow;
                        ccl.col     = columnCol;
                        ccl.comment = comment.InnerText;
                        //var commentCell = "{\"Row\":\""+ columnRow + "\",\"Col\":\"" + columnCol + ",\"Comment\":\"" + commentVal + "\"}";
                        commentLists.Add(ccl);
                    }
                }
                sdl.Comments = commentLists;
                #endregion

                #region //获取合并单元格
                IEnumerable <MergeCells> mergeCells    = worksheet.Worksheet.Elements <MergeCells>();
                List <MergeCellsList>    mergeCellList = new List <MergeCellsList>();
                if (mergeCells.Count() > 0)
                {
                    for (int k = 0; k < mergeCells.First().ChildElements.Count; k++)
                    {
                        MergeCell      mergeCell = (MergeCell)mergeCells.First().ChildElements[k];
                        var            reference = mergeCell.Reference.ToString().Split(':');
                        var            startCell = GetCellXY(reference[0]).Split('_');
                        var            endCell   = GetCellXY(reference[1]).Split('_');
                        MergeCellsList mcl       = new MergeCellsList();
                        mcl.row     = int.Parse(startCell[0]) - 1;
                        mcl.rowspan = int.Parse(endCell[0]) - int.Parse(startCell[0]) + 1;
                        mcl.col     = GetColumnIndex(startCell[1]);
                        mcl.colspan = GetColumnIndex(endCell[1]) - mcl.col + 1;
                        //mcl.reference = mergeCell.Reference.ToString();
                        mergeCellList.Add(mcl);
                    }
                }
                sdl.MergeCells = mergeCellList;
                #endregion

                #region //读取图片
                DrawingsPart drawingPart = worksheet.GetPartsOfType <DrawingsPart>().ToList().FirstOrDefault();
                pictures = new List <PictureInfo>();
                if (drawingPart != null)
                {
                    int tempIndex = 1;
                    foreach (var part in drawingPart.Parts)
                    {
                        PictureInfo          pic     = new PictureInfo();
                        ImagePart            imgPart = (ImagePart)part.OpenXmlPart;
                        System.Drawing.Image img1    = System.Drawing.Image.FromStream(imgPart.GetStream());

                        var      newFilename = Guid.NewGuid().ToString("N") + ".png";
                        string[] sArray      = Regex.Split(file, "UserFile", RegexOptions.IgnoreCase);
                        string   newFilePath = sArray[0] + "_Temp\\" + newFilename;
                        img1.Save(newFilePath);
                        //pic.Image = img1;
                        pic.RefId     = part.RelationshipId;//"rId" + imgPart.Uri.ToString().Split('/')[3].Split('.')[0].Substring(5);
                        pic.ImageUrl  = newFilePath;
                        pic.ImageName = newFilename;
                        pic.ImgHeight = img1.Height;
                        pic.ImgWidth  = img1.Width;
                        pictures.Add(pic);
                        tempIndex++;
                    }
                    //获取图片定位
                    var worksheetDrawings = drawingPart.WorksheetDrawing.Where(c => c.ChildElements.Any
                                                                                   (a => a.GetType().FullName == "DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture")).ToList();
                    foreach (var worksheetDrawing in worksheetDrawings)
                    {
                        if (worksheetDrawing.GetType().FullName ==
                            "DocumentFormat.OpenXml.Drawing.Spreadsheet.TwoCellAnchor")
                        {
                            TwoCellAnchor anchor = (TwoCellAnchor)worksheetDrawing;
                            DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picDef =
                                (DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture)
                                anchor.ChildElements.FirstOrDefault(c => c.GetType().FullName ==
                                                                    "DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture");
                            if (picDef != null)
                            {
                                var embed = picDef.BlipFill.Blip.Embed;
                                if (embed != null)
                                {
                                    var picMapping = pictures.FirstOrDefault(c => c.RefId == embed.InnerText);
                                    picMapping.FromCol = int.Parse(anchor.FromMarker.ColumnId.InnerText);
                                    picMapping.FromRow = int.Parse(anchor.FromMarker.RowId.InnerText);
                                }
                            }
                            // anchor.FromMarker.RowId + anchor.FromMarker.ColumnId
                        }
                    }
                }
                sdl.PictureList = pictures;
                #endregion

                //读取列宽
                IEnumerable <Columns> colsList = worksheet.Worksheet.Elements <Columns>();

                #region //读取表格数据
                List <SheetDatas> sheetDatas = new List <SheetDatas>();
                if (worksheet.Rows().Count() > 0)
                {
                    RowCount = int.Parse((worksheet.Rows().Last()).RowId);
                }
                foreach (OpenXmlPowerTools.Row row in worksheet.Rows())
                {
                    int TempColumn = 0;
                    int r          = 0;
                    foreach (OpenXmlPowerTools.Cell cell in row.Cells())
                    {
                        int co = 0;
                        //读取超链接???

                        //读取单元格数据
                        SheetDatas sheetData = new SheetDatas();
                        sheetData.RowId        = int.Parse(row.RowId) - 1;
                        sheetData.ColumnId     = cell.ColumnIndex;
                        sheetData.Column       = cell.Column;
                        sheetData.Type         = cell.Type;
                        sheetData.Value        = cell.Value;
                        sheetData.SharedString = cell.SharedString;
                        sheetData.Formula      = cell.Formula;
                        sheetData.StyleId      = cell.Style;
                        //读取列宽(仅限第一行设置列宽)
                        if (colsList.Count() > 0 && r == 0)
                        {
                            Columns col = colsList.ElementAt <Columns>(0);
                            foreach (Column c in col.ChildElements)
                            {
                                if (c.Max == cell.ColumnIndex)
                                {
                                    sheetData.Width = c.Width;
                                    break;
                                }
                            }
                        }
                        //读取行高(仅限第一列设置行高)
                        if (co == 0)
                        {
                            if (row.RowElement.Attribute("ht") != null)
                            {
                                sheetData.Height = double.Parse(row.RowElement.Attribute("ht").Value);
                            }
                        }
                        #region 样式赋值
                        if (sheetData.StyleId != null)
                        {
                            CellFormatsList cfl = cellFormatsList[(int)sheetData.StyleId];
                            //字体样式
                            sheetData.FontName           = fontsList[cfl.fontId].fontname;
                            sheetData.FontSize           = fontsList[cfl.fontId].fontsize;
                            sheetData.FontColor          = fontsList[cfl.fontId].color;
                            sheetData.FontBold           = fontsList[cfl.fontId].bold;
                            sheetData.Italic             = fontsList[cfl.fontId].italic;
                            sheetData.Underline          = fontsList[cfl.fontId].underline;
                            sheetData.AligmentVertical   = cfl.vertical;
                            sheetData.AligmentHorizontal = cfl.horizontal;
                            sheetData.WrapText           = cfl.wraptext;
                            //背景色样式
                            sheetData.FillType            = fillsList[cfl.fillId].patternType;
                            sheetData.FillForegroundColor = fillsList[cfl.fillId].fgColor;
                            sheetData.FillBackgroundColor = fillsList[cfl.fillId].bgColor;
                            //边框样式
                            sheetData.LeftBorder     = bordersList[cfl.borderId].left;
                            sheetData.RightBorder    = bordersList[cfl.borderId].right;
                            sheetData.TopBorder      = bordersList[cfl.borderId].top;
                            sheetData.BottomBorder   = bordersList[cfl.borderId].bottom;
                            sheetData.DiagonalBorder = bordersList[cfl.borderId].diagonal;
                        }
                        #endregion

                        //识别文字格式???(日期与数字的区别)

                        sheetDatas.Add(sheetData);
                        TempColumn++;
                        co++;
                    }
                    r++;
                    //计算列数
                    if (TempColumn > ColumnCount)
                    {
                        ColumnCount = TempColumn;
                    }
                }
                sdl.SheetData = sheetDatas;
                #endregion

                sdl.SheetName   = sheetName[i];
                sdl.SheetId     = "sheet" + (i + 1);
                sdl.TotalRow    = RowCount < 20 ? 20 : RowCount + 1;
                sdl.TotalColumn = ColumnCount < 15 ? 15 : ColumnCount + 1;
                listSDL.Add(sdl);
            }
            return(listSDL);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
Пример #29
0
        public void Apply(ShapeOptions so)
        {
            RegularContainer slide = so.FirstAncestorWithType <Slide>();

            if (slide == null)
            {
                slide = so.FirstAncestorWithType <Note>();
            }
            if (slide == null)
            {
                slide = so.FirstAncestorWithType <Handout>();
            }
            string colorval  = "";
            string colorval2 = "";
            uint   fillType  = 0;

            if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillType))
            {
                fillType = so.OptionsByID[ShapeOptions.PropertyId.fillType].op;
            }
            switch (fillType)
            {
            case 0x0:     //solid
                string SchemeType = "";


                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillColor))
                {
                    colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillColor].op, (RegularContainer)slide, so, ref SchemeType);
                }
                else
                {
                    colorval = "FFFFFF";     //TODO: find out which color to use in this case
                }
                _writer.WriteStartElement("a", "solidFill", OpenXmlNamespaces.DrawingML);

                if (SchemeType.Length == 0)
                {
                    _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", colorval);
                }
                else
                {
                    _writer.WriteStartElement("a", "schemeClr", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", SchemeType);
                }

                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillOpacity) && so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op != 65536)
                {
                    _writer.WriteStartElement("a", "alpha", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op / 65536 * 100000)).ToString());     //we need the percentage of the opacity (65536 means 100%)
                    _writer.WriteEndElement();
                }
                _writer.WriteEndElement();
                _writer.WriteEndElement();
                break;

            case 0x1:     //pattern
                uint           blipIndex1 = so.OptionsByID[ShapeOptions.PropertyId.fillBlip].op;
                DrawingGroup   gr1        = (DrawingGroup)this._ctx.Ppt.DocumentRecord.FirstChildWithType <PPDrawingGroup>().Children[0];
                BlipStoreEntry bse1       = (BlipStoreEntry)gr1.FirstChildWithType <BlipStoreContainer>().Children[(int)blipIndex1 - 1];
                BitmapBlip     b1         = (BitmapBlip)_ctx.Ppt.PicturesContainer._pictures[bse1.foDelay];

                _writer.WriteStartElement("a", "pattFill", OpenXmlNamespaces.DrawingML);

                _writer.WriteAttributeString("prst", Utils.getPrstForPatternCode(b1.m_bTag));     //Utils.getPrstForPattern(blipNamePattern));

                _writer.WriteStartElement("a", "fgClr", OpenXmlNamespaces.DrawingML);
                _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                _writer.WriteAttributeString("val", Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillColor].op, slide, so));
                _writer.WriteEndElement();
                _writer.WriteEndElement();

                _writer.WriteStartElement("a", "bgClr", OpenXmlNamespaces.DrawingML);
                _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBackColor))
                {
                    colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillBackColor].op, slide, so);
                }
                else
                {
                    colorval = "ffffff";     //TODO: find out which color to use in this case
                }
                _writer.WriteAttributeString("val", colorval);
                _writer.WriteEndElement();
                _writer.WriteEndElement();

                _writer.WriteEndElement();

                break;

            case 0x2:     //texture
            case 0x3:     //picture
                uint   blipIndex = 0;
                string strUrl    = "";

                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBlip))
                {
                    blipIndex = so.OptionsByID[ShapeOptions.PropertyId.fillBlip].op;
                }
                else if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.Pib))
                {
                    blipIndex = so.OptionsByID[ShapeOptions.PropertyId.Pib].op;
                }
                else if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBlipFlags) && so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBlipName))
                {
                    uint flags      = so.OptionsByID[ShapeOptions.PropertyId.fillBlipFlags].op;
                    bool comment    = !Tools.Utils.BitmaskToBool(flags, 0x1);
                    bool file       = Tools.Utils.BitmaskToBool(flags, 0x1);
                    bool url        = Tools.Utils.BitmaskToBool(flags, 0x1 << 1);
                    bool DoNotSave  = Tools.Utils.BitmaskToBool(flags, 0x1 << 2);
                    bool LinkToFile = Tools.Utils.BitmaskToBool(flags, 0x1 << 3);

                    if (url)
                    {
                        strUrl = ASCIIEncoding.ASCII.GetString(so.OptionsByID[ShapeOptions.PropertyId.fillBlipName].opComplex);
                        strUrl = strUrl.Replace("\0", "");
                    }
                }
                else
                {
                    break;
                }

                //string blipName = Encoding.UTF8.GetString(so.OptionsByID[ShapeOptions.PropertyId.fillBlipName].opComplex);
                string       rId     = "";
                DrawingGroup gr      = (DrawingGroup)this._ctx.Ppt.DocumentRecord.FirstChildWithType <PPDrawingGroup>().Children[0];
                ImagePart    imgPart = null;


                if (strUrl.Length > 0)
                {
                    ExternalRelationship er = _parentSlideMapping.targetPart.AddExternalRelationship(OpenXmlRelationshipTypes.Image, strUrl);

                    rId = er.Id;

                    _writer.WriteStartElement("a", "blipFill", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("dpi", "0");
                    _writer.WriteAttributeString("rotWithShape", "1");

                    _writer.WriteStartElement("a", "blip", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("r", "link", OpenXmlNamespaces.Relationships, rId);



                    _writer.WriteEndElement();

                    _writer.WriteElementString("a", "srcRect", OpenXmlNamespaces.DrawingML, "");

                    if (fillType == 0x3)
                    {
                        _writer.WriteStartElement("a", "stretch", OpenXmlNamespaces.DrawingML);
                        _writer.WriteElementString("a", "fillRect", OpenXmlNamespaces.DrawingML, "");
                        _writer.WriteEndElement();
                    }
                    else
                    {
                        _writer.WriteStartElement("a", "tile", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("tx", "0");
                        _writer.WriteAttributeString("ty", "0");
                        _writer.WriteAttributeString("sx", "100000");
                        _writer.WriteAttributeString("sy", "100000");
                        _writer.WriteAttributeString("flip", "none");
                        _writer.WriteAttributeString("algn", "tl");
                        _writer.WriteEndElement();
                    }

                    _writer.WriteEndElement();
                }
                else if (blipIndex <= gr.FirstChildWithType <BlipStoreContainer>().Children.Count)
                {
                    BlipStoreEntry bse = (BlipStoreEntry)gr.FirstChildWithType <BlipStoreContainer>().Children[(int)blipIndex - 1];

                    if (_ctx.Ppt.PicturesContainer._pictures.ContainsKey(bse.foDelay))
                    {
                        Record rec = _ctx.Ppt.PicturesContainer._pictures[bse.foDelay];

                        if (rec is BitmapBlip)
                        {
                            BitmapBlip b = (BitmapBlip)_ctx.Ppt.PicturesContainer._pictures[bse.foDelay];
                            imgPart = _parentSlideMapping.targetPart.AddImagePart(ShapeTreeMapping.getImageType(b.TypeCode));
                            imgPart.TargetDirectory = "..\\media";
                            System.IO.Stream outStream = imgPart.GetStream();
                            outStream.Write(b.m_pvBits, 0, b.m_pvBits.Length);
                        }
                        else
                        {
                            MetafilePictBlip b = (MetafilePictBlip)_ctx.Ppt.PicturesContainer._pictures[bse.foDelay];
                            imgPart = _parentSlideMapping.targetPart.AddImagePart(ShapeTreeMapping.getImageType(b.TypeCode));
                            imgPart.TargetDirectory = "..\\media";
                            System.IO.Stream outStream    = imgPart.GetStream();
                            byte[]           decompressed = b.Decrompress();
                            outStream.Write(decompressed, 0, decompressed.Length);
                        }

                        rId = imgPart.RelIdToString;

                        _writer.WriteStartElement("a", "blipFill", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("dpi", "0");
                        _writer.WriteAttributeString("rotWithShape", "1");

                        _writer.WriteStartElement("a", "blip", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("r", "embed", OpenXmlNamespaces.Relationships, rId);



                        _writer.WriteEndElement();

                        _writer.WriteElementString("a", "srcRect", OpenXmlNamespaces.DrawingML, "");

                        if (fillType == 0x3)
                        {
                            _writer.WriteStartElement("a", "stretch", OpenXmlNamespaces.DrawingML);
                            _writer.WriteElementString("a", "fillRect", OpenXmlNamespaces.DrawingML, "");
                            _writer.WriteEndElement();
                        }
                        else
                        {
                            _writer.WriteStartElement("a", "tile", OpenXmlNamespaces.DrawingML);
                            _writer.WriteAttributeString("tx", "0");
                            _writer.WriteAttributeString("ty", "0");
                            _writer.WriteAttributeString("sx", "100000");
                            _writer.WriteAttributeString("sy", "100000");
                            _writer.WriteAttributeString("flip", "none");
                            _writer.WriteAttributeString("algn", "tl");
                            _writer.WriteEndElement();
                        }

                        _writer.WriteEndElement();
                    }
                }
                break;

            case 0x4:     //shade
            case 0x5:     //shadecenter
            case 0x6:     //shadeshape
                _writer.WriteStartElement("a", "gradFill", OpenXmlNamespaces.DrawingML);
                _writer.WriteAttributeString("rotWithShape", "1");
                _writer.WriteStartElement("a", "gsLst", OpenXmlNamespaces.DrawingML);
                bool useFillAndBack = true;

                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillShadeColors))
                {
                    byte[] colors = so.OptionsByID[ShapeOptions.PropertyId.fillShadeColors].opComplex;

                    if (colors != null && colors.Length > 0)
                    {
                        useFillAndBack = false;
                        ShapeOptions.OptionEntry type = so.OptionsByID[ShapeOptions.PropertyId.fillShadeType];

                        UInt16 nElems      = System.BitConverter.ToUInt16(colors, 0);
                        UInt16 nElemsAlloc = System.BitConverter.ToUInt16(colors, 2);
                        UInt16 cbElem      = System.BitConverter.ToUInt16(colors, 4);

                        List <string> positions = new List <string>();

                        switch (nElems)
                        {
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                            positions.Add("0");
                            positions.Add("30000");
                            positions.Add("65000");
                            positions.Add("90000");
                            positions.Add("100000");
                            break;

                        case 6:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        default:
                            positions.Add("0");
                            positions.Add("8000");
                            positions.Add("13000");
                            positions.Add("21000");
                            positions.Add("52000");
                            positions.Add("56000");
                            positions.Add("58000");
                            positions.Add("71000");
                            positions.Add("94000");
                            positions.Add("100000");
                            break;
                        }


                        string[] alphas = new string[nElems];
                        if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillOpacity))
                        {
                            decimal end   = Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op / 65536 * 100000));
                            decimal start = Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillBackOpacity].op / 65536 * 100000));
                            alphas[0] = start.ToString();
                            for (int i = 1; i < nElems - 1; i++)
                            {
                                alphas[i] = Math.Round(start + (end - start) / 3 * i).ToString();
                            }
                            //alphas[1] = Math.Round(start + (end - start) / 3).ToString();
                            //alphas[2] = Math.Round(start + (end - start) / 3 * 2).ToString();
                            //alphas[3] = Math.Round(start + (end - start) / 3 * 3).ToString();
                            alphas[nElems - 1] = end.ToString();
                        }

                        for (int i = 0; i < nElems * cbElem; i += cbElem)
                        {
                            colorval = Utils.getRGBColorFromOfficeArtCOLORREF(System.BitConverter.ToUInt32(colors, 6 + i), slide, so);
                            _writer.WriteStartElement("a", "gs", OpenXmlNamespaces.DrawingML);
                            _writer.WriteAttributeString("pos", positions[i / cbElem]);

                            _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                            _writer.WriteAttributeString("val", colorval);
                            if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillOpacity) && so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op != 65536)
                            {
                                _writer.WriteStartElement("a", "alpha", OpenXmlNamespaces.DrawingML);
                                _writer.WriteAttributeString("val", alphas[i / cbElem]);     //we need the percentage of the opacity (65536 means 100%)
                                _writer.WriteEndElement();
                            }
                            _writer.WriteEndElement();

                            _writer.WriteEndElement();
                        }
                    }
                }

                if (useFillAndBack)
                {
                    colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillColor].op, slide, so);

                    _writer.WriteStartElement("a", "gs", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("pos", "0");
                    _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", colorval);
                    if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillOpacity) && so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op != 65536)
                    {
                        _writer.WriteStartElement("a", "alpha", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("val", Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op / 65536 * 100000)).ToString());     //we need the percentage of the opacity (65536 means 100%)
                        _writer.WriteEndElement();
                    }
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();

                    if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBackColor))
                    {
                        colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillBackColor].op, slide, so);
                    }
                    else
                    {
                        if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.shadowColor))
                        {
                            colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.shadowColor].op, slide, so);
                        }
                        else
                        {
                            //use filColor
                        }
                    }

                    _writer.WriteStartElement("a", "gs", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("pos", "100000");
                    _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", colorval);
                    if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBackOpacity) && so.OptionsByID[ShapeOptions.PropertyId.fillBackOpacity].op != 65536)
                    {
                        _writer.WriteStartElement("a", "alpha", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("val", Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillBackOpacity].op / 65536 * 100000)).ToString());     //we need the percentage of the opacity (65536 means 100%)
                        _writer.WriteEndElement();
                    }
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();
                }

                _writer.WriteEndElement();     //gsLst

                switch (fillType)
                {
                case 0x5:
                case 0x6:
                    _writer.WriteStartElement("a", "path", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("path", "shape");
                    _writer.WriteStartElement("a", "fillToRect", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("l", "50000");
                    _writer.WriteAttributeString("t", "50000");
                    _writer.WriteAttributeString("r", "50000");
                    _writer.WriteAttributeString("b", "50000");
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();         //path
                    break;

                default:
                    _writer.WriteStartElement("a", "path", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("path", "rect");
                    _writer.WriteStartElement("a", "fillToRect", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("r", "100000");
                    _writer.WriteAttributeString("b", "100000");
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();         //path
                    break;
                }

                _writer.WriteEndElement();     //gradFill

                break;

            case 0x7:     //shadescale
                _writer.WriteStartElement("a", "gradFill", OpenXmlNamespaces.DrawingML);
                _writer.WriteAttributeString("rotWithShape", "1");
                _writer.WriteStartElement("a", "gsLst", OpenXmlNamespaces.DrawingML);

                decimal angle        = 90;
                bool    switchColors = false;
                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillAngle))
                {
                    if (so.OptionsByID[ShapeOptions.PropertyId.fillAngle].op != 0)
                    {
                        byte[]  bytes      = BitConverter.GetBytes(so.OptionsByID[ShapeOptions.PropertyId.fillAngle].op);
                        int     integral   = BitConverter.ToInt16(bytes, 0);
                        uint    fractional = BitConverter.ToUInt16(bytes, 2);
                        Decimal result     = integral + ((decimal)fractional / (decimal)65536);
                        angle = 65536 - fractional;     //I have no idea why this works!!
                        angle = angle - 90;
                        if (angle < 0)
                        {
                            angle       += 360;
                            switchColors = true;
                        }
                    }
                }

                Dictionary <int, string> shadeColorsDic = new Dictionary <int, string>();
                List <string>            shadeColors    = new List <string>();
                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillShadeColors) && so.OptionsByID[ShapeOptions.PropertyId.fillShadeColors].opComplex != null && so.OptionsByID[ShapeOptions.PropertyId.fillShadeColors].opComplex.Length > 0)
                {
                    uint length = so.OptionsByID[ShapeOptions.PropertyId.fillShadeColors].op;

                    //An IMsoArray record that specifies colors and their relative positions.
                    //Each element of the array contains an OfficeArtCOLORREF record color and a FixedPoint, as specified in [MS-OSHARED]
                    //section 2.2.1.6, that specifies its relative position along the gradient vector.
                    byte[] data = so.OptionsByID[ShapeOptions.PropertyId.fillShadeColors].opComplex;

                    int              pos = 0;
                    string           colval;
                    FixedPointNumber fixedpoint;
                    UInt16           nElems = BitConverter.ToUInt16(data, pos);
                    pos += 2;
                    UInt16 nElemsAlloc = BitConverter.ToUInt16(data, pos);
                    pos += 2;
                    UInt16 cbElem = BitConverter.ToUInt16(data, pos);
                    pos += 2;

                    if (cbElem == 0xFFF0)
                    {
                        //If this value is 0xFFF0 then this record is an array of truncated 8 byte elements. Only the 4 low-order bytes are recorded. Each element's 4 high-order bytes equal 0x00000000 and each element's 4 low-order bytes are contained in data.
                    }
                    else
                    {
                        while (pos < length)
                        {
                            colval = Utils.getRGBColorFromOfficeArtCOLORREF(BitConverter.ToUInt32(data, pos), slide, so);

                            pos       += 4;
                            fixedpoint = new FixedPointNumber(BitConverter.ToUInt16(data, pos), BitConverter.ToUInt16(data, pos + 2));
                            shadeColors.Insert(0, colval);
                            pos += 4;
                        }
                    }
                }
                else
                {
                    bool switchcolors = false;
                    if (switchColors & so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBackColor))
                    {
                        colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillBackColor].op, slide, so);
                    }
                    else
                    {
                        if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillColor))
                        {
                            colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillColor].op, slide, so);
                        }
                        else
                        {
                            colorval     = "FFFFFF"; //TODO: find out which color to use in this case
                            switchcolors = true;
                        }
                    }

                    if (switchColors | !so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBackColor))
                    {
                        colorval2 = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillColor].op, slide, so);
                    }
                    else
                    {
                        colorval2 = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillBackColor].op, slide, so);
                    }

                    if (switchcolors)
                    {
                        //this is a workaround for a bug. Further analysis necessarry
                        string dummy = colorval;
                        colorval  = colorval2;
                        colorval2 = dummy;
                    }

                    shadeColors.Add(colorval);
                    shadeColors.Add(colorval2);
                }


                int    gspos;
                string col;
                for (int i = 0; i < shadeColors.Count; i++)
                {
                    col = shadeColors[i];
                    if (i == 0)
                    {
                        gspos = 0;
                    }
                    else if (i == shadeColors.Count - 1)
                    {
                        gspos = 100000;
                    }
                    else
                    {
                        gspos = i * 100000 / shadeColors.Count;
                    }

                    _writer.WriteStartElement("a", "gs", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("pos", gspos.ToString());
                    _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", col);
                    if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillOpacity) && so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op != 65536)
                    {
                        _writer.WriteStartElement("a", "alpha", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("val", Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op / 65536 * 100000)).ToString());     //we need the percentage of the opacity (65536 means 100%)
                        _writer.WriteEndElement();
                    }

                    if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillShadeType))
                    {
                        uint flags    = so.OptionsByID[ShapeOptions.PropertyId.fillShadeType].op;
                        bool none     = Tools.Utils.BitmaskToBool(flags, 0x1);
                        bool gamma    = Tools.Utils.BitmaskToBool(flags, 0x1 << 1);
                        bool sigma    = Tools.Utils.BitmaskToBool(flags, 0x1 << 2);
                        bool band     = Tools.Utils.BitmaskToBool(flags, 0x1 << 3);
                        bool onecolor = Tools.Utils.BitmaskToBool(flags, 0x1 << 4);

                        if (gamma)
                        {
                            _writer.WriteElementString("a", "gamma", OpenXmlNamespaces.DrawingML, "");
                        }
                        if (band)
                        {
                            _writer.WriteStartElement("a", "shade", OpenXmlNamespaces.DrawingML);
                            _writer.WriteAttributeString("val", "37255");
                            _writer.WriteEndElement();
                        }
                        if (gamma)
                        {
                            _writer.WriteElementString("a", "invGamma", OpenXmlNamespaces.DrawingML, "");
                        }
                    }
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();
                }



                ////new colorval
                //_writer.WriteStartElement("a", "gs", OpenXmlNamespaces.DrawingML);
                //_writer.WriteAttributeString("pos", "100000");
                //_writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                //_writer.WriteAttributeString("val", colorval2);
                //if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBackOpacity))
                //{
                //    _writer.WriteStartElement("a", "alpha", OpenXmlNamespaces.DrawingML);
                //    _writer.WriteAttributeString("val", Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillBackOpacity].op / 65536 * 100000)).ToString()); //we need the percentage of the opacity (65536 means 100%)
                //    _writer.WriteEndElement();
                //}

                //_writer.WriteEndElement();
                //_writer.WriteEndElement();

                _writer.WriteEndElement();     //gsLst

                _writer.WriteStartElement("a", "lin", OpenXmlNamespaces.DrawingML);

                angle *= 60000;
                //if (angle > 5400000) angle = 5400000;

                _writer.WriteAttributeString("ang", angle.ToString());
                _writer.WriteAttributeString("scaled", "1");
                _writer.WriteEndElement();

                _writer.WriteEndElement();
                break;

            case 0x8:     //shadetitle
            case 0x9:     //background
                break;
            }
        }
Пример #30
0
        /// <summary>
        /// Insert a picture into a given xmlpath inside the document part
        /// </summary>
        /// <param name="xpathInsertionPoint">place where we are going to put the picture</param>
        /// <param name="pictureToInsert">picture to insert</param>
        /// <param name="name">name to use for inserted picture</param>
        public void Insert(string xpathInsertionPoint, Image pictureToInsert, string name)
        {
            XDocument           xmlMainDocument  = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart);
            ImagePart           picturePart      = null;
            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());

            namespaceManager.AddNamespace("w", mainns.NamespaceName);
            IEnumerable <XElement> insertionPoints = xmlMainDocument.XPathSelectElements(xpathInsertionPoint, namespaceManager);

            //make the insertion for each insertion point specified in the xpath query
            foreach (XElement insertionPoint in insertionPoints)
            {
                if (picturePart == null)
                {
                    //  Create the picture part in the package
                    picturePart = parentDocument.Document.MainDocumentPart.AddImagePart(GetImagePartType(pictureToInsert.RawFormat));
                }

                //  the pictures in the main document part goes in a very long xml, wich specifies the way the picture
                //  has to be placed using drawingXml.
                insertionPoint.AddAfterSelf(
                    new XElement(mainns + "p",
                                 new XElement(mainns + "r",
                                              new XElement(mainns + "drawing",
                                                           new XElement(wordprocessingDrawingns + "inline",
                                                                        new XElement(wordprocessingDrawingns + "extent",
                                                                                     new XAttribute("cx", pictureToInsert.Width * pixelsPerEmu),
                                                                                     new XAttribute("cy", pictureToInsert.Height * pixelsPerEmu)
                                                                                     ),
                                                                        new XElement(wordprocessingDrawingns + "docPr",
                                                                                     new XAttribute("name", name),
                                                                                     new XAttribute("id", "1")
                                                                                     ),
                                                                        new XElement(drawingmlMainns + "graphic",
                                                                                     new XAttribute(XNamespace.Xmlns + "a", drawingmlMainns.NamespaceName),
                                                                                     new XElement(drawingmlMainns + "graphicData",
                                                                                                  new XAttribute("uri", picturens.NamespaceName),
                                                                                                  new XElement(picturens + "pic",
                                                                                                               new XAttribute(XNamespace.Xmlns + "pic", picturens.NamespaceName),
                                                                                                               new XElement(picturens + "nvPicPr",
                                                                                                                            new XElement(picturens + "cNvPr",
                                                                                                                                         new XAttribute("id", "0"),
                                                                                                                                         new XAttribute("name", name)
                                                                                                                                         ),
                                                                                                                            new XElement(picturens + "cNvPicPr")
                                                                                                                            ),
                                                                                                               new XElement(picturens + "blipFill",
                                                                                                                            new XElement(drawingmlMainns + "blip",
                                                                                                                                         new XAttribute(relationshipns + "embed", parentPart.GetIdOfPart(picturePart))
                                                                                                                                         ),
                                                                                                                            new XElement(drawingmlMainns + "stretch",
                                                                                                                                         new XElement(drawingmlMainns + "fillRect")
                                                                                                                                         )
                                                                                                                            ),
                                                                                                               new XElement(picturens + "spPr",
                                                                                                                            new XElement(drawingmlMainns + "xfrm",
                                                                                                                                         new XElement(drawingmlMainns + "off",
                                                                                                                                                      new XAttribute("x", "0"),
                                                                                                                                                      new XAttribute("y", "0")
                                                                                                                                                      ),
                                                                                                                                         new XElement(drawingmlMainns + "ext",
                                                                                                                                                      new XAttribute("cx", pictureToInsert.Width * pixelsPerEmu),
                                                                                                                                                      new XAttribute("cy", pictureToInsert.Height * pixelsPerEmu)
                                                                                                                                                      )
                                                                                                                                         ),
                                                                                                                            new XElement(drawingmlMainns + "prstGeom",
                                                                                                                                         new XAttribute("prst", "rect")
                                                                                                                                         )
                                                                                                                            )
                                                                                                               )
                                                                                                  )
                                                                                     )
                                                                        )
                                                           )
                                              )
                                 )
                    );
            }
            if (picturePart != null)
            {
                Stream partStream = picturePart.GetStream(FileMode.Create, FileAccess.ReadWrite);
                pictureToInsert.Save(partStream, pictureToInsert.RawFormat);
            }
            else
            {
                throw new Exception("The xpath query did not return a valid location.");
            }
        }