Open PDF in a new tab in browser - asp.net-mvc

Never done this before so not sure what is involved in it. I did search and found many answers but they were more complex than what I need. For example they needed to zoom in, generate, create accurate thumbnail, embed the actual PDF in the webpage, etc... But my question is much simpler:
If my guy that I am showing his information on webpage has some PDF to show I just want to put a generic PDF icon on the page, people click on it and the actual PDF opens in a new tab in their browser.
What is involved in just doing that? It is not like a file path, the PDF is saved in SQL server as binary objects or whatever it does to save it in SQL Server..it is not a file disk path on server

Your tags indicate asp.net-mvc.
Create a controller to handle requests for the PDF file
Pseudo:
[RoutePrefix("Pdf")]
public class PdfController : Controller {
[Route("{id}"]
public ActionResult GetPDF(int id) {
//...Code to extract pdf from SQLServer and store in stream
Stream stream = GetDataFromSQLServerById(id);
return File(stream,"filename.pdf");
}
}
On client
<a href="/Pdf/123456" target="_blank">
<img src="images/pdficon.jpg">
</a>
Update:
Referencing #ChrisPratt's comment; (which I forgot to include in my answer)
The target attribute on the anchor tag is what will tell the browser to open the link in a new tab.

Create a Controller action to for your link
public PdfResult GetPdf(int databaseRecordId)
{
var dbRecord = your code to return the sql record.
return new PdfResult(dbRecord.PdfBytes, "whatever name you want to show.pdf");
}
public class PdfResult : FileResult
{
private const String DefaultFileName = "file.pdf";
private readonly Byte[] _byteArray;
public PdfResult(Byte[] byteArray, String fileName = DefaultFileName)
: base(MediaTypeNames.Application.Pdf)
{
_byteArray = byteArray;
FileDownloadName = fileName;
}
protected override void WriteFile(HttpResponseBase response) { response.BinaryWrite(_byteArray); }
}
view code
<a href="<controller/action/databaseRecordId>" target="_blank">
<img src="<image-path>">
</a>

Related

How to download a file with Vaadin 10?

I want to let user to download a file from server.
I looked up for the solution and when trying to make an example - ended up with this:
#Route("test-download")
public class Download extends VerticalLayout {
public Download() {
Anchor downloadLink = new Anchor(createResource(), "Download");
downloadLink.getElement().setAttribute("download", true);
add(downloadLink);
}
private AbstractStreamResource createResource() {
return new StreamResource("/home/johny/my/important-file.log", this::createExportr);
}
private InputStream createExportr(){
return null;
}
}
Which is giving java.lang.IllegalArgumentException: Resource file name parameter contains '/' when I go to the page in browser.
How do I make a download button (or anchor) knowing file location on disk?
Have a look at the documentation, paragraph "Using StreamResource". The first parameter is just a file name that will be used by the browser to propose that file name to the user when downloading. So you could pass it like "important-file.log". The content of the download is provided by the InputStream parameter. For instance, you could read from your file, see here:
File initialFile = new File("src/main/resources/sample.txt");
InputStream targetStream = new FileInputStream(initialFile);

how to save a mvc view as a file and print the same file?

In my controller, I am rendering a view.
My Action method looks like this:
public ActionResult SomePrint(Model model)
{
//Some business action
return View("viewname",model);
}
Now my requirement is to save this view as file(may be pdf file) in my solution and send it to print and delete the file once the print is done.
Tried to use Rotativa and convert it to pdf by following
public ActionResult DownloadViewPDF()
{
var model = new GeneratePDFModel();
//Code to get content
return new Rotativa.ViewAsPdf("GeneratePDF", model){FileName = "TestViewAsPdf.pdf"}
}
But i need it to save it as pdf and print the same.
Any help? Thanks in advance.
If you would have been requesting to export to a known convertible type (such as Excel), formatting the stream would be enough. But if you would like to Export to PDF you should create another View to Export the file and use a 3rd party application such as iText.
You can use BuildPdf method on ViewAsPdf.
public ActionResult DownloadViewPDF()
{
var model = new GeneratePDFModel();
var pdfResult = new ViewAsPdf("GeneratePDF", model)
{ FileName = "TestViewAsPdf.pdf" };
var binary = pdfResult.BuildPdf(this.ControllerContext);
// you can save the binary pdf now
return File(binary, "application/pdf");
}

MvcRazorToPdf save as MemoryStream or Byte[]

I'm using MvcRazorToPdf in a Azure website and create my PDF's and output them in the browser.
Now i'm creating a new function to directly email the PDF as attachment (without output them in the browser).
Does anybody know if it is possible to save the PDF (with MvcRazorToPdf) as a MemoryStream or Byte[]?
I think you can handle this in ResultFilter, I used below code to allow user to download file and prompt for download popup, in this way you can grab all your memory stream and store somewhere to send email afterwords.
public class ActionDownloadAttribute : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + "Report.pdf");
base.OnResultExecuted(filterContext);
}
}
[ActionDownload]
public ActionResult GeneratePdf()
{
List<Comment> comments = null;
using (var db = new CandidateEntities())
{
comments = db.Comments.ToList();
}
return new PdfActionResult("GeneratePdf", comments);
}
I have implemented something like that. So basically I have not been changing my method to output PDF. What I have done is used restsharp to make request at URL where I get PDF then what you have is in lines of (this is partial code only so you can get idea )
var client = new RestClient(IAPIurl);
var request = new RestRequest(String.Format(IAPIurl_generatePDF, targetID), Method.GET);
RestResponse response = (RestResponse) client.Execute(request);
// Here is your byte array
response.RawBytes
Otherwise you can use my answer from here where I discussed directly returning a file.
Hope this helps!

Display the file in page when the type of that is not specified

When I want to show an image I use something like this:
public ActionResult Show(int id) {
var MyFile = GetFromDB(id);
return File(MyFile.Data, MyFile.ContentType);
}
And in View:
<img alt ="" src='#Url.Action("show", new { id = 36 })'/>
So assume we have some other types of file like txt, pdf, ...
And I think to use a general tag to show all kind of files instead of <img>. Does any one have any idea about it?
It is not easy, because some files need initialization or need additional declarations to specify how they should be presented, but you can try with iframe:
<iframe src='#Url.Action("show", new { id = 36 })'></iframe>
It will use browser built-in way of presenting documents.

MVC open pdf file

I have the following issue:
I have a MVC application, in some action of some controller i'm generating a PDF file, the file is being generated on a specific path on the server. That action is being called on an action link of the view, when the user clicks that link, the action generated that PDF, everything fine until here.
I want the page to show the dialog with my generated PDF file that says:
Open - Save - Cancel (the tipical file dialog when you click a file)
But without refreshing the page, only show the dialog when the user clicked the link.
How could i do that? what should the action return to the view?
Thanks.
Have a look at FilePathResult and FileStreamResult.. An example is here.
To provide the Open - Save - Cancel dialog you will need to set the appropriate Response headers, and as #RichardOD says, return a FilePathResult or FileStreamResult.
HttpContext.Response.AddHeader("content-disposition", "attachment;
filename=form.pdf");
return new FileStreamResult(fileStream, "application/pdf");
Try something like this
public class PdfResult : ActionResult
{
//private members
public PdfResult(/*prams you need to generate that pdf*/)
public override void ExecuteResult(ControllerContext context)
{
//create the pdf in a byte array then drop it into the response
context.HttpContext.Response.Clear();
context.HttpContext.Response.ContentType = "application/pdf";
context.HttpContext.Response.AddHeader("content-disposition", "attachment;filename=xxx.pdf");
context.HttpContext.Response.OutputStream.Write(pdfBytes.ToArray(), 0, pdfBytes.ToArray().Length);
context.HttpContext.Response.End();
}
}
Then u just return a PdfResult
Tip: I got a generic class for doing this and it's something like this and i am using NFop
public PdfResult(IQueryable source, Dictionary<string,int> columns, Type type)
{
Source = source;
Columns = columns;
SourceType = type;
}

Resources