My requirement is as : we have to open a PDF file in new tab. file is opened in new tab successfully, but we want to open 5th page instead-of 1st page. can we achieve it by using c sharp.
My code is below to open pdf in new tab:
MemoryStream stream = new MemoryStream();
stream.Write(fileData, 0, fileData.Length);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
string fileName = System.Web.HttpUtility.UrlEncode(yderInfo, System.Text.UTF8Encoding.UTF8).Replace("+", " ");
HttpContext.Current.Response.AppendHeader("Content-Disposition", "inline; attachment;filename*=UTF-8''" + fileName + ".pdf");
HttpContext.Current.Response.OutputStream.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
HttpContext.Current.Response.End();
Try using PDF.js(https://mozilla.github.io/pdf.js/) to display your doc in browser and use the below property to set the page.
PDFView.initialBookmark = "page=5";
Related
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";
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);
I have successfully implemented the iTextSharp.text.pdf to populate a PDF template file we have setup. Currently that file is being save automatically to a specific folder on local machine...but we don't want that, we want the populated PDF to be saved by the user to the folder of their choice on their pc. We do not want to keep any of these files on the server once this application gets published.
the below code creates the hardcoded file path and it is populated, but the portion at the bottom that prompts the user to save the file, creates a pdf with the file name format we want, but the file is always 20k and wont open. How can I change the below code to not actually create the file on the server, but to create it to the users pc when they chose to save it?
using (FileStream outfile = new FileStream(outputfile, FileMode.Create))
{
PdfReader rdr = new PdfReader(pdftemplate);
PdfStamper stm = new PdfStamper(rdr, outfile);
AcroFields fields = stm.AcroFields;
foreach (var de in rdr.AcroFields.Fields)
{
if (de.Key == "Date")
{
fields.SetField("Date", dt.Rows[0]["Form Date"].ToString());
}
if (de.Key == "Project Name")
{
fields.SetField("Project Name", dt.Rows[0]["Project Name"].ToString());
}
if (de.Key == "Contract No")
{
fields.SetField("Contract No", dt.Rows[0]["Contract Number"].ToString());
}
}
stm.Close();
rdr.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + newFile);
Response.Write(outfile);
Response.End();
}
I think the problem with your code is that you are using filestream which is causing the pdf to be saved to your server. Using memorystream should fix this. Try something like this and see if it helps.
Using (MemoryStream ms = new MemoryStream())
{
PdfReader rdr = new PdfReader(pdftemplate);
PdfStamper stm = new PdfStamper(rdr, ms);
AcroFields fields = stm.AcroFields;
foreach (var de in rdr.AcroFields.Fields)
{
if (de.Key == "Date")
{ fields.SetField("Date", dt.Rows[0]["Form Date"].ToString()); }
if (de.Key == "Project Name")
{ fields.SetField("Project Name", dt.Rows[0]["Project Name"].ToString()); }
if (de.Key == "Contract No")
{ fields.SetField("Contract No", dt.Rows[0]["Contract Number"].ToString()); }
}
stm.Close();
rdr.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=MyFile.pdf");
//To display pdf in the browser window instead of saving, change attachment to inline
Response.BinaryWrite(ms.ToArray());
Response.End();
}
By using MemoryStream along with html headers, you should get a prompt to save the file.
I've a handler in asp.net app. When there comes some kind of request I want user to get download window, where I put PDF stream. I don't want PDF to be saved in memory.
I have the following code, but it fails to open, says pdf file was demaged and couldn't open it.
tell me other way to achieve my goal if you think mine is not good.
MemoryStream stream = new MemoryStream();
CreatePFD(T.Text, stream);
context.Response.Write(stream);
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("content-disposition", "attachment; filename=" + "Nots__Saved__FIle__fileName.pdf");
Now I have this code:
Document Doc = new Document(PageSize.A4, 80, 50, 30, 65);
System.IO.Stream outputStream = new System.IO.FileStream(#"C:\inetpub\wwwroot\c\wefwe.pdf", System.IO.FileMode.OpenOrCreate);
PdfWriter.GetInstance(Doc, outputStream);
Doc.Open();
List<IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(T.Text), null);
for (int k = 0; k < htmlarraylist.Count; k++)
{
Doc.Add((IElement)htmlarraylist[k]);
}
outputStream.CopyTo(context.Response.OutputStream);
Doc.Close();
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("content-disposition", "attachment; filename=" + "Nots__Saved__FIle__fileName.pdf");
when i save pdf, the file is correct...
but when I get response the file is in correct. demaged...
You need to rewind the stream by setting stream.Position = 0.
Also, Response.Write(stream) will just print stream.ToString().
Instead, you should call stream.CopyTo(Response.OutputStream).
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