我使用 iTextSharp 生成了一个 pdf,当它创建时,它会自动保存在我在服务器上的代码中提供的位置,而不是在客户端,当然不会告诉用户任何信息。
我需要将它发送给客户端,我需要提示一个对话框来询问用户他想在哪里保存他的 pdf..
请问我该怎么做?
这是我的pdf代码:
using (MemoryStream myMemoryStream = new MemoryStream())
{
Document document = new Document();
PdfWriter PDFWriter = PdfWriter.GetInstance(document, myMemoryStream);
document.AddHeader("header1", "HEADER1");
document.Open();
//..........
document.Close();
byte[] content = myMemoryStream.ToArray();
// Write out PDF from memory stream.
using (FileStream fs = File.Create(HttpContext.Current.Server.MapPath("~\\report.pdf")))
{
fs.Write(content, 0, (int)content.Length);
}
编辑
这是我想要的结果的一个例子 http://examples.extjs.eu/?ex=download
感谢您的回复,我修改了我的代码:
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AppendHeader( "Content-Disposition", "attachment; filename=test.pdf");
using (MemoryStream myMemoryStream = new MemoryStream())
{
Document document = new Document();
PdfWriter PDFWriter = PdfWriter.GetInstance(document, myMemoryStream);
document.AddHeader("Content-Disposition", "attachment; filename=wissalReport.pdf");
document.Open();
//..........
document.Close();
byte[] content = myMemoryStream.ToArray();
HttpContext.Current.Response.Buffer = false;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AppendHeader("content-disposition","attachment;filename=" + "my_report.pdf");
HttpContext.Current.Response.ContentType = "Application/pdf";
//Write the file content directly to the HTTP content output stream.
HttpContext.Current.Response.BinaryWrite(content);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
但是我得到这个错误:
Uncaught Ext.Error: You're trying to decode an invalid JSON String:
%PDF-1.4 %���� 3 0 obj <</Type/XObject/Subtype/Image/Width 994/Height 185/Length 13339/ColorSpace/DeviceGray/BitsPerComponent 8/Filter/FlateDecode>>stream x���|E�
...........
我绝对确定我创建 pdf 的 itextsharp 是正确的,因为我可以将它保存在服务器上,但这不是我需要做的,当我尝试将它发送到客户端时,我得到了上面的错误
提前致谢
最佳答案
如果是 Web 应用程序,您可能希望将 pdf 作为二进制文件流式传输给用户,这将打开 pdf 或提示用户保存文件。
请记住 pdf 生成是在服务器上进行的,即使用户提供了它在服务器上也没有任何用处的路径。请参阅以下链接 -
在您的情况下,您正在生成文件,因此已经有了二进制流而不是文件,因此您可以直接使用 Response.BinaryWrite而不是 Response.WriteFile .
修改后的样本:
Response.Buffer = false;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
//Set the appropriate ContentType.
Response.ContentType = "Application/pdf";
//Write the file content directly to the HTTP content output stream.
Response.BinaryWrite(content);
Response.Flush();
Response.End();
关于c# - iTextSharp 生成的 PDF : How to send the pdf to the client and add a prompt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8505995/