将图像添加到Word文档的方法(DocumentFormat.OpenXml)

5

我正在使用OpenXml SDK创建一个简单的Word文档,目前已经可以工作。 现在,我该如何将我的文件系统中的图像添加到此文档中呢?我不在意它在文档中的位置,只要它在那里就可以了。 谢谢! 以下是我目前所拥有的内容。

 string fileName = "proposal"+dealerId +Guid.NewGuid().ToString()+".doc";
       string filePath = @"C:\DWSApplicationFiles\Word\" + fileName;
       using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document, true))
       {
           MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();

           mainPart.Document = new Document();
           //create the body
           Body body = new Body();
           DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
           DocumentFormat.OpenXml.Wordprocessing.Run runParagraph = new DocumentFormat.OpenXml.Wordprocessing.Run();         

           DocumentFormat.OpenXml.Wordprocessing.Text text_paragraph = new DocumentFormat.OpenXml.Wordprocessing.Text("This is a test");
           runParagraph.Append(text_paragraph);
           p.Append(runParagraph);
           body.Append(p);
           mainPart.Document.Append(body);
           mainPart.Document.Save();              
       }
3个回答

1

这里有一种方法,可能比上面发布的msdn页面中描述的方法更简单,这段代码是用C++/CLI编写的,但当然你也可以用C#编写等效的代码。

WordprocessingDocument^ doc = WordprocessingDocument::Open(doc_name, true);
FileStream^ img_fs = gcnew FileStream(image_path, FileMode::Open);
ImagePart^ image_part = doc->MainDocumentPart->AddImagePart(ImagePartType::Jpeg);
image_part->FeedData(img_fs);
Run^ img_run = doc->MainDocumentPart->Document->Body->AppendChild(gcnew Paragraph())->AppendChild(gcnew Run());
Vml::ImageData^ img_data = img_run->AppendChild(gcnew Picture())->AppendChild(gcnew Vml::Shape())->AppendChild(gcnew Vml::ImageData());
img_data->RelationshipId = doc->MainDocumentPart->GetIdOfPart(image_part);
doc->Close();

0

这段代码对我很有用:http://msdn.microsoft.com/en-us/library/bb497430.aspx

你的代码将图像添加到了docx包中,但是为了在文档中看到它,你必须在document.xml中声明它,即将其链接到你的物理图像。这就是为什么你必须编写在msdn链接中列出的那个长函数。

我的问题是如何给图片添加效果(编辑、裁剪、去除背景)。 如果你知道如何做到这一点,我会非常感激你的帮助 :)


0
如何使用Open XML API向Office Open XML包添加图像部件

http://msdn.microsoft.com/en-us/library/bb497430(v=office.12).aspx

public static void AddImagePart(string document, string fileName)
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
    {
        MainDocumentPart mainPart = wordDoc.MainDocumentPart;

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

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

不要只发布链接,最好将标题和链接的引用放在一起。 - Samuel Neff
这是什么链接?我知道微软有类似的代码发布,但这并没有添加图像。在微软网站上还有另一个版本,看起来像这样,但包括其余部分,而且更多。这不是有效的回复。 - Jonathan Wood

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接