I created a Location to save converted PDF from asp.net like this:
public string fileUploadLoc = ConfigurationManager.AppSettings["PDFFileLoc"];
//set from web.config eg: d:/temp/employeeData
DirectoryInfo destination = new DirectoryInfo(Server.MapPath("~/" + fileUploadLoc));
Directory.CreateDirectory(Server.MapPath("~/" + fileUploadLoc));
destination = new DirectoryInfo(Server.MapPath("~/" + fileUploadLoc));
destination.Create();
and i converted asp.net page to PDF. How to save this converted PDF to the specified Location.? Please help me.
use this before serializing the file into the response stream:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/pdf";
//HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.HeaderEncoding = Encoding.UTF8;
System.IO.FileStream file = new System.IO.FileStream(Server.MapPath("~/" + fileUploadLoc" System.IO.FileMode.OpenOrCreate);
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, file);
Related
I'm using the free version of NReco to convert html to pdf. The pdf is downloaded in default folder "Downloads". I need to customize it. Can anyone help me?
Thanks!
Edit:
The code that downloads the pdf in default folder was:
var pdfBytes = pdfConverter.GeneratePdf(strHtml);
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment; filename=TEST.pdf");
Response.BinaryWrite(pdfBytes);
Response.TransmitFile(output_path_pdf);
Response.Flush();
Response.End();
This solution don't downloads the PDF as an attachment, but downloads it directly in the selected path, and it solves my problem.
string output_path_pdf = HttpContext.Server.MapPath("~/PDF_RESULT/" + fileName + ".pdf");
HtmlToPdfConverter pdfConverter = new HtmlToPdfConverter();
pdfConverter.PageWidth = 1000;
pdfConverter.PageHeight = 800;
pdfConverter.Margins = new PageMargins { Top = 0, Bottom = 0, Left = 0, Right = 0 };
pdfConverter.GeneratePdfFromFiles(new string[] { URL }, null, output_path_pdf);
I want to export a file from a specific folder which the client will download. My code is below:
string Name = UserID + "HistoricalRecords.csv";
string fileName = "C:\\Temp\\"+Name;
TextWriter textWriter = new StreamWriter(fileName);
/*Some codes which add data to the csv.*/
byte[] bytes = Encoding.ASCII.GetBytes(textWriter.ToString());
if (bytes != null)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Content-Length", bytes.Length.ToString());
HttpContext.Current.Response.AppendHeader("Content-Disposition", "Attachment; Filename=" + fileName + "");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
The file is created with the good content in the specified folder.
However, the file which the client is downloading is not the file from the specific folder "C:\Temp\" with the data as content. It is just creating a new file with the name= UserID + "HistoricalRecords.csv" and with no content. Any idea how to fix this?
You are not sending the file created to the client. Replace
HttpContext.Current.Response.BinaryWrite(bytes);
with
HttpContext.Current.Response.WriteFile(fileName);
Try this
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "application/CSV";
How do i download a file in asp.net?
here is what i did to upload it:
I upload the file into the website and saved the url to it in a database like this:
string CVPath = null;
if (uploadfiles.HasFile)
{
string file = uploadfiles.FileName;
uploadfiles.PostedFile.SaveAs(Server.MapPath(".") + "//CV//" + file);
CVPath = "~//ProfileImages//" + file;
FileName.InnerText = file;
}
else
CVPath = "";
and then I save the "CVPath" in a database
To download a file, first you need to read all the contents to a string.
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
tw.WriteLine("YourString");
tw.Flush();
byte[] bytes = ms.ToArray();
ms.Close();
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=file.txt");
Response.BinaryWrite(bytes);
Response.End();
I use TransmitFile and WriteFile to write an Excel File, but anyone does not work correctly
my code is :
// Get the Physical Path of the file(test.doc)
string filepath = newFilePath;
// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(filepath);
// Checking if file exists
if (file.Exists)
{
// Clear the content of the response
HttpContext.Current.Response.ClearContent();
// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name));
// Add the file size into the response header
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
HttpContext.Current.Response.TransmitFile(file.FullName);
}
FileStream sourceFile = new FileStream(file.FullName, FileMode.Open);
float FileSize;
FileSize = sourceFile.Length;
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)sourceFile.Length);
sourceFile.Close();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Length", getContent.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
HttpContext.Current.Response.BinaryWrite(getContent);
I would simplify it to this instead:
public ActionResult ExcelDoc(string newFilePath)
{
string filepath = newFilePath;
// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(filepath);
// Checking if file exists
if (file.Exists)
{
var fileBytes = System.IO.File.ReadAllBytes(filepath);
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name));
return File(new MemoryStream(fileBytes), "application/vnd.ms-excel");
}
else
{
return Content("File does not exist");
}
}
I am trying to download multiple pdf's as attachments in my asp.net application.I have created some templates and filling values using pdfstamper(itextsharp). I am able to fill the values but not able to download.
private void FillForm(string path, DataTable BridgeValues, DataTable Comments, DataTable Maintenance,string Newfilename)
{
try
{
string pdfTemplate = path;
string newFile = Newfilename;
string Pathser = "";
if (!System.IO.Directory.Exists(Server.MapPath(#"~/PDF/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath(#"~/PDF/"));
}
if (Directory.Exists(Server.MapPath(#"~/PDF/")))
{
Pathser = Server.MapPath(#"~/PDF/" + Newfilename);
}
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
// create a new PDF reader based on the PDF template document
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(Pathser, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
DataColumn dc = null;
for (int i = 0; i < BridgeValues.Columns.Count - 1; i++)
{
dc = BridgeValues.Columns[i];
pdfFormFields.SetField(dc.ColumnName.ToString(), BridgeValues.Rows[0][dc].ToString());
}
pdfStamper.FormFlattening = true;
// close the pdf
pdfStamper.Close();
////Response.ContentType = "application/octet-stream";
Response.ContentType = "application/pdf";
////Response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf");
Response.AddHeader("Content-Disposition", "attachment; filename=" + Newfilename + "");
////Response.BinaryWrite(mStream.ToArray());
Response.TransmitFile(Server.MapPath(("~/PDF/"+ Newfilename)));
Response.Clear();
Response.End();
}
catch (System.Threading.ThreadAbortException lException)
{
// do nothing
}
}
First time I tried to create one pdf ,it worked but later when I tried to download multiple files it gave an execption.
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
I don't think you can download multiple files by making one request and returning a collection from the action. I would suggest that it you need to allow user to download multiple files you ZIP them and stream the archive down to the browser.
Here is an example of zipping multiple files: http://devpinoy.org/blogs/keithrull/archive/2008/01/25/how-to-create-zip-files-in-c-with-sharpziplib-ziplib.aspx