我的 Azure Web 应用程序使用以下代码调用 html2pdfrocket:
MemoryStream stream = new MemoryStream(result.Content.ReadAsByteArrayAsync().Result);
System.IO.File.WriteAllText(path, stream.ToString());
但是我得到了一个只有几个字节的无效 PDF。我知道我传递给 html2pdfrocket 的 URL 是有效的,因为我可以将其粘贴到他们的网站中进行测试。在尝试将数据保存到文件夹之前,我是否需要异步/等待或其他方式来获取所有数据?
不需要使用 async/await,.Result
就像 await 一样。
您的代码中出现类似错误,stream.ToString()
仅将流对象本身转换为字符串,但不包含内容。
我建议您使用 byte[] 数组而不是流(我使用流进行了测试,但即使内容长度正确,保存的 .pdf 文件也是空的)。
尝试使用像下面这样的 byte[] 数组,它在我身边工作:
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("apikey","xxxxx"),
new KeyValuePair<string, string>("value", "the url")
});
var result = client.PostAsync("http://api.html2pdfrocket.com/pdf", content).Result;
if (result.IsSuccessStatusCode)
{
// change the path as per your need
System.IO.File.WriteAllBytes(@"d:\temp\0618.pdf", result.Content.ReadAsByteArrayAsync().Result);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句