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
Related
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();
}
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 am looking to write an image into doc file ..
here is the code that i am trying...
string imageFolder = System.Web.Configuration.WebConfigurationManager.AppSettings["coverLetterPath"].ToString();
string imageName = "images.jpg";
string path1 = Path.Combine(imageFolder, imageName);
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path1))
{
sw.WriteLineAsync(imageName);
}
string fileName = string.Empty;
fileName = "BodyContent_" + DateTime.Now.ToString("ddMMMyyy_HHmmss_fff") + ".docx";
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(path1);
Response.Flush();
Response.End();
here the file that i am creating is downloaded but the image is not loaded into that file.. getting a message when i open the doc as File is corrupted
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 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