ASP.NET MVC open pdf file in new window - asp.net-mvc

I have a MVC application. I need to open the pdf file when user clicks the open button on the page. The filepath where the pdf is stored is read from the database and it is a file on c:. How do I open it in my html code? I have this code:
Open
but this doesn't open my file. What do I have to do? I need to specify somewhere that it is a pdf??

You will need to provide a path to an action that will receive a filename, resolve the full path, and then stream the file on disk from the server to the client. Clients out in the web, thankfully, cannot read files directly off your server's file system (unless... are you suggesting #Model.CertificatePath is the path to the file on the remote user's machine?).
public ActionResult Download(string fileName)
{
string path = Path.Combine(#"C:\path\to\files", fileName);
return File(path, "application/pdf");
}
Update
If #Model.CertificatePath is the location on the client's actual machine, try:
Open
Note that some browsers may have security settings disallowing you from opening local files.

Try like this in your View
#Html.ActionLink("View", "ViewPDF", new { target = "_blank" })
Now Link will open in new window. You can write the pdf bytes in ViewPDF controller method

You could have the link fire a method such as the one below which will then stream your chosen file to the file download rather than opening the pdf in the broswer.
/// <summary>
/// Forces a file to be displayed to the user for download.
/// </summary>
/// <param name="virtualPath"></param>
/// <param name="fileName"></param>
public static void ForceDownload(string virtualPath, string fileName)
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.AddHeader("content-disposition", "attachment; filename=" + fileName);
response.WriteFile(virtualPath);
response.ContentType = "";
response.End();
}

Well if your getting the path value and the value is in #Model.CertificatePath
this wiil not work
Open
You will need to add this
Open
and make sure you path is relative by adding this ~
for example if your path is /Content/pdfs/CertificatePath.pdf
it would need to look like
~/Content/pdfs/CertificatePath.pdf
This should be the simplest way to make it work.
Hope this helps.

Unfortunately you can't dictate where the PDF will be opened, mainly because you can't guarantee the Adobe Acrobat reader plugin is installed or how it functions.
You could in theory open a new window, and in that new window have a JavaScript function to open the PDF file, but again you can't guarantee it will open in a embedded window without the plugin, the best you can hope for is "best try".

Related

PDF JS, from file location

I have successfully set up using the viewer with the following code:
protected void btnShowPDFS_OnClick(object sender, EventArgs e)
{
// Display all files.
string[] files = Directory.GetFiles(#"D:\Reports\2014\July\", "*.PDF");
var pdfNames = new List<string>();
foreach (string file in files)
{
string fileName = Path.GetFileName(file);
string queryString = "/web/viewer.html?file=" + System.Web.HttpUtility.UrlEncode("../July/" + fileName);
pdfNames.Add(queryString);
}
listView.DataSource = pdfNames;
listView.DataBind();
}
Now, this all works fine if all my PDF's are in a folder within the website (i.e localhost). However, how do i point the view to either a network share, or just another folder on the same machine, but outside of IIS?
A browser's XMLHttpRequest might have a restrictions for local files access (Firefox has more relaxed policy for local file than other browsers).
PDF.js is using XHR; and PDF.js also allows "load" files from a typed array (Uint8Array). You can use the latter in your solution. Notice the Internet Explorer (WebBrowser control) has window.external that can be used to transmit the data from the host application, see http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting(v=vs.110).aspx

Primefaces data exporter

I am using p:dataExporter to export the data to client machine. It creates a file in given format based on the data from table mentioned in the tareget method. On export button click file would be exported to client machine.This all goes fine.
Now I want to provide an 'open' button to let open the file with/without downloading the file to client machine. p:dataExporter dont have such property. Does JSF provide such property or any other component recommended?
Here is my code sample,
<p:dataExporter type="#{applicationFilterBean.exportFileType}" target=":appForm:appTable"
fileName="#{applicationFilterBean.exportFileName}" />
Thanks for your suggestion Michele, I have created my customExport class. The only change needed was to change responseHeader to Content-Disposition-inline,
response.setHeader("Content-disposition", "inline;filename="+ fileName + ".pdf");
This is working absolutely fine.
no it is not possible because content-disposition is hardcode.
for example, look through org.primefaces.component.export.PDFExporter source code:
protected void writePDFToResponse(ExternalContext externalContext, ByteArrayOutputStream baos, String fileName) throws IOException, DocumentException {
externalContext.setResponseContentType("application/pdf");
externalContext.setResponseHeader("Expires", "0");
externalContext.setResponseHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
externalContext.setResponseHeader("Pragma", "public");
externalContext.setResponseHeader("Content-disposition", "attachment;filename="+ fileName + ".pdf");
externalContext.setResponseContentLength(baos.size());
externalContext.addResponseCookie(Constants.DOWNLOAD_COOKIE, "true", Collections.<String, Object>emptyMap());
OutputStream out = externalContext.getResponseOutputStream();
baos.writeTo(out);
externalContext.responseFlushBuffer();
}
maybe some other library provide this feature, otherwise you should develop your own DataExporter.

How to show a pdf file in the browser tab from an action method

I'm trying to do pdf viewer functionality in mvc application. When user click the "read the pdf" link it should open a new tab/window and user should be able view the pdf file. So I checked the examples but I couldn't find. Could you suggest me any article or example ?
Show an anchor tag in your first view and pass an id (to identify what PDF to show)
#Html.ActionLink("read the pdf","view","doc",new { #id=123},null)
Now in the doc controller, have an action method which have a parameter called id and return the pdf there using the File method.
public ActionResult View(int id)
{
byte[] byteArrayOfFile=GetFieInByteArrayFormatFromId(id);
return File(byteArrayOfFile,"application/pdf");
}
Assuming GetFileInByteArrayFormatFromId is the method which returns the byte array format of the PDF file.
You can also return the PDF if you know the full path to the PDF file physically stored, using this overload.
public ActionResult Show()
{
string path="FullPAthTosomePDFfile.pdf";
return File(path, "application/pdf","someFriendlyName.pdf");
}
Show the PDF in a browser without downloading it
Based on the browser setting of the end user, the above solution will either ask user whether he/she wishes to download or open the file or simply download/open the file. If you prefer to show the file content directly in the browser without it gets downloaded to the user's computer, you may send a filestream to the browser.
public ActionResult Show(int id)
{
// to do : Using the id passed in,build the path to your pdf file
var pathToTheFile=Server.MapPath("~/Content/Downloads/sampleFile.pdf");
var fileStream = new FileStream(pathToTheFile,
FileMode.Open,
FileAccess.Read
);
return new FileStreamResult(fileStream, "application/pdf");
}
The above code expects you to have a pdf file named sampleFile.pdf in ~/Content/Downloads/ location. If you store the file(s) with a different name/naming convention, you may update the code to build the unique file name/path from the Id passed in.
If you want to display the PDF Content in browser, you can use iTextShare dll.
Refer the link http://www.codeproject.com/Tips/387327/Convert-PDF-file-content-into-string-using-Csharp.
Reading PDF content with itextsharp dll in VB.NET or C#

application/pdf object opening in adobe reader but not in firefox browser tab asp.net mvc

I have my controller action method returning pdf file as
public FileContentResult GetPDF(string filename)
{FileContentResult filecontent= new FileContentResult(Contents, "application/pdf");
HttpContext.Response.AddHeader("Content-Disposition", "inline; filename=" + filename);
return filecontent;
}
here Contents is byte[] type.
If in my Adobe reader Edit->Preferences->Internet unchecked the "Display PDF in the browser" opens file but not with the filename in Adobe Reader. and if I checked that then it is not opening in Browser Tab for this I also tried with opening pdf file from a website it opened it browser tab so no issues with browser.
I need to be able to open pdf in browser tab with file name. can anybody help me because i find no solution after lot of search. Is iframe setting needed?
try this if it works,
return File(filecontent,mimetype,filename);
or use FileStreamResult , idon't what exactly it does but try ,may works
regards,
kris

Why doesn't my PDF document render/download in ASP.NET MVC2?

I have an ASP.NET MVC2 application in development and I am having problems rendering a .pdf file from our production server.
On my Visual Studio 2010 integrated development server everything works fine, but after I publish the application to the production server, it breaks. It does not throw any exceptions or errors of any kind, it simply does not show the file.
Here's my function for displaying the PDF document:
public static void PrintExt(byte[] FileToShow, String TempFileName,
String Extension)
{
String ReportPath = Path.GetTempFileName() + '.' + Extension;
BinaryWriter bwriter =
new BinaryWriter(System.IO.File.Open(ReportPath, FileMode.Create));
bwriter.Write(FileToShow);
bwriter.Close();
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = ReportPath;
p.StartInfo.UseShellExecute = true;
p.Start();
}
My production server is running Windows Server 2008 and IIS 7.
You cannot expect opening the default program associated with PDF file browsing on the server. Try returning the file into the response stream which will effectively open it on the client machine:
public ActionResult ShowPdf()
{
byte[] fileToShow = FetchPdfFile();
return File(fileToShow, "application/pdf", "report.pdf");
}
And now navigate to /somecontroller/showPdf. If you want the PDF opening inside the browser instead of showing the download dialog you may try adding the following to the controller action before returning:
Response.AddHeader("Content-Disposition", "attachment; filename=report.pdf");
i suggest you use ASP.NET MVC FileResult Class to display the PDF.
see http://msdn.microsoft.com/en-us/library/system.web.mvc.fileresult.aspx
your code open`s the PDF on the webserver.
Here's how I did it.
public ActionResult PrintPDF(byte[] FileToShow, String TempFileName, String Extension)
{
String ReportPath = Path.GetTempFileName() + '.' + Extension;
BinaryWriter bwriter = new BinaryWriter(System.IO.File.Open(ReportPath, FileMode.Create));
bwriter.Write(FileToShow);
bwriter.Close();
return base.File(FileToShow, "application/pdf");
}
Thank you all for your efforts. Solution I used is the most similar to the Darin's one (almost the same, but his is prettier :D), so I will accept his solution.
Vote up for all of you folks (both for answers and comments)
Thanks

Resources