Esempio n. 1
0
        /// <summary>
        /// Adds a ImagePart to the MainDocumentPart
        /// </summary>
        /// <param name="partType">The part type of the ImagePart</param>
        /// <return>The newly added part</return>
        public ImagePart AddImagePart(ImagePartType partType)
        {
            var contentType   = ImagePartTypeInfo.GetContentType(partType);
            var partExtension = ImagePartTypeInfo.GetTargetExtension(partType);

            OpenXmlPackage.PartExtensionProvider.MakeSurePartExtensionExist(contentType, partExtension);
            return(AddImagePart(contentType));
        }
        public void CreateSlides(List <string> imageFileNames,
                                 string newPresentation)
        {
            string  relId;
            SlideId slideId;

            uint currentSlideId = 256;

            string imageFileNameNoPath;

            long imageWidthEMU  = 0;
            long imageHeightEMU = 0;

            // Open the new presentation.
            using (PresentationDocument newDeck =
                       PresentationDocument.Open(newPresentation, true))
            {
                PresentationPart presentationPart = newDeck.PresentationPart;
                var slideMasterPart = presentationPart.SlideMasterParts.First();
                var slideLayoutPart = slideMasterPart.SlideLayoutParts.First();
                if (presentationPart.Presentation.SlideIdList == null)
                {
                    presentationPart.Presentation.SlideIdList = new SlideIdList();
                }
                foreach (string imageFileNameWithPath in imageFileNames)
                {
                    imageFileNameNoPath =
                        Path.GetFileNameWithoutExtension(imageFileNameWithPath);
                    relId = "rel" + currentSlideId;

                    ImagePartType imagePartType = ImagePartType.Png;
                    byte[]        imageBytes    = GetImageData(imageFileNameWithPath, ref imagePartType, ref imageWidthEMU, ref imageHeightEMU);
                    var           slidePart     = presentationPart.AddNewPart <SlidePart>(relId);
                    GenerateSlidePart(imageFileNameNoPath, imageFileNameNoPath, imageWidthEMU, imageHeightEMU).Save(slidePart);

                    // Add the relationship between the slide and the
                    // slide layout.
                    slidePart.AddPart <SlideLayoutPart>(slideLayoutPart);
                    var imagePart = slidePart.AddImagePart(ImagePartType.Jpeg, "relId12");
                    GenerateImagePart(imagePart, imageBytes);

                    // Add the new slide to the slide list.
                    slideId = new SlideId();
                    slideId.RelationshipId = relId;
                    slideId.Id             = currentSlideId;
                    presentationPart.Presentation.SlideIdList.Append(slideId);

                    // Increment the slide id;
                    currentSlideId++;
                }

                // Save the changes to the slide master part.
                slideMasterPart.SlideMaster.Save();

                // Save the changes to the new deck.
                presentationPart.Presentation.Save();
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Adds a new picture to the slide in order to re-use the picture later on.
        /// </summary>
        /// <param name="picture">The picture as a byte array.</param>
        /// <param name="contentType">The picture content type: image/png, image/jpeg...</param>
        /// <returns>The image part</returns>
        internal ImagePart AddPicture(byte[] picture, string contentType)
        {
            ImagePartType type = 0;

            switch (contentType)
            {
            case "image/bmp":
                type = ImagePartType.Bmp;
                break;

            case "image/emf":     // TODO
                type = ImagePartType.Emf;
                break;

            case "image/gif":     // TODO
                type = ImagePartType.Gif;
                break;

            case "image/ico":     // TODO
                type = ImagePartType.Icon;
                break;

            case "image/jpeg":
                type = ImagePartType.Jpeg;
                break;

            case "image/pcx":     // TODO
                type = ImagePartType.Pcx;
                break;

            case "image/png":
                type = ImagePartType.Png;
                break;

            case "image/tiff":     // TODO
                type = ImagePartType.Tiff;
                break;

            case "image/wmf":     // TODO
                type = ImagePartType.Wmf;
                break;
            }

            ImagePart imagePart = this.slidePart.AddImagePart(type);

            // FeedData() closes the stream and we cannot reuse it (ObjectDisposedException)
            // solution: copy the original stream to a MemoryStream
            using (MemoryStream stream = new MemoryStream(picture))
            {
                imagePart.FeedData(stream);
            }

            // No need to detect duplicated images
            // PowerPoint do it for us on the next manual save

            return(imagePart);
        }
Esempio n. 4
0
        private ImagePart AddPicture(byte[] picture, string contentType, SlidePart diapositiva)
        {
            ImagePartType type = 0;

            switch (contentType)
            {
            case "image/bmp":
                type = ImagePartType.Bmp;
                break;

            case "image/emf":
                type = ImagePartType.Emf;
                break;

            case "image/gif":
                type = ImagePartType.Gif;
                break;

            case "image/ico":
                type = ImagePartType.Icon;
                break;

            case "image/jpeg":
                type = ImagePartType.Jpeg;
                break;

            case "image/pcx":
                type = ImagePartType.Pcx;
                break;

            case "image/png":
                type = ImagePartType.Png;
                break;

            case "image/tiff":
                type = ImagePartType.Tiff;
                break;

            case "image/wmf":
                type = ImagePartType.Wmf;
                break;
            }

            ImagePart imagePart = diapositiva.AddImagePart(type);

            // FeedData() closes the stream and we cannot reuse it (ObjectDisposedException)
            // solution: copy the original stream to a MemoryStream
            using (MemoryStream stream = new MemoryStream(picture))
            {
                imagePart.FeedData(stream);
            }

            return(imagePart);
        }
        /// <summary>
        /// Inspect the response headers of a web request and decode the mime type if provided
        /// </summary>
        /// <returns>Returns the extension of the image if provideds.</returns>
        private static bool TryInspectMimeType(string contentType, out ImagePartType type)
        {
            // can be null when the protocol used doesn't allow response headers
            if (contentType != null &&
                knownContentType.TryGetValue(contentType, out type))
            {
                return(true);
            }

            type = default;
            return(false);
        }
        /// <summary>
        /// Add a background picture to the currently selected worksheet given a picture's data in a byte array.
        /// If there's an existing background picture, that will be deleted first.
        /// </summary>
        /// <param name="PictureByteData">The picture's data in a byte array.</param>
        /// <param name="PictureType">The image type of the picture.</param>
        public void AddBackgroundPicture(byte[] PictureByteData, ImagePartType PictureType)
        {
            // delete any background picture first
            this.DeleteBackgroundPicture();

            slws.BackgroundPictureDataIsInFile = false;
            slws.BackgroundPictureByteData = new byte[PictureByteData.Length];
            for (int i = 0; i < PictureByteData.Length; ++i)
            {
                slws.BackgroundPictureByteData[i] = PictureByteData[i];
            }
            slws.BackgroundPictureImagePartType = PictureType;
        }
Esempio n. 7
0
        public static void CreateImageRid(ReportImage reportImage, MainDocumentPart objMainDocumentPart)
        {
            ImagePartType imagetype  = ImagePartType.Jpeg;
            FileInfo      newImg     = new FileInfo(reportImage.Value);
            ImagePart     newImgPart = objMainDocumentPart.AddImagePart(imagetype);

            //插入图片数据到Word里去.
            using (FileStream stream = newImg.OpenRead())
            {
                newImgPart.FeedData(stream);
            }
            //Word返回给我们插入数据的标识符.
            reportImage.RId = objMainDocumentPart.GetIdOfPart(newImgPart);
        }
        private byte[] GetImageData(string imageFilePath,
                                    ref ImagePartType imagePartType, ref long imageWidthEMU,
                                    ref long imageHeightEMU)
        {
            byte[] imageFileBytes;
            using (FileStream fsImageFile = File.OpenRead(imageFilePath))
            {
                imageFileBytes = new byte[fsImageFile.Length];
                fsImageFile.Read(imageFileBytes, 0, imageFileBytes.Length);

                using (Bitmap imageFile = new Bitmap(fsImageFile))
                {
                    if (imageFile.RawFormat.Guid == ImageFormat.Bmp.Guid)
                    {
                        imagePartType = ImagePartType.Bmp;
                    }
                    else if (imageFile.RawFormat.Guid == ImageFormat.Gif.Guid)
                    {
                        imagePartType = ImagePartType.Gif;
                    }
                    else if (imageFile.RawFormat.Guid == ImageFormat.Jpeg.Guid)
                    {
                        imagePartType = ImagePartType.Jpeg;
                    }
                    else if (imageFile.RawFormat.Guid == ImageFormat.Png.Guid)
                    {
                        imagePartType = ImagePartType.Png;
                    }
                    else if (imageFile.RawFormat.Guid == ImageFormat.Tiff.Guid)
                    {
                        imagePartType = ImagePartType.Tiff;
                    }
                    else
                    {
                        throw new ArgumentException(
                                  "Unsupported image file format: " + imageFilePath);
                    }

                    imageWidthEMU =
                        (long)
                        ((imageFile.Width / imageFile.HorizontalResolution) * 914400L);

                    imageHeightEMU =
                        (long)
                        ((imageFile.Height / imageFile.VerticalResolution) * 914400L);
                }
            }

            return(imageFileBytes);
        }
Esempio n. 9
0
        private void InsertPicture(MainDocumentPart mainPart, Paragraph paragraph, string fileBase64)
        {
            var           bytes     = Convert.FromBase64String(fileBase64);
            ImagePartType type      = CheckImageType(bytes);
            ImagePart     imagePart = mainPart.AddImagePart(type);

            using (MemoryStream stream = new MemoryStream(bytes)) {
                imagePart.FeedData(stream);
            }
            var element = CreateDrawing(mainPart.GetIdOfPart(imagePart));

            var run = new Run(element);

            paragraph.AppendChild(run);
        }
Esempio n. 10
0
        internal static string GetContentType(ImagePartType imageType)
        {
            switch (imageType)
            {
            case ImagePartType.Bmp:
                return("image/bmp");

            case ImagePartType.Gif:
                return("image/gif");

            case ImagePartType.Png:
                return("image/png");

            case ImagePartType.Tiff:
                return("image/tiff");

            //case ImagePartType.Xbm:
            //    return "image/xbm";
            case ImagePartType.Icon:
                return("image/x-icon");

            case ImagePartType.Pcx:
                return("image/x-pcx");

            //case ImagePartType.Pcz:
            //    return "image/x-pcz";

            //case ImagePartType.Pict:
            //    return "image/pict";
            case ImagePartType.Jpeg:
                return("image/jpeg");

            case ImagePartType.Emf:
                return("image/x-emf");

            case ImagePartType.Wmf:
                return("image/x-wmf");

            case ImagePartType.Svg:
                return("image/svg+xml");

            default:
                throw new ArgumentOutOfRangeException(nameof(imageType));
            }
        }
Esempio n. 11
0
        internal static string GetTargetExtension(ImagePartType imageType)
        {
            switch (imageType)
            {
            case ImagePartType.Bmp:
                return(".bmp");

            case ImagePartType.Gif:
                return(".gif");

            case ImagePartType.Png:
                return(".png");

            case ImagePartType.Tiff:
                return(".tiff");

            //case ImagePartType.Xbm:
            //    return ".xbm";
            case ImagePartType.Icon:
                return(".ico");

            case ImagePartType.Pcx:
                return(".pcx");

            //case ImagePartType.Pcz:
            //    return ".pcz";

            //case ImagePartType.Pict:
            //    return ".pict";
            case ImagePartType.Jpeg:
                return(".jpg");

            case ImagePartType.Emf:
                return(".emf");

            case ImagePartType.Wmf:
                return(".wmf");

            case ImagePartType.Svg:
                return(".svg");

            default:
                return(".image");
            }
        }
Esempio n. 12
0
        public static Drawing CreateDrawing(
            WordprocessingDocument package,
            Stream imageStream,
            ImagePartType imagePartType,
            int percentage, long maxWidthInEmus)
        {
            var imagePart = package.MainDocumentPart.AddImagePart(imagePartType);
            var img       = new BitmapImage();

            using (imageStream)
            {
                img.BeginInit();
                img.StreamSource = imageStream;
                img.EndInit();

                imageStream.Seek(0, SeekOrigin.Begin);
                imagePart.FeedData(imageStream);
                // imagePart will also dispose the stream.
            }

            var       widthPx     = img.PixelWidth;
            var       heightPx    = img.PixelHeight;
            var       horzRezDpi  = img.DpiX;
            var       vertRezDpi  = img.DpiY;
            const int emusPerInch = 914400;
            var       widthEmus   = (long)(widthPx / horzRezDpi * emusPerInch);
            var       heightEmus  = (long)(heightPx / vertRezDpi * emusPerInch);

            if (widthEmus > maxWidthInEmus)
            {
                var ratio = heightEmus * 1.0m / widthEmus;
                widthEmus  = maxWidthInEmus;
                heightEmus = (long)(widthEmus * ratio);
            }

            if (percentage != 100)
            {
                widthEmus  = widthEmus * percentage / 100;
                heightEmus = heightEmus * percentage / 100;
            }

            var drawing = GetDrawing(package.MainDocumentPart.GetIdOfPart(imagePart), widthEmus, heightEmus);

            return(drawing);
        }
Esempio n. 13
0
        public static Drawing CreateDrawing(
            WordprocessingDocument package,
            Stream imageStream,
            ImagePartType imagePartType,
            int percentage, long maxWidthInEmus)
        {
            var imagePart = package.MainDocumentPart.AddImagePart(imagePartType);

            var img = Image.FromStream(imageStream);

            var widthPx    = img.Width;
            var heightPx   = img.Height;
            var horzRezDpi = img.HorizontalResolution;
            var vertRezDpi = img.VerticalResolution;

            img.Dispose();

            using (imageStream)
            {
                imageStream.Seek(0, SeekOrigin.Begin);
                imagePart.FeedData(imageStream);
                // imagePart will also dispose the stream.
            }

            const long emusPerInch = 914400; // this must be a long otherwise the multiplication in the next line could lead to an overflow and negative number
            var        widthEmus   = (long)(widthPx * emusPerInch / horzRezDpi);
            var        heightEmus  = (long)(heightPx * emusPerInch / vertRezDpi);

            if (widthEmus > maxWidthInEmus)
            {
                var ratio = heightEmus * 1.0m / widthEmus;
                widthEmus  = maxWidthInEmus;
                heightEmus = (long)(widthEmus * ratio);
            }

            if (percentage != 100)
            {
                widthEmus  = widthEmus * percentage / 100;
                heightEmus = heightEmus * percentage / 100;
            }

            var drawing = GetDrawing(package.MainDocumentPart.GetIdOfPart(imagePart), widthEmus, heightEmus);

            return(drawing);
        }
Esempio n. 14
0
        /// <summary>
        /// Gets the OpenXml ImagePartType associated to an image.
        /// </summary>
        private static bool TryGuessTypeFromUri(Uri uri, out ImagePartType type)
        {
            string extension = Path.GetExtension(uri.IsAbsoluteUri ? uri.Segments[uri.Segments.Length - 1] : uri.OriginalString);

            if (knownExtensions.TryGetValue(extension, out type))
            {
                return(true);
            }

            // extension not recognized, try with checking the query string. Expecting to resolve something like:
            // ./image.axd?picture=img1.jpg
            extension = Path.GetExtension(uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.ToString());
            if (knownExtensions.TryGetValue(extension, out type))
            {
                return(true);
            }

            return(false);
        }
Esempio n. 15
0
        /// <summary>
        /// Gets the OpenXml ImagePartType associated to an image.
        /// </summary>
        private static bool TryGuessTypeFromStream(Stream stream, out ImagePartType type)
        {
            if (ImageHeader.TryDetectFileType(stream, out ImageHeader.FileType guessType))
            {
                switch (guessType)
                {
                case ImageHeader.FileType.Bitmap: type = ImagePartType.Bmp; return(true);

                case ImageHeader.FileType.Emf: type = ImagePartType.Emf; return(true);

                case ImageHeader.FileType.Gif: type = ImagePartType.Gif; return(true);

                case ImageHeader.FileType.Jpeg: type = ImagePartType.Jpeg; return(true);

                case ImageHeader.FileType.Png: type = ImagePartType.Png; return(true);
                }
            }
            type = ImagePartType.Bmp;
            return(false);
        }
Esempio n. 16
0
        public static byte[] GetImageData(string imageFilePath, ref ImagePartType imagePartType)
        {
            byte[] imageFileBytes;

            using (FileStream fsImageFile = File.OpenRead(HttpContext.Current.Server.MapPath(imageFilePath)))
            {
                imageFileBytes = new byte[fsImageFile.Length];
                fsImageFile.Read(imageFileBytes, 0, imageFileBytes.Length);

                using (Bitmap imageFile = new Bitmap(fsImageFile))
                {
                    if (imageFile.RawFormat.Guid == ImageFormat.Bmp.Guid)
                    {
                        imagePartType = ImagePartType.Bmp;
                    }
                    else if (imageFile.RawFormat.Guid == ImageFormat.Gif.Guid)
                    {
                        imagePartType = ImagePartType.Gif;
                    }
                    else if (imageFile.RawFormat.Guid == ImageFormat.Jpeg.Guid)
                    {
                        imagePartType = ImagePartType.Jpeg;
                    }
                    else if (imageFile.RawFormat.Guid == ImageFormat.Png.Guid)
                    {
                        imagePartType = ImagePartType.Png;
                    }
                    else if (imageFile.RawFormat.Guid == ImageFormat.Tiff.Guid)
                    {
                        imagePartType = ImagePartType.Tiff;
                    }
                    else
                    {
                        throw new ArgumentException(
                                  "Unsupported image file format: " + imageFilePath);
                    }
                }
            }

            return(imageFileBytes);
        }
Esempio n. 17
0
 /// <summary>
 /// Adds an image element into the body of the given word document
 /// </summary>
 /// <param name="word">Word document reference</param>
 /// <param name="stream">Stream containing the image data</param>
 /// <param name="imageType">Type of image</param>
 /// <returns>True or False</returns>
 public static bool AddImage(this WordprocessingDocument word, Stream stream, ImagePartType imageType = ImagePartType.Jpeg)
 {
     if (word.IsNotValid() || stream.IsNotValid())
     {
         return(false);
     }
     try
     {
         MainDocumentPart main      = word.MainDocumentPart;
         ImagePart        imagePart = main.AddImagePart(imageType);
         using (Stream s = stream)
         {
             imagePart.FeedData(s);
         }
         AddImageToBody(word, main.GetIdOfPart(imagePart));
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Esempio n. 18
0
        public static ImageInfo.Type GetImageInfoType(ImagePartType imagePartType)
        {
            switch (imagePartType)
            {
            case ImagePartType.Bmp:
                return(ImageInfo.Type.Bmp);

            case ImagePartType.Gif:
                return(ImageInfo.Type.Gif);

            case ImagePartType.Jpeg:
                return(ImageInfo.Type.Jpeg);

            case ImagePartType.Png:
                return(ImageInfo.Type.Png);

            case ImagePartType.Tiff:
                return(ImageInfo.Type.Tiff);
            }

            return(ImageInfo.Type.Unknown);
        }
Esempio n. 19
0
    private static ImageFormat ToImageFormat(ImagePartType imagePartType)
    {
        switch (imagePartType)
        {
        case ImagePartType.Bmp: return(ImageFormat.Bmp);

        case ImagePartType.Emf: return(ImageFormat.Emf);

        case ImagePartType.Gif: return(ImageFormat.Gif);

        case ImagePartType.Icon: return(ImageFormat.Icon);

        case ImagePartType.Jpeg: return(ImageFormat.Jpeg);

        case ImagePartType.Png: return(ImageFormat.Png);

        case ImagePartType.Tiff: return(ImageFormat.Tiff);

        case ImagePartType.Wmf: return(ImageFormat.Wmf);
        }

        throw new InvalidOperationException("Unexpected {0}".FormatWith(imagePartType));
    }
Esempio n. 20
0
        private static ImagePart AddImagePart(OpenXmlPart documentPart, ImagePartType imagePartType)
        {
            var mainPart = documentPart as MainDocumentPart;

            if (mainPart != null)
            {
                return(mainPart.AddImagePart(imagePartType));
            }
            var headerPart = documentPart as HeaderPart;

            if (headerPart != null)
            {
                return(headerPart.AddImagePart(imagePartType));
            }

            var footerPart = documentPart as FooterPart;

            if (footerPart != null)
            {
                return(footerPart.AddImagePart(imagePartType));
            }

            throw new ArgumentException("'documentPart' is of type not supported by this function");
        }
Esempio n. 21
0
    public static bool AvoidAdaptSize = false; //Jpeg compression creates different images in TeamCity

    /// <param name="titleOrDescription">
    /// Replaces a placeholder-image with the provided image by comparing title/description
    ///
    /// Word Image -> Right Click -> Format Picture -> Alt Text -> Title
    /// </param>
    public static void ReplaceImage(this WordprocessingDocument doc, string titleOrDescription, Bitmap bitmap, string newImagePartId, bool adaptSize = false, ImagePartType imagePartType = ImagePartType.Png)
    {
        var blip = doc.FindBlip(titleOrDescription);

        if (adaptSize && AvoidAdaptSize == false)
        {
            var size = doc.GetBlipBitmapSize(blip);
            bitmap = ImageResizer.Resize(bitmap, size.Width, size.Height);
        }

        doc.ReplaceBlipContent(blip, bitmap, newImagePartId, imagePartType);
    }
Esempio n. 22
0
    static ImagePart CreateImagePart(this WordprocessingDocument doc, Bitmap bitmap, string id, ImagePartType imagePartType = ImagePartType.Png)
    {
        ImagePart img = doc.MainDocumentPart !.AddImagePart(imagePartType, id);

        using (var ms = new MemoryStream())
        {
            bitmap.Save(ms, ToImageFormat(imagePartType));
            ms.Seek(0, SeekOrigin.Begin);
            img.FeedData(ms);
        }
        return(img);
    }
Esempio n. 23
0
 /// <summary>
 /// Permet d'ajouter le type d'une image dans le document de type OpenXmlPart
 /// </summary>
 /// <param name="type">Type de l'image</param>
 /// <returns></returns>
 private ImagePart AddImagePart(ImagePartType type)
 {
     return(wdMainDocumentPart.AddImagePart(type));
 }
Esempio n. 24
0
        internal static string GetTargetExtension(ImagePartType imageType)
        {
            switch (imageType)
            {
                case ImagePartType.Bmp:
                    return ".bmp";

                case ImagePartType.Gif:
                    return ".gif";

                case ImagePartType.Png:
                    return ".png";

                case ImagePartType.Tiff:
                    return ".tiff";

                //case ImagePartType.Xbm:
                //    return ".xbm";

                case ImagePartType.Icon:
                    return ".ico";

                case ImagePartType.Pcx:
                    return ".pcx";

                //case ImagePartType.Pcz:
                //    return ".pcz";

                //case ImagePartType.Pict:
                //    return ".pict";

                case ImagePartType.Jpeg:
                    return ".jpg";

                case ImagePartType.Emf:
                    return ".emf";

                case ImagePartType.Wmf:
                    return ".wmf";

                default:
                    return ".image";
            }
        }
        private void ProcessPicture(string cellText)
        {
            if (HasPictureDefinition(cellText))
            {
                int    picDefStart   = cellText.ToLower().IndexOf(@"<pic");
                int    picDefEnd     = cellText.ToLower().IndexOf(@"/>", picDefStart);
                string picDefinition = cellText.Substring(picDefStart, picDefEnd - picDefStart);
                picDefinition = picDefinition.Replace(@"<pic", "").Replace(@"/>", "");
                string[] picAtts = picDefinition.Split(new char[] { ',' }, picDefinition.Length);
                var      picItem = new ReportPictureItem();
                picItem.PictureRowPosition = this.CurrentRow;
                picItem.PictureColPosition = this.CurrentColumn;
                picItem.AddToColPosition   = 0.0;
                picItem.AddToRowPosition   = 0.0;
                string picreftype = "";
                string picref     = "";

                foreach (string picAtt in picAtts)
                {
                    try
                    {
                        if (picAtt.ToLower().Replace(" ", "").StartsWith("name="))
                        {
                            picItem.PictureName = picAtt.ToLower().Replace(" ", "").Replace("name=", "");
                        }
                        if (picAtt.ToLower().Replace(" ", "").StartsWith("heightemu="))
                        {
                            picItem.PictureHeightEMU = long.Parse(picAtt.ToLower().Replace(" ", "").Replace("heightemu=", ""));
                        }
                        if (picAtt.ToLower().Replace(" ", "").StartsWith("widthemu="))
                        {
                            picItem.PictureWidthEMU = long.Parse(picAtt.ToLower().Replace(" ", "").Replace("widthemu=", ""));
                        }
                        if (picAtt.ToLower().Replace(" ", "").StartsWith("heightcm="))
                        {
                            picItem.PictureHeightEMU = long.Parse((double.Parse(picAtt.ToLower().Replace(" ", "").Replace("heightcm=", "")) * 360000).ToString());
                        }
                        if (picAtt.ToLower().Replace(" ", "").StartsWith("widthcm="))
                        {
                            picItem.PictureWidthEMU = long.Parse((double.Parse(picAtt.ToLower().Replace(" ", "").Replace("widthcm=", "")) * 360000).ToString());
                        }
                        if (picAtt.ToLower().Replace(" ", "").StartsWith("heightinch="))
                        {
                            picItem.PictureHeightEMU = long.Parse((double.Parse(picAtt.ToLower().Replace(" ", "").Replace("heightinch=", "")) * 914400).ToString());
                        }
                        if (picAtt.ToLower().Replace(" ", "").StartsWith("widthinch="))
                        {
                            picItem.PictureWidthEMU = long.Parse((double.Parse(picAtt.ToLower().Replace(" ", "").Replace("widthinch=", "")) * 914400).ToString());
                        }
                        if (picAtt.ToLower().Replace(" ", "").StartsWith("addtocolpos="))
                        {
                            picItem.AddToColPosition = double.Parse(picAtt.ToLower().Replace(" ", "").Replace("addtocolpos=", "").ToString());
                        }
                        if (picAtt.ToLower().Replace(" ", "").StartsWith("addtorowpos="))
                        {
                            picItem.AddToRowPosition = double.Parse(picAtt.ToLower().Replace(" ", "").Replace("addtorowpos=", "").ToString());
                        }
                        if (picAtt.ToLower().Replace(" ", "").StartsWith("ref="))
                        {
                            var temp     = picAtt.Replace(" ", "");
                            int startInd = picAtt.ToLower().Replace(" ", "").IndexOf("ref=");

                            temp = temp.Remove(startInd, 4);

                            picref = temp;
                        }
                        if (picAtt.ToLower().Replace(" ", "").StartsWith("reftype="))
                        {
                            picreftype = picAtt.ToLower().Replace(" ", "").Replace("reftype=", "");
                        }
                        if (picAtt.ToLower().Replace(" ", "").StartsWith("format="))
                        {
                            if (picAtt.ToLower().Replace(" ", "").EndsWith("jpeg") ||
                                (picAtt.ToLower().Replace(" ", "").EndsWith("jpg")))
                            {
                                picItem.PictureFormat = ImagePartType.Jpeg;
                            }
                            else if (picAtt.ToLower().Replace(" ", "").EndsWith("wmf"))
                            {
                                picItem.PictureFormat = ImagePartType.Wmf;
                            }
                            else if (picAtt.ToLower().Replace(" ", "").EndsWith("tif") ||
                                     picAtt.ToLower().Replace(" ", "").EndsWith("tiff"))
                            {
                                picItem.PictureFormat = ImagePartType.Tiff;
                            }
                            else if (picAtt.ToLower().Replace(" ", "").EndsWith("png"))
                            {
                                picItem.PictureFormat = ImagePartType.Png;
                            }
                            else if (picAtt.ToLower().Replace(" ", "").EndsWith("pcx"))
                            {
                                picItem.PictureFormat = ImagePartType.Pcx;
                            }
                            else if (picAtt.ToLower().Replace(" ", "").EndsWith("ico"))
                            {
                                picItem.PictureFormat = ImagePartType.Icon;
                            }
                            else if (picAtt.ToLower().Replace(" ", "").EndsWith("gif"))
                            {
                                picItem.PictureFormat = ImagePartType.Gif;
                            }
                            else if (picAtt.ToLower().Replace(" ", "").EndsWith("emf"))
                            {
                                picItem.PictureFormat = ImagePartType.Emf;
                            }
                            else
                            {
                                NotifyReportLogEvent("Picture format is not supported.");
                                return;
                            }
                        }
                    }
                    catch
                    {
                        NotifyReportLogEvent("Was not able to process picture attribute. " + picAtt);
                        return;
                    }
                }
                if (!String.IsNullOrEmpty(picreftype) && !String.IsNullOrEmpty(picref))
                {
                    if (picreftype.ToLower().Replace(" ", "") == PictureSourceTypeEnum.fileref.ToString() || picreftype.ToLower().Replace(" ", "") == "file")
                    {
                        if (File.Exists(picref))
                        {
                            if (picref.ToLower().Replace(" ", "").EndsWith("jpeg") ||
                                picref.ToLower().Replace(" ", "").EndsWith("jpg"))
                            {
                                picItem.PictureFormat = ImagePartType.Jpeg;
                            }
                            if (picref.ToLower().Replace(" ", "").EndsWith("wmf"))
                            {
                                picItem.PictureFormat = ImagePartType.Wmf;
                            }
                            if (picref.ToLower().Replace(" ", "").EndsWith("tif") ||
                                picref.ToLower().Replace(" ", "").EndsWith("tiff"))
                            {
                                picItem.PictureFormat = ImagePartType.Tiff;
                            }
                            if (picref.ToLower().Replace(" ", "").EndsWith("png"))
                            {
                                picItem.PictureFormat = ImagePartType.Png;
                            }
                            if (picref.ToLower().Replace(" ", "").EndsWith("pcx"))
                            {
                                picItem.PictureFormat = ImagePartType.Pcx;
                            }
                            if (picref.ToLower().Replace(" ", "").EndsWith("ico"))
                            {
                                picItem.PictureFormat = ImagePartType.Icon;
                            }
                            if (picref.ToLower().Replace(" ", "").EndsWith("gif"))
                            {
                                picItem.PictureFormat = ImagePartType.Gif;
                            }
                            if (picref.ToLower().Replace(" ", "").EndsWith("emf"))
                            {
                                picItem.PictureFormat = ImagePartType.Emf;
                            }
                            if (picItem.PictureFormat != null)
                            {
                                picItem.PicData = File.ReadAllBytes(picref);
                            }
                            else
                            {
                                NotifyReportLogEvent("Picture format is not supported.");
                                return;
                            }
                        }
                        else
                        {
                            NotifyReportLogEvent("Picture referenced file not found : " + picref);
                        }
                    }
                    if (picreftype.ToLower().Replace(" ", "") == PictureSourceTypeEnum.webref.ToString() || picreftype.ToLower() == "web")
                    {
                        ImagePartType imagePartType = ImagePartType.Bmp;
                        if (picref.ToLower().Replace(" ", "").EndsWith("jpeg") ||
                            picref.ToLower().Replace(" ", "").EndsWith("jpg"))
                        {
                            picItem.PictureFormat = ImagePartType.Jpeg;
                        }
                        if (picref.ToLower().Replace(" ", "").EndsWith("wmf"))
                        {
                            picItem.PictureFormat = ImagePartType.Wmf;
                        }
                        if (picref.ToLower().Replace(" ", "").EndsWith("tif") ||
                            picref.ToLower().Replace(" ", "").EndsWith("tiff"))
                        {
                            picItem.PictureFormat = ImagePartType.Tiff;
                        }
                        if (picref.ToLower().Replace(" ", "").EndsWith("png"))
                        {
                            picItem.PictureFormat = ImagePartType.Png;
                        }
                        if (picref.ToLower().Replace(" ", "").EndsWith("pcx"))
                        {
                            picItem.PictureFormat = ImagePartType.Pcx;
                        }
                        if (picref.ToLower().Replace(" ", "").EndsWith("ico"))
                        {
                            picItem.PictureFormat = ImagePartType.Icon;
                        }
                        if (picref.ToLower().Replace(" ", "").EndsWith("gif"))
                        {
                            picItem.PictureFormat = ImagePartType.Gif;
                        }
                        if (picref.ToLower().Replace(" ", "").EndsWith("emf"))
                        {
                            picItem.PictureFormat = ImagePartType.Emf;
                        }
                        if (picItem.PictureFormat != null)
                        {
                            WebClient client = new WebClient();
                            picItem.PicData = client.DownloadData(picref);
                        }
                        else
                        {
                            NotifyReportLogEvent("Picture format is not supported.");
                            return;
                        }
                    }
                    if (picreftype.ToLower() == PictureSourceTypeEnum.prop.ToString() || picreftype.ToLower() == "property" || picreftype.ToLower() == "var" || picreftype.ToLower() == "variable")
                    {
                        try
                        {
                            bool propFound = false;
                            foreach (var prop in this._reportModelData.GetType().GetProperties())
                            {
                                if (prop.Name.Trim() == picref.Trim())
                                {
                                    picItem.PicData =
                                        (byte[])prop.GetValue(this._reportModelData, null);
                                    propFound = true;
                                    break;
                                }
                            }
                            if (!propFound)
                            {
                                NotifyReportLogEvent("Property with the name : " + picref + "was not found");
                            }
                        }
                        catch
                        {
                            NotifyReportLogEvent("Was not able to process property : " + picref);
                            return;
                        }
                    }
                }

                this.ReportPictures.Add(picItem);
            }
        }
Esempio n. 26
0
    private static byte[] GetImageData(string imageFilePath, ref ImagePartType imagePartType, ref long imageWidthEMU, ref long imageHeightEMU)
    {
        byte[] imageFileBytes;

        // Open a stream on the image file and read it's contents. The
        // following code will generate an exception if an invalid file
        // name is passed.
        using (FileStream fsImageFile = File.OpenRead(imageFilePath))
        {
            imageFileBytes = new byte[fsImageFile.Length];
            fsImageFile.Read(imageFileBytes, 0, imageFileBytes.Length);

            Bitmap imageFile = new Bitmap(fsImageFile);

            // Determine the format of the image file.
            // This sample code supports working with the following types of image files:
            //
            // Bitmap (BMP)
            // Graphics Interchange Format (GIF)
            // Joint Photographic Experts Group (JPG, JPEG)
            // Portable Network Graphics (PNG)
            // Tagged Image File Format (TIFF)

            if (imageFile.RawFormat.Guid == ImageFormat.Bmp.Guid)
            {
                imagePartType = ImagePartType.Bmp;
            }
            else if (imageFile.RawFormat.Guid == ImageFormat.Gif.Guid)
            {
                imagePartType = ImagePartType.Gif;
            }
            else if (imageFile.RawFormat.Guid == ImageFormat.Jpeg.Guid)
            {
                imagePartType = ImagePartType.Jpeg;
            }
            else if (imageFile.RawFormat.Guid == ImageFormat.Png.Guid)
            {
                imagePartType = ImagePartType.Png;
            }
            else if (imageFile.RawFormat.Guid == ImageFormat.Tiff.Guid)
            {
                imagePartType = ImagePartType.Tiff;
            }
            else
            {
                throw new ArgumentException("Unsupported image file format: " + imageFilePath);
            }

            if (imageFile.Width > 1024)
            {
                Size size = new Size(1024, (imageFile.Height * imageFile.Width) / 1024);
                imageFile = Utils.ResizeImage(imageFile, size);
            }
            if (imageFile.Height > 768)
            {
                Size size = new Size((imageFile.Height * imageFile.Width) / 768, 768);
                imageFile = Utils.ResizeImage(imageFile, size);
            }

            // Get the dimensions of the image in English Metric Units (EMU)
            // for use when adding the markup for the image to the slide.
            imageWidthEMU =
                (long)((imageFile.Width / imageFile.HorizontalResolution) * 914400L);
            imageHeightEMU =
                (long)((imageFile.Height / imageFile.VerticalResolution) * 914400L);
        }

        return(imageFileBytes);
    }
Esempio n. 27
0
        private void InitialisePicture()
        {
            // should be true once we get *everyone* to stop using those confoundedly
            // hard to understand EMUs and absolute positionings...
            UseEasyPositioning = false;
            TopPosition = 0;
            LeftPosition = 0;

            UseRelativePositioning = true;
            AnchorRowIndex = 1;
            AnchorColumnIndex = 1;
            OffsetX = 0;
            OffsetY = 0;
            WidthInEMU = 0;
            HeightInEMU = 0;
            WidthInPixels = 0;
            HeightInPixels = 0;
            fHorizontalResolutionRatio = 1;
            fVerticalResolutionRatio = 1;

            this.bLockWithSheet = true;
            this.bPrintWithSheet = true;
            this.vCompressionState = A.BlipCompressionValues.Print;
            this.decBrightness = 0;
            this.decContrast = 0;
            //this.decRotationAngle = 0;

            this.vPictureShape = A.ShapeTypeValues.Rectangle;

            this.FillType = SLPictureFillType.None;
            this.FillClassInnerXml = string.Empty;

            this.HasOutline = false;
            this.PictureOutline = new A.Outline();
            this.HasOutlineFill = false;
            this.PictureOutlineFill = new A.SolidFill();

            this.HasGlow = false;
            this.GlowRadius = 0;
            this.GlowColorInnerXml = string.Empty;

            this.HasInnerShadow = false;
            this.PictureInnerShadow = new A.InnerShadow();
            this.HasOuterShadow = false;
            this.PictureOuterShadow = new A.OuterShadow();

            this.HasReflection = false;
            this.ReflectionBlurRadius = 0;
            this.ReflectionStartOpacity = 100000;
            this.ReflectionStartPosition = 0;
            this.ReflectionEndAlpha = 0;
            this.ReflectionEndPosition = 100000;
            this.ReflectionDistance = 0;
            this.ReflectionDirection = 0;
            this.ReflectionFadeDirection = 5400000;
            this.ReflectionHorizontalRatio = 100000;
            this.ReflectionVerticalRatio = 100000;
            this.ReflectionHorizontalSkew = 0;
            this.ReflectionVerticalSkew = 0;
            this.ReflectionAlignment = A.RectangleAlignmentValues.Bottom;
            this.ReflectionRotateWithShape = true;

            this.HasSoftEdge = false;
            this.SoftEdgeRadius = 0;

            this.HasScene3D = false;

            this.CameraLatitude = 0;
            this.CameraLongitude = 0;
            this.CameraRevolution = 0;
            this.CameraPreset = A.PresetCameraValues.OrthographicFront;
            this.CameraFieldOfView = 0;
            this.CameraZoom = 0;

            this.LightRigLatitude = 0;
            this.LightRigLongitude = 0;
            this.LightRigRevolution = 0;
            this.LightRigType = A.LightRigValues.ThreePoints;
            this.LightRigDirection = A.LightRigDirectionValues.Top;

            //this.HasBackdrop = false;
            //this.BackdropAnchorX = 0;
            //this.BackdropAnchorY = 0;
            //this.BackdropAnchorZ = 0;
            //this.BackdropNormalDx = 0;
            //this.BackdropNormalDy = 0;
            //this.BackdropNormalDz = 0;
            //this.BackdropUpVectorDx = 0;
            //this.BackdropUpVectorDy = 0;
            //this.BackdropUpVectorDz = 0;

            this.HasBevelTop = false;
            this.BevelTopPreset = A.BevelPresetValues.Circle;
            this.BevelTopWidth = 76200;
            this.BevelTopHeight = 76200;

            this.HasBevelBottom = false;
            this.BevelBottomPreset = A.BevelPresetValues.Circle;
            this.BevelBottomWidth = 76200;
            this.BevelBottomHeight = 76200;

            this.HasExtrusion = false;
            this.ExtrusionHeight = 0;
            this.ExtrusionColorInnerXml = string.Empty;

            this.HasContour = false;
            this.ContourWidth = 0;
            this.ContourColorInnerXml = string.Empty;

            this.HasMaterialType = false;
            this.MaterialType = A.PresetMaterialTypeValues.WarmMatte;

            this.HasZDistance = false;
            this.ZDistance = 0;

            this.HasUri = false;
            this.HyperlinkUri = string.Empty;
            this.HyperlinkUriKind = UriKind.Absolute;
            this.IsHyperlinkExternal = true;

            this.DataIsInFile = true;
            this.PictureFileName = string.Empty;
            this.PictureByteData = new byte[1];
            this.PictureImagePartType = ImagePartType.Bmp;
        }
Esempio n. 28
0
        /// <summary>
        /// Initializes an instance of SLPicture given a picture's data in a byte array, and the targeted computer's horizontal and vertical resolution. This scales the picture according to how it will be displayed on the targeted computer screen.
        /// </summary>
        /// <param name="PictureByteData">The picture's data in a byte array.</param>
        /// <param name="PictureType">The image type of the picture.</param>
        /// <param name="TargetHorizontalResolution">The targeted computer's horizontal resolution (DPI).</param>
        /// <param name="TargetVerticalResolution">The targeted computer's vertical resolution (DPI).</param>
        public SLPicture(byte[] PictureByteData, ImagePartType PictureType, float TargetHorizontalResolution, float TargetVerticalResolution)
        {
            InitialisePicture();

            DataIsInFile = false;
            this.PictureByteData = new byte[PictureByteData.Length];
            for (int i = 0; i < PictureByteData.Length; ++i)
            {
                this.PictureByteData[i] = PictureByteData[i];
            }
            this.PictureImagePartType = PictureType;

            SetResolution(true, TargetHorizontalResolution, TargetVerticalResolution);
        }
Esempio n. 29
0
        private void InitialisePictureFile(string FileName)
        {
            this.PictureFileName = FileName.Trim();

            this.PictureImagePartType = SLDrawingTool.GetImagePartType(this.PictureFileName);

            string sImageFileName = this.PictureFileName.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
            sImageFileName = sImageFileName.Substring(sImageFileName.LastIndexOf(Path.DirectorySeparatorChar) + 1);
            this.sAlternativeText = sImageFileName;
        }
Esempio n. 30
0
        // byte array as picture data suggested by Rob Hutchinson, with sample code sent in.
        /// <summary>
        /// Initializes an instance of SLPicture given a picture's data in a byte array.
        /// </summary>
        /// <param name="PictureByteData">The picture's data in a byte array.</param>
        /// <param name="PictureType">The image type of the picture.</param>
        public SLPicture(byte[] PictureByteData, ImagePartType PictureType)
        {
            InitialisePicture();

            DataIsInFile = false;
            this.PictureByteData = PictureByteData;
            this.PictureImagePartType = PictureType;

            SetResolution(false, 96, 96);
        }
    private static byte[] GetImageData(string imageFilePath, ref ImagePartType imagePartType, ref long imageWidthEMU, ref long imageHeightEMU)
    {
        byte[] imageFileBytes;

        // Open a stream on the image file and read it's contents. The
        // following code will generate an exception if an invalid file
        // name is passed.
        using (FileStream fsImageFile = File.OpenRead(imageFilePath))
        {
            imageFileBytes = new byte[fsImageFile.Length];
            fsImageFile.Read(imageFileBytes, 0, imageFileBytes.Length);

            Bitmap imageFile = new Bitmap(fsImageFile);

                // Determine the format of the image file.
                // This sample code supports working with the following types of image files:
                //
                // Bitmap (BMP)
                // Graphics Interchange Format (GIF)
                // Joint Photographic Experts Group (JPG, JPEG)
                // Portable Network Graphics (PNG)
                // Tagged Image File Format (TIFF)

                if (imageFile.RawFormat.Guid == ImageFormat.Bmp.Guid)
                    imagePartType = ImagePartType.Bmp;
                else if (imageFile.RawFormat.Guid == ImageFormat.Gif.Guid)
                    imagePartType = ImagePartType.Gif;
                else if (imageFile.RawFormat.Guid == ImageFormat.Jpeg.Guid)
                    imagePartType = ImagePartType.Jpeg;
                else if (imageFile.RawFormat.Guid == ImageFormat.Png.Guid)
                    imagePartType = ImagePartType.Png;
                else if (imageFile.RawFormat.Guid == ImageFormat.Tiff.Guid)
                    imagePartType = ImagePartType.Tiff;
                else
                {
                    throw new ArgumentException("Unsupported image file format: " + imageFilePath);
                }

                if (imageFile.Width > 1024)
                {

                   Size size = new Size(1024, (imageFile.Height * imageFile.Width) / 1024);
                   imageFile = Utils.ResizeImage(imageFile,size);
                }
                if (imageFile.Height > 768)
                {
                    Size size = new Size((imageFile.Height * imageFile.Width) / 768, 768);
                    imageFile = Utils.ResizeImage(imageFile, size);
                }

                // Get the dimensions of the image in English Metric Units (EMU)
                // for use when adding the markup for the image to the slide.
                imageWidthEMU =
                    (long)((imageFile.Width / imageFile.HorizontalResolution) * 914400L);
                imageHeightEMU =
                    (long)((imageFile.Height / imageFile.VerticalResolution) * 914400L);

        }

        return imageFileBytes;
    }
Esempio n. 32
0
    /// <param name="titleOrDescription">
    /// Replaces a placeholder-image with multiple images by comparing title/description
    ///
    /// Word Image -> Right Click -> Format Picture -> Alt Text -> Title
    /// </param>
    public static void ReplaceMultipleImages(WordprocessingDocument doc, string titleOrDescription, Bitmap[] bitmaps, string newImagePartId, bool adaptSize = false, ImagePartType imagePartType = ImagePartType.Png)
    {
        Blip[] blips = FindAllBlips(doc, d => d.Title == titleOrDescription || d.Description == titleOrDescription);

        if (blips.Count() != bitmaps.Length)
        {
            throw new ApplicationException("Images count does not match the images count in word");
        }

        if (adaptSize && !AvoidAdaptSize)
        {
            bitmaps = bitmaps.Select(bitmap =>
            {
                var part = doc.MainDocumentPart !.GetPartById(blips.First().Embed !);

                using (var stream = part.GetStream())
                {
                    Bitmap oldBmp = (Bitmap)Bitmap.FromStream(stream);
                    return(ImageResizer.Resize(bitmap, oldBmp.Width, oldBmp.Height));
                }
            }).ToArray();
        }

        doc.MainDocumentPart !.DeletePart(blips.First().Embed !);

        var i           = 0;
        var bitmapStack = new Stack <Bitmap>(bitmaps.Reverse());

        foreach (var blip in blips)
        {
            ImagePart img = CreateImagePart(doc, bitmapStack.Pop(), newImagePartId + i, imagePartType);
            blip.Embed = doc.MainDocumentPart.GetIdOfPart(img);
            i++;
        }
    }
Esempio n. 33
0
    public static void ReplaceBlipContent(this WordprocessingDocument doc, Blip blip, Bitmap bitmap, string newImagePartId, ImagePartType imagePartType = ImagePartType.Png)
    {
        if (doc.MainDocumentPart !.Parts.Any(p => p.RelationshipId == blip.Embed))
        {
            doc.MainDocumentPart.DeletePart(blip.Embed !);
        }
        ImagePart img = CreateImagePart(doc, bitmap, newImagePartId, imagePartType);

        blip.Embed = doc.MainDocumentPart.GetIdOfPart(img);
    }
Esempio n. 34
0
        private Drawing CreateDrawingFromStream(string src, ImagePartType imagePartType, Func <Stream> getStream)
        {
            long cx;
            long cy;

            using (Stream stream = getStream())
            {
                using (Bitmap bitmap = new Bitmap(stream))
                {
                    cx = (long)bitmap.Width * (long)((float)914400 / bitmap.HorizontalResolution);
                    cy = (long)bitmap.Height * (long)((float)914400 / bitmap.VerticalResolution);
                }
            }

            using (Stream stream = getStream())
            {
                ImagePart imagePart = context.MainDocumentPart.AddImagePart(imagePartType);

                imagePart.FeedData(stream);

                var image = new Drawing(
                    new DW.Inline(
                        new DW.Extent()
                {
                    Cx = cx, Cy = cy
                },
                        new DW.EffectExtent()
                {
                    LeftEdge   = 0L,
                    TopEdge    = 0L,
                    RightEdge  = 0L,
                    BottomEdge = 0L
                },
                        new DW.DocProperties()
                {
                    Id   = (UInt32Value)1U,
                    Name = "Picture 1"
                },
                        new DW.NonVisualGraphicFrameDrawingProperties(
                            new A.GraphicFrameLocks()
                {
                    NoChangeAspect = true
                }),
                        new A.Graphic(
                            new A.GraphicData(
                                new PIC.Picture(
                                    new PIC.NonVisualPictureProperties(
                                        new PIC.NonVisualDrawingProperties()
                {
                    Id   = (UInt32Value)0U,
                    Name = Path.GetFileName(src)
                },
                                        new PIC.NonVisualPictureDrawingProperties()),
                                    new PIC.BlipFill(
                                        new A.Blip(
                                            new A.BlipExtensionList(
                                                new A.BlipExtension()
                {
                    Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"
                })
                                            )
                {
                    Embed            = context.MainDocumentPart.GetIdOfPart(imagePart),
                    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 = cx, Cy = cy
                }),
                                        new A.PresetGeometry(
                                            new A.AdjustValueList()
                                            )
                {
                    Preset = A.ShapeTypeValues.Rectangle
                }))
                                )
                {
                    Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
                })
                        )
                {
                    DistanceFromTop    = (UInt32Value)0U,
                    DistanceFromBottom = (UInt32Value)0U,
                    DistanceFromLeft   = (UInt32Value)0U,
                    DistanceFromRight  = (UInt32Value)0U
                });

                return(image);
            }
        }
Esempio n. 35
0
    void CreateSlides(List <string> imageFileNames, string newPresentation)
    {
        string  relId;
        SlideId slideId;

        // Slide identifiers have a minimum value of greater than or equal to 256
        // and a maximum value of less than 2147483648. Assume that the template
        // presentation being used has no slides.
        uint currentSlideId = 256;

        string imageFileNameNoPath;

        long imageWidthEMU  = 0;
        long imageHeightEMU = 0;

        // Open the new presentation.
        using (PresentationDocument newDeck = PresentationDocument.Open(newPresentation, true))
        {
            PresentationPart presentationPart = newDeck.PresentationPart;

            // Reuse the slide master part. This code assumes that the template presentation
            // being used has at least one master slide.
            var slideMasterPart = presentationPart.SlideMasterParts.First();

            // Reuse the slide layout part. This code assumes that the template presentation
            // being used has at least one slide layout.
            var slideLayoutPart = slideMasterPart.SlideLayoutParts.First();

            // If the new presentation doesn't have a SlideIdList element yet then add it.
            if (presentationPart.Presentation.SlideIdList == null)
            {
                presentationPart.Presentation.SlideIdList = new SlideIdList();
            }

            // Loop through each image file creating slides in the new presentation.
            foreach (string imageFileNameWithPath in imageFileNames)
            {
                if (Step != null)
                {
                    Step();
                }

                imageFileNameNoPath = Path.GetFileNameWithoutExtension(imageFileNameWithPath);

                // Create a unique relationship id based on the current slide id.
                relId = "rel" + currentSlideId;

                // Get the bytes, type and size of the image.
                ImagePartType imagePartType = ImagePartType.Png;
                byte[]        imageBytes    = GetImageData(imageFileNameWithPath, ref imagePartType, ref imageWidthEMU, ref imageHeightEMU);

                // Create a slide part for the new slide.
                var slidePart = presentationPart.AddNewPart <SlidePart>(relId);
                GenerateSlidePart(imageFileNameNoPath, imageFileNameNoPath, imageWidthEMU, imageHeightEMU).Save(slidePart);

                // Add the relationship between the slide and the slide layout.
                slidePart.AddPart <SlideLayoutPart>(slideLayoutPart);

                // Create an image part for the image used by the new slide.
                // A hardcoded relationship id is used for the image part since
                // there is only one image per slide. If more than one image
                // was being added to the slide an approach similar to that
                // used above for the slide part relationship id could be
                // followed, where the image part relationship id could be
                // incremented for each image part.
                var imagePart = slidePart.AddImagePart(imagePartType, "relId1");
                GenerateImagePart(imagePart, imageBytes);

                // Add the new slide to the slide list.
                slideId = new SlideId();
                slideId.RelationshipId = relId;
                slideId.Id             = currentSlideId;
                presentationPart.Presentation.SlideIdList.Append(slideId);

                // Increment the slide id;
                currentSlideId++;
            }

            // Save the changes to the slide master part.
            slideMasterPart.SlideMaster.Save();

            // Save the changes to the new deck.
            presentationPart.Presentation.Save();
        }
    }
Esempio n. 36
0
        private void RenderImage(OpenXMLRenderer renderer, LinkInline link, string url)
        {
            using (var imageStream = new MemoryStream())
            {
                var streamResult = renderer.ImageProvider.GetImageStream(imageStream, url, renderer.ImageResolution, renderer.TextDocumentFolderLocation, renderer.LocalImages);

                if (!streamResult.IsValid)
                {
                    Current.Console.WriteLine("Error resolving image url {0}: {1}", url, streamResult.ErrorMessage);
                    return;
                }

                double?width = null, height = null;

                if (link.ContainsData(typeof(Markdig.Renderers.Html.HtmlAttributes)))
                {
                    var htmlAttributes = (Markdig.Renderers.Html.HtmlAttributes)link.GetData(typeof(Markdig.Renderers.Html.HtmlAttributes));
                    if (null != htmlAttributes.Properties)
                    {
                        foreach (var entry in htmlAttributes.Properties)
                        {
                            switch (entry.Key.ToLowerInvariant())
                            {
                            case "width":
                                width = GetLength(entry.Value);
                                break;

                            case "height":
                                height = GetLength(entry.Value);
                                break;
                            }
                        }
                    }
                }

                ImagePartType imgPartType = ImagePartType.Jpeg;
                switch (streamResult.Extension.ToLowerInvariant())
                {
                case ".bmp":
                    imgPartType = ImagePartType.Bmp;
                    break;

                case ".emf":
                    imgPartType = ImagePartType.Emf;
                    break;

                case ".gif":
                    imgPartType = ImagePartType.Gif;
                    break;

                case ".ico":
                    imgPartType = ImagePartType.Icon;
                    break;

                case ".jpg":
                case ".jpeg":
                    imgPartType = ImagePartType.Jpeg;
                    break;

                case ".pcx":
                    imgPartType = ImagePartType.Pcx;
                    break;

                case ".png":
                    imgPartType = ImagePartType.Png;
                    break;

                case ".tif":
                case ".tiff":
                    imgPartType = ImagePartType.Tiff;
                    break;

                case ".wmf":
                    imgPartType = ImagePartType.Wmf;
                    break;

                default:
                    throw new NotImplementedException();
                }


                MainDocumentPart mainPart = renderer._wordDocument.MainDocumentPart;
                ImagePart        imagePart = mainPart.AddImagePart(imgPartType);

                imageStream.Seek(0, SeekOrigin.Begin);
                imagePart.FeedData(imageStream);

                AddImageToBody(renderer, mainPart.GetIdOfPart(imagePart), streamResult, width, height);
            }
        }
Esempio n. 37
0
        public static Drawing CreateDrawing(
            WordprocessingDocument package,
            Stream imageStream,
            ImagePartType imagePartType,
            int percentage, long maxWidthInEmus)
        {
            var imagePart = package.MainDocumentPart.AddImagePart(imagePartType);

#if NET35 || NET45
            var img = new BitmapImage();

            using (imageStream)
            {
                img.BeginInit();
                img.StreamSource = imageStream;
                img.EndInit();

                imageStream.Seek(0, SeekOrigin.Begin);
                imagePart.FeedData(imageStream);
                // imagePart will also dispose the stream.
            }

            var widthPx    = img.PixelWidth;
            var heightPx   = img.PixelHeight;
            var horzRezDpi = (int)img.DpiX;
            var vertRezDpi = (int)img.DpiY;
#else
            ImageInfoBase imageInfo = null;

            using (imageStream)
            {
                var type = GetImageInfoType(imagePartType);
                imageInfo = ImageInfo.GetInfo(type, imageStream);
                if (imageInfo == null)
                {
                    throw new ArgumentException("Unsupported image format.");
                }

                imageStream.Seek(0, SeekOrigin.Begin);
                imagePart.FeedData(imageStream);
                // imagePart will also dispose the stream.
            }

            var widthPx    = imageInfo.Width;
            var heightPx   = imageInfo.Height;
            var horzRezDpi = imageInfo.DpiH;
            var vertRezDpi = imageInfo.DpiV;
#endif
            const int emusPerInch = 914400;
            var       widthEmus   = (long)widthPx * emusPerInch / horzRezDpi;
            var       heightEmus  = (long)heightPx * emusPerInch / vertRezDpi;

            if (widthEmus > maxWidthInEmus)
            {
                var ratio = heightEmus * 1.0m / widthEmus;
                widthEmus  = maxWidthInEmus;
                heightEmus = (long)(widthEmus * ratio);
            }

            if (percentage != 100)
            {
                widthEmus  = widthEmus * percentage / 100;
                heightEmus = heightEmus * percentage / 100;
            }

            var drawing = GetDrawing(package.MainDocumentPart.GetIdOfPart(imagePart), widthEmus, heightEmus);
            return(drawing);
        }
Esempio n. 38
0
        internal static string GetContentType(ImagePartType imageType)
        {
            switch (imageType)
            {
                case ImagePartType.Bmp:
                    return "image/bmp";

                case ImagePartType.Gif:
                    return "image/gif";

                case ImagePartType.Png:
                    return "image/png";

                case ImagePartType.Tiff:
                    return "image/tiff";

                //case ImagePartType.Xbm:
                //    return "image/xbm";

                case ImagePartType.Icon:
                    return "image/x-icon";

                case ImagePartType.Pcx:
                    return "image/x-pcx";

                //case ImagePartType.Pcz:
                //    return "image/x-pcz";

                //case ImagePartType.Pict:
                //    return "image/pict";

                case ImagePartType.Jpeg:
                    return "image/jpeg";

                case ImagePartType.Emf:
                    return "image/x-emf";

                case ImagePartType.Wmf:
                    return "image/x-wmf";

                default:
                    throw new ArgumentOutOfRangeException("imageType");
            }
        }
Esempio n. 39
0
 /// <summary>
 /// Adds a ImagePart to the WorksheetPart.
 /// </summary>
 /// <param name="partType">The part type of the ImagePart.</param>
 /// <param name="id">The relationship id.</param>
 /// <returns>The newly added part.</returns>
  public ImagePart AddImagePart(ImagePartType partType, string id)
 {
     string contentType = ImagePartTypeInfo.GetContentType(partType);
     string partExtension = ImagePartTypeInfo.GetTargetExtension(partType);
     OpenXmlPackage.PartExtensionProvider.MakeSurePartExtensionExist(contentType, partExtension);
 
     return AddImagePart(contentType, id);
 }
Esempio n. 40
0
        private void InitialisePicture()
        {
            // should be true once we get *everyone* to stop using those confoundedly
            // hard to understand EMUs and absolute positionings...
            UseEasyPositioning = false;
            TopPosition = 0;
            LeftPosition = 0;

            UseRelativePositioning = true;
            AnchorRowIndex = 1;
            AnchorColumnIndex = 1;
            OffsetX = 0;
            OffsetY = 0;
            WidthInEMU = 0;
            HeightInEMU = 0;
            WidthInPixels = 0;
            HeightInPixels = 0;
            fHorizontalResolutionRatio = 1;
            fVerticalResolutionRatio = 1;

            this.bLockWithSheet = true;
            this.bPrintWithSheet = true;
            this.vCompressionState = A.BlipCompressionValues.Print;
            this.decBrightness = 0;
            this.decContrast = 0;
            //this.decRotationAngle = 0;

            this.ShapeProperties = new SLShapeProperties(new List<System.Drawing.Color>());

            this.HasUri = false;
            this.HyperlinkUri = string.Empty;
            this.HyperlinkUriKind = UriKind.Absolute;
            this.IsHyperlinkExternal = true;

            this.DataIsInFile = true;
            this.PictureFileName = string.Empty;
            this.PictureByteData = new byte[1];
            this.PictureImagePartType = ImagePartType.Bmp;
        }