Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
This you use when saving to pdf using asp.net but i am using win forms

how should i write Response. because in win forms it doesnt work.
why? what should i use?

C#
using (MemoryStream ms = new MemoryStream())
using(Document document = new Document(PageSize.A4, 25, 25, 30, 30))
using(PdfWriter writer = PdfWriter.GetInstance(document, ms))
{
    document.Open();
    document.Add(new Paragraph("Hello World"));
    document.Close();
    writer.Close();
    ms.Close();
    Response.ContentType = "pdf/application";
    Response.AddHeader("content-disposition", "attachment;filename=First_PDF_document.pdf");
    Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}
Posted
Comments
Sergey Alexandrovich Kryukov 25-Feb-14 11:41am    
Not clear at all. How is that: "saving to pdf using asp.net but i am using win forms"?
—SA
phil.o 25-Feb-14 11:53am    
It simply means he got some code working on server side in an ASP.NET project, and would like to use it in a Winforms application (thus, no Response object whatsoever) :)
Sergey Alexandrovich Kryukov 25-Feb-14 12:07pm    
Of course... :-)
Thank you, Phil.
—SA

1 solution

You can use a stream other than a memory-one (for example, a binary file stream) and write to it.

This could look like:
C#
using (FileStream fs = File.Open("First_PDF_document.pdf"))
using(Document document = new Document(PageSize.A4, 25, 25, 30, 30))
using(PdfWriter writer = PdfWriter.GetInstance(document, fs))
{
    document.Open();
    document.Add(new Paragraph("Hello World"));
    document.Close();
    writer.Close();
    fs.Close();
}


This way you do not construct a Response object (relative to web connections), but rather an actual file on your filesystem.

Hope this helps.

PS: you may have to adapt the content of using blocks a little bit; I currently have no IDE installed on my computer, so unable to test for that piece of code.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 25-Feb-14 12:08pm    
Good answer, a 5.
—SA
phil.o 26-Feb-14 2:35am    
Thank you Sergey :)
Kurac1 26-Feb-14 0:55am    
Hi , i doesnt work. How should i open a file that doesnt exists?
Usign this code FileStream fs = new FileStream("KundLista.Pdf", FileMode.Create);
It creates the document by it self in debug folder. but i dont want to create in i debug i want to create in memory and then open up the file from the memory
phil.o 26-Feb-14 2:34am    
Sorry, I never tried to open any file from an in-memory byte array; I'm afraid I cannot help you for this part.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900