In my method in controller I use the following code to save pdf.
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlContent);
HtmlNode node = doc.GetElementbyId("DetailsToPDF");
HtmlToPdfConverter htmlToPdf = new HtmlToPdfConverter();
var pdfBytes = htmlToPdf.GeneratePdf("<html><body>" + node.InnerHtml + "</body></html>");
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment; filename=TEST.pdf");
Response.BinaryWrite(pdfBytes);
Response.Flush();
Response.End();
Everything has passed without any exceptions in debugger. However file is not saved. What am I doing wrong?
The recommended way to return a File in ASP.NET MVC is using the File() helper method:
public ActionResult Download()
{
// Starting with pdfBytes here...
// ...
var pdfBytes = htmlToPdf.GeneratePdf("<html><body>" + node.InnerHtml + "</body></html>");
var contentDisposition = new System.Net.Mime.ContentDisposition
{
FileName = "TEST.pdf",
Inline = false
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
return File(pdfBytes, "application/pdf");
}
string path = Server.MapPath("~/Content/files/newPDFFile.pdf");
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + "PDFfile.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(buffer);
Response.End();
}
Related
I am trying to export the Gridview data to docx, but it doesnot work.
public static void SendToUserWord(GridView grid, string fileName, string type)
{
var response = HttpContext.Current.Response;
response.Clear();
response.AddHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", fileName));
response.Charset = "";
response.ContentType = type == "doc" ? "application/vnd.ms-word" : "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
response.ContentEncoding = Encoding.Default;
response.Write("<head><meta http-equiv=\"content-type\" content=\"text/html; charset="
+ Encoding.Default.WebName + "\"></head>");
response.Write(#"<style> td { mso-number-format:\#; } </style>");
using (var writer = new HtmlTextWriter(response.Output))
{
grid.RenderControl(writer);
}
response.End();
}
How do export to doxc?
when I click on it my file doesn't open properly enter image description here
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
// Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
Response.AddHeader("Content-Disposition", "inline; filename"+Path.GetFileName(filePath)+".pdf");
Response.WriteFile(filePath);
Response.End();
}
You can try this code to get your work done,
string pdfPath = Server.MapPath("~/SomePDFFile.pdf");
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(pdfPath);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
I wrote some code for making PDF from HTML with pechkin and pechkin.synchronized.
It will work very well at first time.
Since second time, images are disappeared in pdf.
Other [html to pdf]s are too. First pdf is right. Other pdfs are not.
At the first time in server, it will work.
Maybe because pechkin will not unload in memory. I think.
I need help.
System.IO.File.WriteAllText(textfilepath, html);
GlobalConfig gc = new GlobalConfig();
ObjectConfig oc = new ObjectConfig()
.SetLoadImages(true)
.SetZoomFactor(1.0)
.SetPrintBackground(true)
.SetScreenMediaType(true)
.SetCreateExternalLinks(true)
.SetAllowLocalContent(true)
.SetPageUri(url);
IPechkin pechkin = new Pechkin.Synchronized.SynchronizedPechkin(gc);
pdf = pechkin.Convert(oc);
using NReco.ImageGenerator;
using NReco.PdfGenerator;
//아래 주석들을 잘 여닫으면 jpg로 저장할 수 있다.
/*
'C:\inetpub\wwwroot\...\bin\wkhtmltopdf.exe' 경로에 대한 액세스가 거부되었습니다.
'C:\inetpub\wwwroot\...\bin\msvcp120.dll' 경로에 대한 액세스가 거부되었습니다.
'C:\inetpub\wwwroot\...\bin\msvcr120.dll' 경로에 대한 액세스가 거부되었습니다.
위 세 파일을 해당 경로에 넣어 주면 정상 작동한다.
*/
string article_no = Request["article_no"];
//string[] urlArray = Request["url"].Split('/');
//string textfilename = Guid.NewGuid().ToString() + ".html";
//string url = urlArray[0] + "//" + urlArray[2] + "/storage/print/" + textfilename;
//string textfilepath = Server.MapPath("/storage/print/" + textfilename);
string html = "<html>"+HttpUtility.UrlDecode(Request["html"])+"</html>";
//string jpgpath = Server.MapPath("/storage/print/") + article_no + ".jpg";
string pdfpath = Server.MapPath("/storage/print/") + article_no + ".pdf";
try
{
//byte[] jpg;
byte[] pdf;
//if (System.IO.File.Exists(jpgpath))
if (System.IO.File.Exists(pdfpath))
{
//jpg = System.IO.File.ReadAllBytes(jpgpath);
pdf = System.IO.File.ReadAllBytes(pdfpath);
}
else
{
#region Transform the HTML into PDF
//System.IO.File.WriteAllText(textfilepath, html);
//jpg
/*
var htmlToImageConv = new HtmlToImageConverter();
jpg = htmlToImageConv.GenerateImage(html, ImageFormat.Jpeg);
//jpg = htmlToImageConv.GenerateImageFromFile(textfilepath, ImageFormat.Jpeg);
*/
//pdf
var htmlToPdf = new HtmlToPdfConverter();
pdf = htmlToPdf.GeneratePdf(html);
//htmlToPdf.GeneratePdfFromFile(url, null, pdfpath);
System.IO.File.WriteAllBytes(pdfpath, pdf);
//System.IO.File.Delete(textfilepath);
#endregion
}
#region Return the pdf file
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
//Response.AddHeader("Content-Disposition", string.Format("attachment;filename={1}.jpg; size={0}", jpg.Length, article_no));
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={1}.pdf; size={0}", pdf.Length, article_no));
Response.BinaryWrite(pdf);
Response.Flush();
Response.End();
#endregion
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");
}
}