使用Open XML SDK将图从EA导出到文档文件

本文关键字:文档 文件 EA XML Open SDK 使用 | 更新日期: 2023-09-27 18:01:21

我正试图从EA导出一些图表到一个文档文件。虽然大多数图表都正确导出,但很少有图表被扭曲。它们的宽度或高度被放大,这种情况很少发生。我已经尝试了几种方法,但都无法纠正这个问题。

下面是我使用的代码:

EA。Project oProject = mainclass_srs . eareposs . getprojectinterface ();

oProject.PutDiagramImageToFile(diagram.DiagramGUID, SDSAddinForm.testsavediagramfilename, 1);
var img = BitmapFromUri(new Uri(SDSAddinForm.testsavediagramfilename, UriKind.RelativeOrAbsolute));
var widthPx = img.PixelWidth;
var heightPx = img.PixelHeight;
var horzRezDpi = img.DpiX;
var vertRezDpi = img.DpiY;
const int emusPerInch = 914400;
const int emusPerCm = 360000;
//    var maxWidthCm = 7.00;
var widthEmus = (long)((widthPx / horzRezDpi) * emusPerInch);
var heightEmus = (long)((heightPx / vertRezDpi) * emusPerInch);
var maxWidthEmus = (long)(14 * emusPerCm);
var maxHeightEmus = (long)(18.5 * emusPerCm);

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

谁能建议应该做什么改变,以便正确的大小导出

使用Open XML SDK将图从EA导出到文档文件

从我的图表包装器中,我使用以下代码提取图表图像:

    /// <summary>
    /// returns diagram image
    /// </summary>
    public Image image
    {
        get 
        {
            EA.Project projectInterface = this.model.getWrappedModel().GetProjectInterface();
            string diagramGUID = projectInterface.GUIDtoXML(this.wrappedDiagram.DiagramGUID);
            string filename = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".png";
            //save diagram image to file (format ".png")
            projectInterface.PutDiagramImageToFile(diagramGUID, filename, 1);
            //load the contents of the file into a memorystream
            MemoryStream imageStream = new MemoryStream(File.ReadAllBytes(filename));
            //then create the image from the memorystream.
            //this allows us to delete the temporary file right after loading it.
            //When using Image.FromFile the file would have been locked for the lifetime of the Image
            Image diagramImage = Image.FromStream(imageStream);
            //delete the temorary file
            System.IO.File.Delete(filename);
            return diagramImage;
        }
    }

然后我用这段代码让包含图像的模板对象通过序列化器

    [XmlIgnoreAttribute()]
    public System.Drawing.Image diagramImage { get; set; }
    // Serializes the 'Picture' Bitmap to XML.
    [XmlElementAttribute("diagramImage")]
    public string imageBase64String
    {
        get
        {
            if (this.diagramImage != null)
            {
                System.ComponentModel.TypeConverter BitmapConverter = System.ComponentModel.TypeDescriptor.GetConverter(this.diagramImage.GetType());
                byte[] byteArray = (byte[])BitmapConverter.ConvertTo(this.diagramImage, typeof(byte[]));
                string imageString = Convert.ToBase64String(byteArray);
                return imageString;
            }
            else
                return null;
        }
        set
        {
            if (value != null)
            {
                byte[] imageFileBytes = Convert.FromBase64String(value);
                this.diagramImage = new System.Drawing.Bitmap(new System.IO.MemoryStream(imageFileBytes));
            }
            else
            {
                this.diagramImage = null;
            }
        }
    }

然后在文档中这是将图像插入文档

的代码
/// <summary>
/// Adds image
/// </summary>
/// <param name="filename">image</param>
/// <param name="mainpart">main document part</param>
/// <param name="contentOpenXmlElement">element where picture will be added</param>
private static void AddImage(string filename, MainDocumentPart mainpart, OpenXmlElement contentOpenXmlElement)
{
    Picture pic = contentOpenXmlElement.Descendants().Where(x => x is Picture).FirstOrDefault() as Picture;
    if (null != pic)
    {
        byte[] imageFileBytes = Convert.FromBase64String(filename);
        Bitmap image = new Bitmap(new MemoryStream(imageFileBytes));
        // write the image to the document
        string SigId = "b" + Guid.NewGuid();
        //var imagePart = mainpart.AddNewPart<ImagePart>("image/png", SigId);
        //using (BinaryWriter writer = new BinaryWriter(imagePart.GetStream()))
        //{
        //    writer.Write(imageFileBytes);
        //    writer.Flush();
        //}
        ImagePart imagePart = mainpart.AddNewPart<ImagePart>("image/png", SigId);
        using (MemoryStream ms = new MemoryStream())
        {
            image.Save(ms, ImageFormat.Png);
            ms.Position = 0;
            imagePart.FeedData(ms);
        }

        //make sure image dimensions are respected and our image is centered in the container
        if (image.Width / (double)image.Height > pic.ShapeProperties.Transform2D.Extents.Cx / (double)pic.ShapeProperties.Transform2D.Extents.Cy)
        {
            long oldcy = pic.ShapeProperties.Transform2D.Extents.Cy;
            pic.ShapeProperties.Transform2D.Extents.Cy = (long)(pic.ShapeProperties.Transform2D.Extents.Cx * image.Height / (double)image.Width);
            pic.ShapeProperties.Transform2D.Offset.Y = (oldcy - pic.ShapeProperties.Transform2D.Extents.Cy) >> 1;
        }
        else
        {
            long oldcx = pic.ShapeProperties.Transform2D.Extents.Cx;
            pic.ShapeProperties.Transform2D.Extents.Cx = (long)(pic.ShapeProperties.Transform2D.Extents.Cy * image.Width / (double)image.Height);
            pic.ShapeProperties.Transform2D.Offset.X = (oldcx - pic.ShapeProperties.Transform2D.Extents.Cx) >> 1;
        }
        pic.BlipFill = new BlipFill(new Blip { Embed = SigId }, new Stretch(new FillRectangle()));
        var element = new Drawing(new Inline(
                            new Extent { Cx = pic.ShapeProperties.Transform2D.Extents.Cx, Cy = pic.ShapeProperties.Transform2D.Extents.Cy },
                            new EffectExtent { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
                            new DocProperties { Id = (UInt32Value)1U, Name = "Picture 1" },
                            new NonVisualGraphicFrameDrawingProperties(
                            new A.GraphicFrameLocks { NoChangeAspect = true }),
                                    new A.Graphic(new A.GraphicData(new Picture(
                                            new PIC.NonVisualPictureProperties(
                                                new PIC.NonVisualDrawingProperties { Id = (UInt32Value)0U, Name = "New Bitmap Image.jpg" },
                                                    new PIC.NonVisualPictureDrawingProperties()),
                                            new BlipFill(new Blip(new A.BlipExtensionList(
                                                new A.BlipExtension { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }))
                                            { Embed = SigId, CompressionState = A.BlipCompressionValues.Print },
                                            new Stretch(new FillRectangle())),
                                            new PIC.ShapeProperties(new A.Transform2D(
                                            new A.Offset { X = pic.ShapeProperties.Transform2D.Offset.X, Y = pic.ShapeProperties.Transform2D.Offset.Y },
                                            new A.Extents { Cx = pic.ShapeProperties.Transform2D.Extents.Cx, Cy = pic.ShapeProperties.Transform2D.Extents.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,
                                                 EditId = "50D07946"
                                             });
        contentOpenXmlElement.RemoveAllChildren();
        contentOpenXmlElement.AppendChild(new Paragraph(new Run(element)));
    }
}

我建议直接使用

Repository.GetProjectInterface.PutDiagramImageToFile (string Diagram GUID, string FileName, long Type)

这将以您指定的格式保存正确呈现的文件。

存在图表大小不正确的问题(论坛讨论;记不住细节)。如果是,请尝试升级或报告错误。