如何在 ASP.NET 生成的 Word 文件中嵌入图像 [英] How can I embed images in an ASP.NET Generated Word File

查看:18
本文介绍了如何在 ASP.NET 生成的 Word 文件中嵌入图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很常见的问题,正如我在各种用户组中看到的那样,但找不到合适的答案.

I have a quite common problem, as I saw in the various user groups but could not find a suitable answer.

我想要做的是在我的网站中生成一个 ASP.NET 页面,该页面可以选择导出为 Microsoft Word .doc 格式.

What I want to do is generate an ASP.NET page in my website which will have the option of being exported into Microsoft Word .doc format.

我使用的方法是这样的:

The method I have used is this:

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Test.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/msword";

StringWriter sw = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(sw);
Page.RenderControl(htmlWrite);
Response.Write(sw.ToString());
Response.End();

然而,即使它生成了一个 word 文档,图像还是嵌入在文档中,而不是作为链接放置.我一直在寻找一种方法来做到这一点,但还没有找到真正有效的方法.

However this eventhough it generates a word doc, the images are note embedded in the document, rather they are placed as links. I have looked for a way to do this, but have not found something that actually worked.

我很感激我能得到的任何帮助,因为这是最后一分钟"的要求(谈典型)

I would appreciate any help I can get, since this as "last minute" requirement (talk about typical)

谢谢

推荐答案

简短回答:您需要为页面中的图像来源提供绝对 URL.

Short Answer: You need to provide absolute URLs for the source of the images in your page.

更长的答案:

如果您使用 *.doc 扩展名重命名,Microsoft Word 将打开一个 HTML 文档.这就是您提供的代码正在执行的操作.在这种情况下,图像不会像您以实际 Word 格式创建文档那样嵌入文档中.如果您的图片使用相对 URL,那么 Word 将不知道在哪里查找它们,因此需要绝对 URL.

Microsoft Word will open an HTML document if you rename it with a *.doc extension. This is what the code that you provided is doing. In this case, the images are not embedded in the document like they would be if you created a document in actual Word format. If your images are using relative URLs then Word will not know where to look for them, hence the need for absolute URLs.

注意:这意味着在没有互联网连接的情况下查看文档的任何人都不会看到图像,因为每次打开文档时服务器都会请求它们.

一个更优雅的解决方案是以真正的 Word 格式创建文档.一个很棒的库是 Aspose.Words.使用这个库,您可以将图像直接嵌入到文档中,这样它们就不会依赖于服务器.

A more elegant solution would be to create the document in the real Word format. A great library for this is Aspose.Words. Using this library you would be able to embed the images directly into the document so that they do not rely on the server.

这篇关于如何在 ASP.NET 生成的 Word 文件中嵌入图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆