2

Is there a way to open the save as window when saving webpage to PDF using iTextSharp? right now I'm just saving it to a set file.

var pdfDoc = new Document();

const string folderPath = "C:\\SG-ListingPDFs\\";

bool isExists = Directory.Exists(folderPath);

if (!isExists)
    Directory.CreateDirectory(folderPath);

var writer = PdfWriter.GetInstance(pdfDoc, new FileStream("C:\\SG-ListingPDFs\\" + detailsViewModel.ListingNumber + ".pdf", FileMode.Create));
pdfDoc.Open();

....Code Here

pdfDoc.Add(table);

TempData["SavedPdF"] = true;
pdfDoc.Close();
hutchonoid
  • 32,982
  • 15
  • 99
  • 104
NNassar
  • 485
  • 5
  • 11
  • 25
  • I've created a razor html to pdf library that may be of use to you too. See here: http://stackoverflow.com/questions/16517171/convert-html-to-pdf-in-mvc-with-itextsharp-in-mvc-razor/20198939#20198939 – hutchonoid Nov 27 '13 at 17:10
  • 1
    instead of asking the same question more than once, I'd suggest you do some research on this topic then come back if you run into a specific problem. http://stackoverflow.com/questions/20245553/website-using-itextsharp-needs-to-save-pdf-on-local-machine-c-drive – iamkrillin Nov 27 '13 at 18:25
  • They are two different thing. – NNassar Nov 29 '13 at 19:07

2 Answers2

1

You'll need to have an ActionResult method that returns a file and set the appropriate request headers.

public ActionResult Pdf()
{
    Response.AddHeader("Content-Disposition", "attachment;filename=YourFile.pdf");
    return File(yourPdfFile, "application/octet-stream");
}

File() has a few overloads that take either a byte[], a System.IO.Stream or the path to an actual file on disk. I'm not too familiar with iTextSharp so I can't help you much further, but this should send you on the right track.

If my memory serves me right, the header is needed in a specific browser (I'm thinking IE) to get the save as dialog to pop.

dom
  • 6,702
  • 3
  • 30
  • 35
0

I would create the stream as a referenced variable i.e.

var aFileName = string.Format("{0}.{1}", detailsViewModel.ListingNumber + "pdf";
var aStream =  new FileStream("C:\\SG-ListingPDFs\\" + aFileName);

Then pass it into the get instance like this:

var writer = PdfWriter.GetInstance(pdfDoc, aStream , FileMode.Create));

Then from your controller return the stream like this as a FileResult.

public ActionResult SaveFile()
{   
    // processing to get the file etc....

    return File(filePath, aStream , aFileName);
}

The important part in the above is the aFileName paramater, this is the fileNameDownload parameter which makes it open as a downloadable file.

hutchonoid
  • 32,982
  • 15
  • 99
  • 104