Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# OpenXML添加的图像位于文档媒体文件夹中,但未显示在Office中_C#_Wpf_Openxml - Fatal编程技术网

C# OpenXML添加的图像位于文档媒体文件夹中,但未显示在Office中

C# OpenXML添加的图像位于文档媒体文件夹中,但未显示在Office中,c#,wpf,openxml,C#,Wpf,Openxml,我在创建Word文档(openXML)和向其中添加图像时遇到问题。我已经尝试了很多只找到的代码片段以及官方MS文档() 为了实现这一点,我基本上复制了上面链接中的完整代码,并包装了两个WPF文件对话框,首先创建一个文档,然后选择要添加的图像。我还在图像前添加了一些文本,以检查访问文档是否正常工作 一切编译和运行都没有错误。但是,创建的文档只有我的文本,没有图像的标志。我经常读到人们有错误,比如“红色X”,或者添加图像的资源丢失,但对我来说,文档只包含添加的文本。 但是,当我将文档作为归档文件打开

我在创建Word文档(openXML)和向其中添加图像时遇到问题。我已经尝试了很多只找到的代码片段以及官方MS文档()

为了实现这一点,我基本上复制了上面链接中的完整代码,并包装了两个WPF文件对话框,首先创建一个文档,然后选择要添加的图像。我还在图像前添加了一些文本,以检查访问文档是否正常工作

一切编译和运行都没有错误。但是,创建的文档只有我的文本,没有图像的标志。我经常读到人们有错误,比如“红色X”,或者添加图像的资源丢失,但对我来说,文档只包含添加的文本。 但是,当我将文档作为归档文件打开时(例如使用winrar),我可以看到我选择的图像被放置在文档的“媒体”文件夹中

为什么在office应用程序中打开文档时不显示任何内容

下面是我的代码,但它基本上来自Official SDK:

using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;    

public static void ExportToDoc()
    {
        
        SaveFileDialog exportFile = new SaveFileDialog
        {
            Filter = "Word Document (*.docx)|*.docx",
            AddExtension = true,
            FileName = "Proposed-Filename.docx"
        };
        switch (exportFile.ShowDialog())
        {
            case true:
                WordprocessingDocument doc = WordprocessingDocument.Create(exportFile.FileName, WordprocessingDocumentType.Document);
                // Make some changes to the document.  
                MainDocumentPart mainDocumentPart = doc.AddMainDocumentPart();
                mainDocumentPart.Document = new Document();
                Document document = mainDocumentPart.Document;
                Body body = document.AppendChild(new Body());
                Paragraph para = body.AppendChild(new Paragraph());
                Run run = para.AppendChild(new Run());
                run.AppendChild(new Text("Created text in body."));

                //Prepare Image
                OpenFileDialog openImage = new OpenFileDialog
                {
                    Filter = "Bild (*.jpg)| *.jpg"
                };
                
                //Document is created
                doc.Close();

                switch (openImage.ShowDialog())
                {
                    case true:
                        InsertAPicture(exportFile.FileName, openImage.FileName);
                        break;
                    default:
                        break;
                }

                Console.WriteLine("Bild angehängt");
                break;
            default:
                break;
        }
        
    }
    //from MSDN after this point:
    public static void InsertAPicture(string document, string fileName)
    {
        using (WordprocessingDocument wordprocessingDocument =
            WordprocessingDocument.Open(document, true))
        {
            MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

            ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

            using (FileStream stream = new FileStream(fileName, FileMode.Open))
            {
                imagePart.FeedData(stream);
            }

            AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
        }
    }

    private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
    {
        // Define the reference of the image.
        var element =
             new DocumentFormat.OpenXml.Office.Drawing.Drawing(
                 new DW.Inline(
                     new DW.Extent() { Cx = 990000L, Cy = 792000L },
                     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 = "New Bitmap Image.jpg"
                                     },
                                     new PIC.NonVisualPictureDrawingProperties()),
                                 new PIC.BlipFill(
                                     new A.Blip(
                                         new A.BlipExtensionList(
                                             new A.BlipExtension()
                                             {
                                                 Uri =
                                                    "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                             })
                                     )
                                     {
                                         Embed = relationshipId,
                                         CompressionState =
                                         A.BlipCompressionValues.Print
                                     },
                                     new A.Stretch(
                                         new A.FillRectangle())),
                                 new PIC.ShapeProperties(
                                     new A.Transform2D(
                                         new A.Offset() { X = 0L, Y = 0L },
                                         new A.Extents() { Cx = 990000L, Cy = 792000L }),
                                     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"
                 });

        // Append the reference to body, the element should be in a Run.
        wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
    }

}

好吧,我自己想出来了:

我在绘图时使用了错误的名称空间。就这样

有趣的是,这根本没有产生任何错误,但却不起作用

所以,如果你有这个问题,这里是我改变的:

 private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
        {
            // Define the reference of the image.
            var element =
                 new DocumentFormat.OpenXml.Office.Drawing.Drawing(
                   
改为:

private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
            {
                // Define the reference of the image.
                var element =
                     new DocumentFormat.OpenXml.Wordprocessing.Drawing(

只是一个注释,但是
开关(exportFile.ShowDialog())
看起来非常奇怪。为什么不直接编写
if(exportFile.ShowDialog()==true
)或
if((bool)exportFile.ShowDialog())
?我实际上尝试了
if(exportFile.ShowDialog())
,但没有成功。我来自java,对整个C#世界来说都是比较新的。有些时候,我看到一个代码使用开关被剪断,我想一定是这样的。从未尝试过从现在起将使用的长if版本,该版本的
“==true”
。谢谢提醒。
if(exportFile.ShowDialog())
不起作用,因为该方法返回一个可为空的bool(一个
bool?
)。因此,在我的第一个评论中有两个变体。