直接通过代码打开生成的pdf文件,无需保存到磁盘 [英] Open Generated pdf file through code directly without saving it onto the disk
本文介绍了直接通过代码打开生成的pdf文件,无需保存到磁盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 Sharepoint 2010 并且我正在开发一个 Web 部件,其中在按钮单击事件中,需要生成并直接打开 pdf 文件.不应该保存到磁盘上.我试过下面的代码
I use Sharepoint 2010 and I am developing a web part where on a button click event, a pdf file needs to be generated and opened directly. Should not be saving onto the disk. I tried the below code
protected void Button1_OnClick(object sender, EventArgs e)
{
Document myDoc = new Document(PageSize.A4.Rotate());
try
{
PdfWriter.GetInstance(myDoc, new FileStream(@"C:DirectoryTest.pdf", FileMode.Create));
myDoc.Open();
myDoc.Add(new Paragraph("Hello World"));
}
catch (DocumentException ex)
{
Console.Error.WriteLine(ex.Message);
}
myDoc.Close();
}
我也尝试了下面的代码,它也在服务器上生成了我不想要的文件.
I also tried the below code which also generates the file on the Server which I dont want.
Document document = new Document(PageSize.A4);
PdfWriter.GetInstance(document, new FileStream(HttpContext.Current.Server.MapPath("~/Test.pdf"), FileMode.Create));
document.Open();
var WelcomePara = new Paragraph("Hello World");
document.Add(WelcomePara);
document.Close();
这是在桌面上创建pdf文件,我需要以pdf格式打开它.有人可以帮我吗.
This one creates the pdf file on the desktop, I need it to be opened in the pdf format.Can someone help me please.
推荐答案
我终于让它工作了.
using (var ms = new MemoryStream())
{
using (var document = new Document(PageSize.A4,50,50,15,15))
{
PdfWriter.GetInstance(document, ms);
document.Open();
document.Add(new Paragraph("HelloWorld"));
document.Close();
}
Response.Clear();
//Response.ContentType = "application/pdf";
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment;filename= Test.pdf");
Response.Buffer = true;
Response.Clear();
var bytes = ms.ToArray();
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.OutputStream.Flush();
}
这篇关于直接通过代码打开生成的pdf文件,无需保存到磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文