Print queries

Asked

Viewed 1,351 times

2

I have a view in my application in Asp.net mvc that allows the user to perform a search, which returns the name and data of that search. I wish I could print this search result. How do I print div or table?

My view:

<div> 
     @using (Html.BeginForm())
     {
         IEnumerable<Banco.Models.Perfil> modelPerfil = (IEnumerable<Banco.Models.Perfil>)ViewBag.Perfil;
         <h4>Pesquisa por Dados</h4> <br />
       <div>  <input type="text" name="texto" id="texto" placeholder="Digite a busca" /> &nbsp; &nbsp;
         <button class="btn btn-primary btn-xs" type="submit">Filtrar</button></div>   <br/> <br>
     }
</div>
<table>

    @{
        if (Model != null)
        {
            foreach (var item in Model)
            {
        <tr>
        <th>Nome </th>
        <th>Experiência</th>

    </tr>
                <tr>
                   <td width="30%">@item.Perfil.Nome<b></td> 
                    <td width="50%">@item.Atividades <b></td>
                   @* <td>@item.Perfil.Chapa</td>*@
                    <td>
                      |&nbsp;  @Html.ActionLink("Ver Dados", "Details", "Relatorio", new { userName = @item.Perfil.Chapa }, null)|
                    </td>
                </tr>
            }
        }
    }
</table>

Controller

    [HttpGet]
    public ActionResult Pesquisa()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Pesquisa(string texto)
    {
        ViewBag.Perfil = db.Perfis.AsEnumerable();
        return View(db.Experiencia.Where(x => x.Atividades.Contains(texto)).OrderBy(x => x.NomeEmpresa));
    }
  • In what format you want to print?

  • Whatever. I just want to be able to make the impression of the search result.

2 answers

3

Here based at that link has a very easy tutorial to follow. I used and it is relatively simple, just needs a little attention. There is how to do it, but I’ll put the examples here for you:

Library installation

To install it is easy, go to the Nuget prompt and install the Rotary library, which will be used to generate the pdf to be printed. Thus opening the prompt put:
Rotating Install-Package(or to be more equal to the prompt: PM>Rotating Install-Package)

Confecção da View

This view will be used as a template for creating your report, or query, as you want. Remembering here that this report is just an example, you can customize it in the way you think best:

Template.cshtml

 @model RelatorioPDF.Models.Usuario
 <!DOCTYPE html>
 <html lang="pt-br">
 <head>
   <meta charset="utf-8" />
   <title>Exemplo de Relatório em PDF</title>

   <!-- css -->
  <link href="~/Content/estilos-relatorio.css" rel="stylesheet" />
 </head>
 <body>
   <div id="container">
      <div id="cabecalho">
        <div id="nome">
            <h1>RECIBO DE DISPENSAÇÃO</h1>
        </div>
        <div id="unidade">
            <h2>Meu Sistema</h2>
            <h3>Hospital São Paulo</h3>
            <h4>Farmácia</h4>
        </div>
    </div>
    <div id="corpo">
        <div class="linha">
            <p>
                Dispensado:<br />
                <span>10/10/2012</span>
            </p>
            <p>
                Cartão do SUS:<br />
                <span>123.1232.123.123</span>
            </p>
            <p>
                Usuario:<br />
                <span class="bold">João da Silva Gonçalves</span>
            </p>
        </div>
        <div class="linha">
            <p>
                Prescritor:<br />
                <span>Jonas São João</span>
            </p>
            <p>
                Nº Registro:<br />
                <span>12323132</span>
            </p>
            <p>
                Origem da Receita:<br />
                <span>10/10/012</span>
            </p>
        </div>
        <div class="linha">
            <p>Produtos Dispensados:</p>
            <table>
                <thead>
                    <tr>
                        <th>Produto</th>
                        <th>Atendido?</th>
                        <th>Und</th>
                        <th class="aling-right">Dispensado</th>
                        <th class="aling-right">Unitário R$</th>
                        <th class="aling-right">Total R$</th>
                    </tr>
                </thead>

                <tbody>

                    <tr class="odd">
                        <td class="bold" width="45%">Anador</td>
                        <td>Sim</td>
                        <td class="fonte10">FRS</td>
                        <td class="aling-right">10</td>
                        <td class="aling-right" width="100px;">1,2345</td>
                        <td class="aling-right" style="min-width: 100px">12,23</td>
                    </tr>
                    <tr class="odd">
                        <td colspan="6" class="italico">Possologia: 1 dose, 3 vez por dia, durante 5 dias</td>
                    </tr>

                    <tr class="">
                        <td class="bold" width="45%">Dipirona</td>
                        <td>Sim</td>
                        <td class="fonte10">FRS</td>
                        <td class="aling-right">10</td>
                        <td class="aling-right" width="100px;">1,2345</td>
                        <td class="aling-right" style="min-width: 100px">12,23</td>
                    </tr>
                    <tr class="">
                        <td colspan="6" class="italico">Possologia: 1 dose, 3 vez por dia, durante 5 dias</td>
                    </tr>

                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="5" class="bold">Total</td>
                        <td class="aling-right">R$ 12,23</td>
                    </tr>
                </tfoot>
            </table>
        </div>
        <div class="linha">
            <p>
                Observação:<br />
                <span>Paciente com fortes dores de cabeça</span>
            </p>
        </div>
    </div>
    <div id="rodape">
        <p>Usuário: <span>Cleyton Ferrari</span> Emitido: <span>26/10/2012</span> CleytonFerrari.com</p>
       </div>
   </div>
  </body>
  </html>

Putting to work

After the template view has been created to be printed or saved in pdf, now just create the logic in the controller to actually create the pdf:

Controller

In this controller, it’s just an example, to point out, and you can put the template creation action in any controller ok ? Here’s just an example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RelatorioPDF.Models;
using Rotativa;
using Rotativa.Options;

namespace RelatorioPDF.Controllers
{
  public class RelatoriosController : Controller
{
       /*
           * Retorna a view simples em HTML, usada como modelo para gerar o PDF
        */
    public ActionResult ModeloHTML()
    {
        return View("Modelo");
    }

       /*
        * Retorna um PDF diretamente no browser com as configurações padrões
        * ViewName é setado somente para utilizar o próprio Modelo anterior
        * Caso não queira setar o ViewName, você deve gerar a view com o mesmo nome da action
     */
    public ActionResult PDFPadrao()
    {
        var pdf = new ViewAsPdf
                      {
                          ViewName = "Modelo"
                      };
        return pdf;
    }

    /*
     * Configura algumas propriedades do PDF, inclusive o nome do arquivo gerado,
     * Porem agora ele baixa o pdf ao invés de mostrar no browser
     */
    public ActionResult PDFConfigurado()
    {
        var pdf = new ViewAsPdf
        {
            ViewName = "Modelo",
            FileName = "NomeDoArquivoPDF.pdf",
            PageSize = Size.A4,
            IsGrayScale = true,
            PageMargins = new Margins{Bottom = 5, Left = 5, Right = 5, Top = 5},
        };
        return pdf;
    }

    /*
     * Pode passar um modelo para a view que vai ser utilizada para gerar o PDF
     */
    public ActionResult PDFComModel()
    {
        var modelo = new Usuario
                         {
                             Nome = "Cleyton Ferrari", 
                             Site = "http://cleytonferrari.com"
                         };

        var pdf = new ViewAsPdf
        {
            ViewName = "Modelo",
            Model = modelo
        };

        return pdf;
    }

}
}

Remarks

Following this example will work to generate the printing of your queries quietly. Now, if it’s something more dynamic, I mean, with data coming from the bank, you just adapt the code and put the manipulation of the bank, just like when the actions that come with scaffolding are created. Or you can take a look in a question of mine that I put the action in the right way to search the data dynamically, and even answered the question showing the right way to generate the report by clicking on the link.

  • It is not good to use Rotary. It does not work in Azure.

  • But if he’s not going to put it on Azure it’s a good one. But you know why it doesn’t work @Ciganomorrisonmendez ?

  • Gives error. I contacted the developer and he said he would not solve.

  • Wow... What interest then in relation to a mistake he can solve right... But there are others that work right ?

  • Yes, there is Razorpdf, which works in Azure. This one I use in my solutions: https://www.nuget.org/packages/RazorPDF

2

The simplest way is through a Javascript link:

<a href="javascript:window.print()">Imprimir</a>

To avoid the title being printed on the page, use the following setting in your Layout:

<head>
    <style type="text/css" media="print">
        @page 
        {
            size: auto;
            margin: 0mm;
        }
    </style>
</head>
  • I am not using Azure no and I search the database yes. I will try the razorPDF then and for some folders just this javascript. I tested this javascript:windows.print and saw that returns everything that appears on my page. Okay, in some cases that’s just what I need, but if I want to for example not print the buttons and links of the page, how do I?

  • Api you would have to prepare a simplified View. It doesn’t have to be a PDF.

  • Just creating another simplified view? I can’t in any way in the same view omit what I don’t want to print?

  • Just creating a Javascript function that hides what you don’t want to display, and then calling the window.print().

Browser other questions tagged

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