Exemple #1
0
        private static void CopyChart(string fromPresentation1, string toPresentation2)
        {
            using (PresentationDocument ppt1 = PresentationDocument.Open(fromPresentation1, false))
                using (PresentationDocument ppt2 = PresentationDocument.Open(toPresentation2, true))
                {
                    SlideId fromSlideId = ppt1.PresentationPart.Presentation.SlideIdList.GetFirstChild <SlideId>();
                    string  fromRelId   = fromSlideId.RelationshipId;

                    SlideId toSlideId = ppt2.PresentationPart.Presentation.SlideIdList.GetFirstChild <SlideId>();
                    string  toRelId   = fromSlideId.RelationshipId;

                    SlidePart fromSlidePart = (SlidePart)ppt1.PresentationPart.GetPartById(fromRelId);
                    SlidePart toSlidePart   = (SlidePart)ppt2.PresentationPart.GetPartById(fromRelId);

                    var graphFrame = fromSlidePart.Slide.CommonSlideData.ShapeTree.GetFirstChild <GraphicFrame>().CloneNode(true);
                    GroupShapeProperties groupShapeProperties = toSlidePart.Slide.CommonSlideData.ShapeTree.GetFirstChild <GroupShapeProperties>();
                    toSlidePart.Slide.CommonSlideData.ShapeTree.InsertAfter(graphFrame, groupShapeProperties);

                    ChartPart fromChartPart = fromSlidePart.ChartParts.First();
                    ChartPart toChartPart   = toSlidePart.AddNewPart <ChartPart>("rId2");


                    using (StreamReader streamReader = new StreamReader(fromChartPart.GetStream()))
                        using (StreamWriter streamWriter = new StreamWriter(toChartPart.GetStream(FileMode.Create)))
                        {
                            streamWriter.Write(streamReader.ReadToEnd());
                        }

                    EmbeddedPackagePart fromEmbeddedPackagePart1 = fromChartPart.EmbeddedPackagePart;
                    EmbeddedPackagePart toEmbeddedPackagePart1   = toChartPart.AddNewPart <EmbeddedPackagePart>("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "rId3");

                    using (StreamReader streamReader = new StreamReader(fromEmbeddedPackagePart1.GetStream()))
                        toEmbeddedPackagePart1.FeedData(streamReader.BaseStream);
                }
        }
Exemple #2
0
        private void TransformEmbeddedPart(EmbeddedPackagePart part, OptimizeDiagnostic diagnostic, ImageOptimizerOptions options, CancellationToken token)
        {
            // Read mode about office mime types: http://filext.com/faq/office_mime_types.php
            var fileType = part.ContentType
                           switch
            {
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => ".docx",
                "application/vnd.openxmlformats-officedocument.presentationml.presentation" => ".pptx",
                _ => null
            };

            if (fileType is null)
            {
                var message = $"Unsupported embedding type {part.ContentType}";
                diagnostic.Errors.Add(new OptimizeError(part.Uri.OriginalString, message));
                return;
            }

            using var result = Transform(fileType, part.GetStream(), out var partDiagnostic, options, token);
            result.Position  = 0;
            part.FeedData(result);

            foreach (var error in partDiagnostic.Errors)
            {
                var pointer = part.Uri.OriginalString + '|' + error.Pointer;
                diagnostic.Errors.Add(new OptimizeError(pointer, error.Message));
            }
        }
        private EmbeddedObject ProcessObject(string filePath, string contentType, string progId)
        {
            if (TryCreateAbsoluteUri(filePath, out Uri uri))
            {
                int    width, height;
                string relationshipId = string.Concat("rId", (++context.RelationshipId).ToString());

                EmbeddedPackagePart embeddedPackagePart = context.MainDocumentPart.AddNewPart <EmbeddedPackagePart>(contentType,
                                                                                                                    relationshipId);

                using (Stream stream = GetStream(uri))
                {
                    embeddedPackagePart.FeedData(stream);
                }

                ImagePart imagePart = context.MainDocumentPart.AddImagePart(ImagePartType.Jpeg);

                using (MemoryStream mem = GetImageStream(Path.GetFileName(filePath), out width, out height))
                {
                    imagePart.FeedData(mem);
                }

                V.Shape shape = new V.Shape()
                {
                    Id = string.Concat("_x0000_i", context.RelationshipId.ToString()), Ole = false, Type = "#_x0000_t75", Style = "width:" + width.ToString() + "pt;height:" + height.ToString() + "pt"
                };
                V.ImageData imageData = new V.ImageData()
                {
                    Title = "", RelationshipId = context.MainDocumentPart.GetIdOfPart(imagePart)
                };

                shape.Append(imageData);

                EmbeddedObject embeddedObject = new EmbeddedObject()
                {
                    DxaOriginal = "9360", DyaOriginal = "450"
                };
                embeddedObject.Append(shape);

                OVML.OleObject oleObject = new OVML.OleObject()
                {
                    Type = OVML.OleValues.Embed, ProgId = progId, ShapeId = string.Concat("_x0000_i", context.RelationshipId.ToString()), DrawAspect = OVML.OleDrawAspectValues.Content, ObjectId = string.Concat("_", context.RelationshipId.ToString()), Id = relationshipId
                };

                embeddedObject.Append(oleObject);

                return(embeddedObject);
            }

            return(null);
        }
    /// <summary>
    /// Appends an Embedded Object into the specified Main Document
    /// </summary>
    /// <param name="mainDocumentPart">The MainDocument Part of your OpenXml Word Doc</param>
    /// <param name="fileInfo">The FileInfo object associated with the file being embedded</param>
    /// <param name="displayAsIcon">Whether or not to display the embedded file as an Icon (Otherwise it will display a snapshot of the file)</param>
    public static void AppendEmbeddedObject(MainDocumentPart mainDocumentPart, FileInfo fileInfo, bool displayAsIcon)
    {
        OpenXmlEmbeddedObject openXmlEmbeddedObject = new OpenXmlEmbeddedObject(fileInfo, displayAsIcon);

        if (!String.IsNullOrEmpty(openXmlEmbeddedObject.OleObjectBinaryData))
        {
            using (Stream dataStream = new MemoryStream(Convert.FromBase64String(openXmlEmbeddedObject.OleObjectBinaryData)))
            {
                if (!String.IsNullOrEmpty(openXmlEmbeddedObject.OleImageBinaryData))
                {
                    using (Stream emfStream = new MemoryStream(Convert.FromBase64String(openXmlEmbeddedObject.OleImageBinaryData)))
                    {
                        string    imagePartId = OpenXmlWordHelper.GetUniqueXmlItemID();
                        ImagePart imagePart   = mainDocumentPart.AddImagePart(ImagePartType.Emf, imagePartId);
                        if (emfStream != null)
                        {
                            imagePart.FeedData(emfStream);
                        }
                        string embeddedPackagePartId = OpenXmlWordHelper.GetUniqueXmlItemID();
                        if (dataStream != null)
                        {
                            if (openXmlEmbeddedObject.ObjectIsOfficeDocument)
                            {
                                EmbeddedPackagePart embeddedObjectPart = mainDocumentPart.AddNewPart <EmbeddedPackagePart>(
                                    openXmlEmbeddedObject.FileContentType, embeddedPackagePartId);
                                embeddedObjectPart.FeedData(dataStream);
                            }
                            else
                            {
                                EmbeddedObjectPart embeddedObjectPart = mainDocumentPart.AddNewPart <EmbeddedObjectPart>(
                                    openXmlEmbeddedObject.FileContentType, embeddedPackagePartId);
                                embeddedObjectPart.FeedData(dataStream);
                            }
                        }
                        if (!displayAsIcon && !openXmlEmbeddedObject.ObjectIsPicture)
                        {
                            Paragraph attachmentHeader = OpenXmlWordHelper.CreateParagraph(JustificationValues.Left,
                                                                                           OpenXmlWordHelper.ParagraphSpacing.AfterMedium, null, true, false,
                                                                                           String.Format("Attachment: {0} (Double-Click to Open)", fileInfo.Name));
                            mainDocumentPart.Document.Body.Append(attachmentHeader);
                        }
                        Paragraph embeddedObjectParagraph = GetEmbeededObjectParagraph(openXmlEmbeddedObject.FileType,
                                                                                       imagePartId, openXmlEmbeddedObject.OleImageStyle, embeddedPackagePartId);
                        mainDocumentPart.Document.Body.Append(embeddedObjectParagraph);
                    }
                }
            }
        }
    }
        public void Process(ShapeElementBase shape)
        {
            element      = shape as ChartElement;
            fullData     = element.Data.Clone();
            element.Data = fullData.GetFragmentByIndexes(element.RowIndexes, element.ColumnIndexes);
            element.ProcessCommands(element.Data);
            if (element.Data == null)
            {
                return;
            }

            //get chart reference
            A.GraphicData  graphicData    = element.ChartFrame.Graphic.GraphicData;
            ChartReference chartReference = graphicData.FirstElement <ChartReference>();

            if (chartReference == null)
            {
                return;
            }

            //various chart structure elements
            ChartPart chartPart = element.Slide.Slide.SlidePart.GetPartById(chartReference.Id.Value) as ChartPart;
            Chart     chart     = chartPart.ChartSpace.FirstElement <Chart>();

            //get external data and update it
            DataElement dataToInsert = element.Data.Clone();

            foreach (var item in element.ChildShapes)
            {
                var childDataElement = fullData.GetFragmentByIndexes(item.RowIndexes, item.ColumnIndexes);
                element.ProcessCommands(childDataElement);
                dataToInsert.MergeWith(childDataElement);
            }
            ExternalData        externalData   = chartPart.ChartSpace.FirstElement <ExternalData>();
            EmbeddedPackagePart xlsPackagePart = chartPart.GetPartById(externalData.Id.Value) as EmbeddedPackagePart;
            Stream sourceStream = xlsPackagePart.GetStream();
            Stream outputStream = new MemoryStream();

            dataToInsert.TrimHiddenRowsAndColumns();
            List <ChartSeriesElement> newSeries = SpreadsheetProcessor.InsertData(dataToInsert, sourceStream, outputStream);

            outputStream.Seek(0, SeekOrigin.Begin);
            xlsPackagePart.FeedData(outputStream);


            ChartType        type      = ChartType.None;
            Tuple <int, int> dataRange = null;
            var charts = chart.PlotArea.Elements().ToList();

            OpenXmlElement mainChart  = null;
            int            chartIndex = 0;

            for (; chartIndex < charts.Count; chartIndex++)
            {
                GetChartTypeAndDataRange(ref type, ref dataRange, charts[chartIndex]);
                if (type != ChartType.None)
                {
                    mainChart = charts[chartIndex];
                    chartIndex++;
                    break;
                }
            }


            int seriesIndex = 0;

            foreach (ErrorBarCommand errorBarCommand in element.CommandsOf <ErrorBarCommand>())
            {
                ChartSeriesElement chartSeriesMinus = newSeries.FirstOrDefault(s => s.ColumnIndex == errorBarCommand.MinusIndex && !s.ColumnIndex.IsCore);
                ChartSeriesElement chartSeriesPlus  = null;
                if (errorBarCommand.PlusIndex != null)
                {
                    chartSeriesPlus = newSeries.FirstOrDefault(s => s.ColumnIndex == errorBarCommand.PlusIndex && !s.ColumnIndex.IsCore);
                }
                if (seriesIndex < newSeries.Count)
                {
                    newSeries[seriesIndex].MinusErrorBar = chartSeriesMinus;
                    newSeries[seriesIndex].PlusErrorBar  = chartSeriesPlus;
                }
                seriesIndex++;
            }
            foreach (ErrorBarCommand errorBarCommand in element.CommandsOf <ErrorBarCommand>())
            {
                ChartSeriesElement chartSeriesMinus = newSeries.FirstOrDefault(s => s.ColumnIndex == errorBarCommand.MinusIndex && !s.ColumnIndex.IsCore);
                ChartSeriesElement chartSeriesPlus  = null;
                if (errorBarCommand.PlusIndex != null)
                {
                    chartSeriesPlus = newSeries.FirstOrDefault(s => s.ColumnIndex == errorBarCommand.PlusIndex && !s.ColumnIndex.IsCore);
                }
                if (chartSeriesMinus != null)
                {
                    newSeries.Remove(chartSeriesMinus);
                }
                if (chartSeriesPlus != null)
                {
                    newSeries.Remove(chartSeriesPlus);
                }
            }
            seriesIndex = 0;
            if (element.CommandsOf <YCommand>().Count > 0)
            {
                List <ChartSeriesElement> newSeriesWithoutY = new List <ChartSeriesElement>(newSeries);
                foreach (YCommand yCommand in element.CommandsOf <YCommand>())
                {
                    ChartSeriesElement yChartSeries = newSeries.FirstOrDefault(s => s.ColumnIndex == yCommand.Index);  //  && !s.ColumnIndex.IsCore
                    if (yChartSeries != null)
                    {
                        newSeriesWithoutY.Remove(yChartSeries);
                    }
                }
                foreach (YCommand yCommand in element.CommandsOf <YCommand>())
                {
                    ChartSeriesElement yChartSeries = newSeries.FirstOrDefault(s => s.ColumnIndex == yCommand.Index); // && !s.ColumnIndex.IsCore
                    for (int i = seriesIndex; i < newSeriesWithoutY.Count; i++)
                    {
                        newSeriesWithoutY[i].YValues = yChartSeries;
                    }
                    //if (seriesIndex < newSeries.Count)
                    //{
                    //    newSeries[seriesIndex].YValues = yChartSeries;
                    //}
                    seriesIndex++;
                }
                newSeries = new List <ChartSeriesElement>(newSeriesWithoutY);
            }


            switch (type)
            {
            case ChartType.Waterfall:
            case ChartType.Bar:
                ReplaceBarChart(newSeries, mainChart as BarChart, element, element.IsWaterfall);
                break;

            case ChartType.Scatter:
                ReplaceScatterChart(newSeries, mainChart as ScatterChart, element);
                break;

            case ChartType.Line:
                ReplaceLineChart(newSeries, mainChart as LineChart, element);
                break;
            }
            int childShapeIndex = 0;

            for (; chartIndex < charts.Count; chartIndex++)
            {
                var childChart = charts[chartIndex];
                if (element.ChildShapes.Count > childShapeIndex)
                {
                    GetChartTypeAndDataRange(ref type, ref dataRange, childChart);
                    if (type != ChartType.None)
                    {
                        ProcessChildShapes(element, element.ChildShapes[childShapeIndex], type, childChart, newSeries);
                        childShapeIndex++;
                    }
                }
            }
        }