Open PDF in browser automatically after download

Asked

Viewed 1,339 times

2

The downalod from the PDF is executed correctly (is minimized at the bottom corner of the browser).

How to make it open automatically in a new guide ?:

<a href="#" class="download" name="downloaditem" id="downloaditem3" target="_blank"><span style="cursor:pointer"><font color="red"><b>BAIXADA</b></font></span></a>

That doubt is similar to that How to open the Razorpdf report in a separate tab, but I’m using another PDF generator Pechkin, I added the target="_blank" link as above, but does not work.

This is the Action that generates the PDF:

[HttpPost]
        public ActionResult PDFUmDocSelecionado(ProcessamentoRegistros pProcessamentoRegistros)
        {
            try
            {
                string _nomeArquivo = "Meu_Documento_" + DateTime.Now.ToString().Replace(" ", "_").Replace("/", "_").Replace(":", "_") + ".pdf";
                DataTable _Dt = new DataTable();

                _Dt = _IRepositorio.ObterHTML(pProcessamentoRegistros);
                DataRow foundRow = _Dt.Rows[0];

                var pechkin = Factory.Create(new GlobalConfig());
                var pdf = pechkin.Convert(new ObjectConfig()
                                                .SetLoadImages(true).SetZoomFactor(1)
                                             .SetPrintBackground(true)
                                             .SetScreenMediaType(true)
                                             .SetCreateExternalLinks(true)
                                             .SetIntelligentShrinking(true).SetCreateInternalLinks(true)
                                             .SetAllowLocalContent(true), foundRow.ItemArray[0].ToString());
                using (MemoryStream file = new MemoryStream())
                {
                    file.Write(pdf, 0, pdf.Length);
                }

                byte[] arquivo = pdf;

                //Response.Clear();
                //Response.ClearContent();
                //Response.ClearHeaders();
                //Response.ContentType = "application/pdf";
                ////Response.AddHeader("Content-Disposition", string.Format("attachment;filename=arquivo.pdf, size={0}", _pdf.Length));
                //Response.AddHeader("Content-Disposition", string.Format("inline;filename=" + _nomeArquivo + ", size={0}", pdf.Length));
                //Response.BinaryWrite(pdf);
                //Response.Flush();
                //Response.End();

                ////return RedirectToAction("Index", "Documento");
                return File(arquivo, System.Net.Mime.MediaTypeNames.Application.Octet, _nomeArquivo);
            }
            catch
            {
                return RedirectToAction("Index", "ProcessamentoRegistros");
            }
        }

2 answers

2


Instead of returning File, return FileStreamResult. How the file is in byte[], will need to do this to pass to MemoryStream:

byte[] arquivo = pdf;
MemoryStream pdfStream = new MemoryStream();
pdfStream.Write(stream.ToArray(), 0, stream.ToArray().Length);
pdfStream.Position = 0;
return new FileStreamResult(pdfStream, "application/pdf");

The code you set as an example would look like this:

[HttpPost]
public ActionResult PDFUmDocSelecionado(ProcessamentoRegistros pProcessamentoRegistros)
{
    try
    {
        string _nomeArquivo = "Meu_Documento_" + DateTime.Now.ToString().Replace(" ", "_").Replace("/", "_").Replace(":", "_") + ".pdf";
        DataTable _Dt = new DataTable();

        _Dt = _IRepositorio.ObterHTML(pProcessamentoRegistros);
        DataRow foundRow = _Dt.Rows[0];

        var pechkin = Factory.Create(new GlobalConfig());
        var pdf = pechkin.Convert(new ObjectConfig()
                                        .SetLoadImages(true).SetZoomFactor(1)
                                     .SetPrintBackground(true)
                                     .SetScreenMediaType(true)
                                     .SetCreateExternalLinks(true)
                                     .SetIntelligentShrinking(true).SetCreateInternalLinks(true)
                                     .SetAllowLocalContent(true), foundRow.ItemArray[0].ToString());
        using (MemoryStream file = new MemoryStream())
        {
            file.Write(pdf, 0, pdf.Length);
        }

        byte[] arquivo = pdf;

        MemoryStream pdfStream = new MemoryStream();
        pdfStream.Write(stream.ToArray(), 0, stream.ToArray().Length);
        pdfStream.Position = 0;
        return new FileStreamResult(pdfStream, "application/pdf");
    }
    catch
    {
        return RedirectToAction("Index", "ProcessamentoRegistros");
    }
}

Below is another example using an excerpt from an answer I gave to another question of yours:

[HttpPost]
public ActionResult OpenPdfFileInBrowser()
{
    var doc = new Document(PageSize.A4.Rotate());
    var stream = new MemoryStream();
    var pw = PdfWriter.GetInstance(doc, stream);
    var minhaStringHTML = @"<HTML><HEAD></HEAD><body><FORM method='post'><table><tr><td>Nome:</td><td>JOÃO DA SILVA</td></tr><tr><td>NOME:</td><td>MARCOS ALVES</td></tr></table></FORM></BODY></HTML>";

    doc.Open();
    using (var srHtml = new StringReader(minhaStringHTML))
    {
        //Convertendo o HTML
        XMLWorkerHelper.GetInstance().ParseXHtml(pw, doc, srHtml);
    }
    doc.Close();

    MemoryStream pdfStream = new MemoryStream();
    pdfStream.Write(stream.ToArray(), 0, stream.ToArray().Length);
    pdfStream.Position = 0;
    return new FileStreamResult(pdfStream, "application/pdf");
}

See working:

I used the same Github project as before and added an example to open the PDF in the browser.

  • thanks for the answer but the example that is in Github error when click on the PDF download button: Não é possível acessar um fluxo fechado.

  • @Adrianosuv, test now, I’ve made an edit and I’ve uploaded a change to Github.

  • all right ! Congratulations !

0

Served here with me, variable "file" bring his name.

  ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('../files/Reports/" + arquivo + "','_blank')", true);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.