Print Queries

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));
    }
    
asked by anonymous 23.06.2014 / 16:22

2 answers

3

Here based in this link has a very easy tutorial of follow. I've used it and it's relatively simple, just need a little attention. Here's how to do it, but I'll put the examples here for you:

Installing the library

To install is easy, go to the Nuget prompt and install the Rotating library, which is the one that will be used to generate the pdf to be printed. This way, by opening the prompt, place:
Install-Package Rotating (or to be more like the prompt: PM> Install-Rotatable Package)

Making the View

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

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 was created to be printed or saved in pdf, now just create the logic in the controller so that the pdf is actually created:

Controller

In this controller, it's just an example, to point out, and you can put the model creation action in any controller ok? Here is just one 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;
    }

}
}

Observations

Following this example will work generating the impression of your queries quietly. Now, if it is a more dynamic thing, I say, with data coming from the bank, it is only you to 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 at in a question of mine that I put the action in the right way to get the data dynamically, and even answered the question showing the right way to generate the report by clicking the link.

    
23.06.2014 / 17:37
2

The simplest way is through a link in JavaScript:

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

To prevent the title from 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>
    
23.06.2014 / 17:37