NReco PdfGenerator customize output path c# - c#

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);

Related

Post Back not occuring after pdf is downloaded

I've developed a pdf file using itextsharp.
Pdf generation is working fine. After the pdf is created it's being downloaded.
My problem is when the user clicks on Generate PDF button , Pdf is generated and downloaded properly but postback doesn't occurs.
I want the postback to be occured because I want to Reset my Form after Pdf is generated that is Clear All Fields .
How Can I do this ?
Here is my code :
Method to Generate PDF :
public void GetPDF(string quote_num)
{
string url = FilesPath.Path_SaveFile + Session["empcd"].ToString() +"-Quotation.pdf";
Document disclaimer = new Document(PageSize.A4, 2, 2, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(disclaimer, new FileStream(url, FileMode.Create));
writer.PageEvent = new myPDFpgHandler(quote_num);
disclaimer.SetMargins(70, 10, 60, 80);
disclaimer.Open();
GenerateQuotPDF getpdf = new GenerateQuotPDF();
disclaimer = getpdf.GetPDFparams(disclaimer,quote_num, Session["empcd"].ToString(),txt_contactperson.Text,txt_contact1.Text,txt_company.Text,txt_address.Text,ddl_gene_desc.SelectedItem.ToString(),ddl_canopy.SelectedItem.ToString(),ddl_gene_type.SelectedItem.ToString(),txt_rentalamount.Text,txt_hours.Text,txt_variable.Text,ddl_terms.SelectedItem.ToString(),txt_remarks.Text,txt_technical.Text,ddl_sign1.SelectedValue,ddl_sign2.SelectedValue,txt_designation.Text,DateTime.Now);
disclaimer.Close();
System.IO.FileInfo file = new System.IO.FileInfo(url);
if (file.Exists)
{
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(url);
Response.AddHeader("content-disposition", "attachment; filename=" + Session["empcd"].ToString() + "-Quotation.pdf");
Response.AddHeader("content-length", buffer.Length.ToString());
Response.ContentType = "application/pdf";
Response.BinaryWrite(buffer);
}
}
Generate PDF Button Code :
protected void btn_submit_Click(object sender, EventArgs e)
{
if (IsValidQuotation())
{
string newQuotNum = rental_quotations.GetNewQuotNumber();
rental_quotations.AddNewQuotation(newQuotNum, Session["empcd"].ToString(), ddl_gene_type.SelectedValue.ToString(), ddl_gene_desc.SelectedValue, ddl_canopy.SelectedValue, txt_company.Text, txt_address.Text, txt_contactperson.Text, txt_designation.Text, txt_contact1.Text, txt_contact2.Text, txt_rentalamount.Text, ddl_terms.SelectedValue, txt_hours.Text, txt_variable.Text, txt_remarks.Text,ddl_sign1.SelectedValue,ddl_sign2.SelectedValue,txt_technical.Text);
GetPDF(newQuotNum);
ClearAllFields(); //this is not working
}
}
Postback is occurring since the file is being created. Try the given solution. Your GetPDF(string quote_num) function is doing two tasks that you should break into two functions.
Creating the pdf document.
Downloading the pdf file after it is done.
Now, After you have created the document, you should clear the controls and then send the file as response. Therefore do it as follows:
Create pdf file.
public void CreatePDF(string quote_num)
{
string url = FilesPath.Path_SaveFile + Session["empcd"].ToString() +"-Quotation.pdf";
Document disclaimer = new Document(PageSize.A4, 2, 2, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(disclaimer, new FileStream(url, FileMode.Create));
writer.PageEvent = new myPDFpgHandler(quote_num);
disclaimer.SetMargins(70, 10, 60, 80);
disclaimer.Open();
GenerateQuotPDF getpdf = new GenerateQuotPDF();
disclaimer = getpdf.GetPDFparams(disclaimer,quote_num, Session["empcd"].ToString(),txt_contactperson.Text,txt_contact1.Text,txt_company.Text,txt_address.Text,ddl_gene_desc.SelectedItem.ToString(),ddl_canopy.SelectedItem.ToString(),ddl_gene_type.SelectedItem.ToString(),txt_rentalamount.Text,txt_hours.Text,txt_variable.Text,ddl_terms.SelectedItem.ToString(),txt_remarks.Text,txt_technical.Text,ddl_sign1.SelectedValue,ddl_sign2.SelectedValue,txt_designation.Text,DateTime.Now);
disclaimer.Close();
}
Reset the controls.
ClearAllFields();
Send the file as response.
public void SendPDF(string url)
{
System.IO.FileInfo file = new System.IO.FileInfo(url);
if (file.Exists)
{
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(url);
Response.AddHeader("content-disposition", "attachment; filename=" + Session["empcd"].ToString() + "-Quotation.pdf");
Response.AddHeader("content-length", buffer.Length.ToString());
Response.ContentType = "application/pdf";
Response.BinaryWrite(buffer);
Response.End();
}
}
Note that I also added Response.End() to clear the buffer.

Excel sheet does not display exported chart image - ASP.NET

I have a web page in my website that allows me to download the chart from that page and add it to an excel sheet. However, a red x button with the words: "this image cannot currently be displayed" is shown in place of the chart. I have tried many solutions online but all of them show the same outcome.
Here are my codes:
protected void ExcelDl_Click(object sender, EventArgs e) {
string tmpChartName = "test2.jpg";
string imgPath = HttpContext.Current.Request.PhysicalApplicationPath + tmpChartName;
Chart1.SaveImage(imgPath);
string imgPath2 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/" + tmpChartName);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
string headerTable = #"<Table><tr><td><img src='" + imgPath2 + #"' \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(sw.ToString());
Response.End();
}
Any form of help will be greatly appreciated. Also, do note that I have added the required codes in my Web.config.
We have tried your program and here it’s working fine. Excel downloaded along with image. I have installed in iis and tried with many client machine and it was working fine.
Not sure what’s going on your end. The problem might be wrong image path reference will cause this problem. Print image URL and make sure whether it is correct or not.
Alternate method: instead of using html tags inside the excel cell use XML closing method to render the image inside the excel cell.
Here I have added sample code for the Closed XML methods to render the image in excel. to use this code need to refer the following DLLs
1. ClosedXML.dll
2. WindowsCore.dll
3. DocumentFormat.OpenXML.dll
4. PresentationCore.dll
Reference Link for Closed XML methods: https://closedxml.codeplex.com/
using (XLWorkbook wb = new XLWorkbook())
{
IXLWorksheet WorkSheet = new IXLWorksheet();
string LogoPath = Server.MapPath("~/App_Themes/Images/logonew.png");
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(LogoPath);
if (bitmap != null)
{
var stream = new System.IO.MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
if (stream != null)
{
stream.Position = 0;
XLPicture pic = new XLPicture
{
NoChangeAspect = true,
NoMove = true,
NoResize = true,
ImageStream = stream,
Name = "Logo",
EMUOffsetX = 4,
EMUOffsetY = 6
};
XLMarker fMark = new XLMarker
{
ColumnId = 1,
RowId = 1
};
pic.AddMarker(fMark);
WorkSheet.AddPicture(pic);
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=test.xls");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
Please check and let me know your comments.

Images disappeared in PDF made by Pechkin.Synchronized

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 to download Pdf to client machine

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);

download multiple pdf

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

Categories

Resources