我使用DocumentFormat.OpenXml生成docx。我尝试从WebClient异步加载小png图像(20-50 kb)到我的docx。我对一个代码有不同的结果:
此代码演示了我的问题:
internal class Program
{
public static void Main(string[] args)
{
using (var outputStream = new MemoryStream())
{
using (var doc = WordprocessingDocument.Create(outputStream, WordprocessingDocumentType.Document))
{
var mainPart = doc.AddMainDocumentPart();
new Document(new Body()).Save(mainPart);
var tasks = Directory.GetFiles("images").Select(async it =>
await AddImagePart(it, mainPart.AddImagePart(ImagePartType.Png)).ConfigureAwait(false));
Task.WaitAll(tasks.ToArray());
}
File.WriteAllBytes("output.docx", outputStream.ToArray());
}
}
private static async Task AddImagePart(string path, ImagePart imagePart)
{
using (var client = new WebClient())
{
var image = await client.DownloadDataTaskAsync(path).ConfigureAwait(false);
imagePart.FeedData(new MemoryStream(image));
}
}
packages.config
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="DocumentFormat.OpenXml" version="2.7.2" targetFramework="net46" />
<package id="System.IO.FileSystem.Primitives" version="4.0.1" targetFramework="net46" />
<package id="System.IO.Packaging" version="4.0.0" targetFramework="net46" />
</packages>
有git大文件问题和.net少于4.6的问题。但我使用小文件和.net4.6。