我正在使用第 3 方 html 到 pdf 的转换(DocRaptor)。您将 HTML 发布到他们的网站,他们会使用 PDF 进行响应。他们给你的启动代码工作正常,但它把文件放到你的硬盘上。我修改了他们的代码以使其通过浏览器并作为文件下载。所以我 100% 确信我从 HTTP 响应中获得的数据是好的数据。我似乎无法将其组装回可用的文件。
我有理由相信问题是我如何处理 responseStream 数据。一旦我进入 Try/Catch,一切似乎都出错了。我对 c# 和 web 编程非常陌生,所以我非常感谢这里的 SO 用户提供的一些指导。谢谢。这是我的代码。
string postData = String.Format(PostFormat,
(string.IsNullOrEmpty(DocumentContent) ? "document_url" : "document_content"),
HttpUtility.UrlEncode(string.IsNullOrEmpty(DocumentContent) ? DocumentURL : DocumentContent),
HttpUtility.UrlEncode(Name),
HttpUtility.UrlEncode(type),
HttpUtility.UrlEncode(Test.ToString().ToLower()),
HttpUtility.UrlEncode(Strict),
HttpUtility.UrlEncode(PrinceOptions));
var byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(DocRaptorUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (var dataStream = request.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); }
System.IO.Stream stream = null;
try
{
using (HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse())
{
using (System.IO.Stream responseStream = httpResponse.GetResponseStream())
{
var filepath = @"C:\Users\David\Downloads\UberwriterUSRReport.pdf";
HttpContext.Current.Response.ContentType = "application/pdf";
// let the browser know how to open the PDF document, attachment or inline, and the file name
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename=UberwriterUSRReport.pdf"));
stream = new System.IO.FileStream(filepath, System.IO.FileMode.Create);
CopyStream(responseStream, stream);
long bytestToRead = stream.Length;
while (bytestToRead > 0)
{
if (HttpContext.Current.Response.IsClientConnected)
{
byte[] buffer = new Byte[10000];
int length = stream.Read(buffer, 0, 10000);
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
HttpContext.Current.Response.Flush();
bytestToRead = bytestToRead - length;
}
else
{
bytestToRead = -1;
}
}
}
}
}