Usuário com melhor resposta
Relatório em html transformar para pdf

Pergunta
-
Todos os meus relatórios sempre faço com o report viewer, mais me deparei com um relatório que não conseguir faze-lo e tive que recorrer ao HTML, faço assim , crio uma label e dentro dela monto o relatório com <table>,<tr> e <td>.
Funciona legal, sendo que não tem quebra de página e formato (paisagem e retrato), queria saber tendo essa label com o relatório pronto tenho como transforma-lo em pdf ? tenho que exibir em paisagem.
Alguém sabe como fazer isso ?
Junior
Respostas
-
Junior,
Cole esse conteúdo abaixo do seu label
<asp:Label ID="lbl_conteudo" name="lbl_conteudo" runat="server" Text="Label"></asp:Label> <iframe class="preview-pane" type="application/pdf" width="100%" height="650" frameborder="0" style=";z-index:999"></iframe> <div class="text-center"> <button id="gerarPdf" class="btn btn-primary">PDF</button> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script> <script type="text/javascript"> // Botao var button = $("#gerarPdf"); // PDF - Init the configs var pdf = new jsPDF('p', 'pt', 'letter'); // source can be HTML-formatted string, or a reference // to an actual DOM element from which the text will be scraped. source = $('span[name=lbl_conteudo]')[0]; // we support special element handlers. Register them with jQuery-style // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.) // There is no support for any other type of selectors // (class, of compound) at this time. specialElementHandlers = { // element with id of "bypass" - jQuery style selector '#bypassme': function (element, renderer) { // true = "handled elsewhere, bypass text extraction" return true } }; margins = { top: 80, bottom: 60, left: 40, width: 522 }; // all coords and widths are in jsPDF instance's declared units // 'inches' in this case pdf.fromHTML( source, // HTML string or DOM elem ref. margins.left, // x coord margins.top, {// y coord 'width': margins.width, // max width of content on PDF 'elementHandlers': specialElementHandlers }, margins); var conteudoPDF = pdf.output('dataurl'); console.log(conteudoPDF); $('.preview-pane').attr('src', conteudoPDF); // handle click and add class button.on("click", function () { // dispose: object with X, Y of the last line add to the PDF // this allow the insertion of new lines after html pdf.save('Test.pdf'); }) </script>
Espero ter ajudado! Se consegui, não esquece de marcar no fórum como útil! Obrigado :)
#fullstack dev - MCSA, MCTS and actually blogging at www.saindodacaixinha.com.br- Marcado como Resposta Filipe B CastroModerator quinta-feira, 2 de agosto de 2018 19:45
Todas as Respostas
-
Será que o JSPdf não te ajuda?
Ele gera pdf's a partir de um componente HTML
https://github.com/MrRio/jsPDF
Espero ter ajudado! Se consegui, não esquece de marcar no fórum como útil! Obrigado :)
#fullstack dev - MCSA, MCTS and actually blogging at www.saindodacaixinha.com.br -
-
Não precisa adicionar DLL no seu projeto :)
E com ele é possivel formatar quebra de página, o layout como um todo, basta seguir os exemplos que a própria biblioteca disponibiliza aqui.
O JSPdf é uma biblioteca javascript, ele vai pegar teu HTML e gerar um PDF. Extremamente simples de utilizar, veja o exemplo:
Adicione a referencia do JSPdf ao seu HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>
Agora adicione essa função demo
function demoFromHTML() { var pdf = new jsPDF('p', 'pt', 'letter'); // source can be HTML-formatted string, or a reference // to an actual DOM element from which the text will be scraped. source = $('#customers')[0]; // we support special element handlers. Register them with jQuery-style // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.) // There is no support for any other type of selectors // (class, of compound) at this time. specialElementHandlers = { // element with id of "bypass" - jQuery style selector '#bypassme': function (element, renderer) { // true = "handled elsewhere, bypass text extraction" return true } }; margins = { bottom: 60, width: 522 }; // all coords and widths are in jsPDF instance's declared units // 'inches' in this case pdf.fromHTML( source, // HTML string or DOM elem ref. margins.left, // x coord margins.top, {// y coord 'width': margins.width, // max width of content on PDF 'elementHandlers': specialElementHandlers }, function (dispose) { // dispose: object with X, Y of the last line add to the PDF // this allow the insertion of new lines after html pdf.save('Test.pdf'); } , margins); }
E por fim uma tabela com conteúdo
<div id="customers"> <table id="tab_customers" class="table table-striped"> <colgroup> <col width="20%"> <col width="20%"> <col width="20%"> <col width="20%"> </colgroup> <thead> <tr class='warning'> <th>Country</th> <th>Population</th> <th>Date</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>Chinna</td> <td>1,363,480,000</td> <td>March 24, 2014</td> <td>19.1</td> </tr> <tr> <td>India</td> <td>1,241,900,000</td> <td>March 24, 2014</td> <td>17.4</td> </tr> <tr> <td>United States</td> <td>317,746,000</td> <td>March 24, 2014</td> <td>4.44</td> </tr> <tr> <td>Indonesia</td> <td>249,866,000</td> <td>July 1, 2013</td> <td>3.49</td> </tr> <tr> <td>Brazil</td> <td>201,032,714</td> <td>July 1, 2013</td> <td>2.81</td> </tr> </tbody> </table> </div> <button onclick="javascript:demoFromHTML()">PDF</button>
Veja o resultado abaixo
Espero ter ajudado! Se consegui, não esquece de marcar no fórum como útil! Obrigado :)
#fullstack dev - MCSA, MCTS and actually blogging at www.saindodacaixinha.com.br
- Editado Bruno Brito terça-feira, 3 de julho de 2018 16:36
-
-
Para exibir ao cliente você tem que usar a propriedade output do JSPDdf.
Abaixo um exemplo utilizando tanto a opção salvar quanto exibindo o PDF na tela. Crie um arquivo chamado teste.html e cole o conteudo
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title> JSPdf</title> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.min.css" /> </head> <body> <div id="banner-message"> <div id="customers"> <table id="tab_customers" class="table table-striped"> <colgroup> <col width="20%"> <col width="20%"> <col width="20%"> <col width="20%"> </colgroup> <thead> <tr class='warning'> <th>Country</th> <th>Population</th> <th>Date</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>Chinna</td> <td>1,363,480,000</td> <td>March 24, 2014</td> <td>19.1</td> </tr> <tr> <td>India</td> <td>1,241,900,000</td> <td>March 24, 2014</td> <td>17.4</td> </tr> <tr> <td>United States</td> <td>317,746,000</td> <td>March 24, 2014</td> <td>4.44</td> </tr> <tr> <td>Indonesia</td> <td>249,866,000</td> <td>July 1, 2013</td> <td>3.49</td> </tr> <tr> <td>Brazil</td> <td>201,032,714</td> <td>July 1, 2013</td> <td>2.81</td> </tr> </tbody> </table> </div> <iframe class="preview-pane" type="application/pdf" width="100%" height="650" frameborder="0" style=";z-index:999"></iframe> <div class="text-center"> <button id="gerarPdf" class="btn btn-primary">PDF</button> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script> <script type="text/javascript"> // Botao var button = $("#gerarPdf"); // PDF - Init the configs var pdf = new jsPDF('p', 'pt', 'letter'); // source can be HTML-formatted string, or a reference // to an actual DOM element from which the text will be scraped. source = $('#customers')[0]; // we support special element handlers. Register them with jQuery-style // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.) // There is no support for any other type of selectors // (class, of compound) at this time. specialElementHandlers = { // element with id of "bypass" - jQuery style selector '#bypassme': function (element, renderer) { // true = "handled elsewhere, bypass text extraction" return true } }; margins = { top: 80, bottom: 60, left: 40, width: 522 }; // all coords and widths are in jsPDF instance's declared units // 'inches' in this case pdf.fromHTML( source, // HTML string or DOM elem ref. margins.left, // x coord margins.top, {// y coord 'width': margins.width, // max width of content on PDF 'elementHandlers': specialElementHandlers }, margins); var conteudoPDF = pdf.output('dataurl'); console.log(conteudoPDF); $('.preview-pane').attr('src', conteudoPDF); // handle click and add class button.on("click", function () { // dispose: object with X, Y of the last line add to the PDF // this allow the insertion of new lines after html pdf.save('Test.pdf'); }) </script> </body> </html>
Espero ter ajudado! Se consegui, não esquece de marcar no fórum como útil! Obrigado :)
#fullstack dev - MCSA, MCTS and actually blogging at www.saindodacaixinha.com.br -
meu aspx está assim
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style type="text/css" media="print"> @page { size: landscape; } </style> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script> </head> <body> <form id="form1" runat="server"> <div id="ap" > <asp:Label runat="server" id="lbl_conteudo"></asp:Label> </div> </form> </body> <script type="text/javascript"> function demoFromHTML() { debugger; var pdf = new jsPDF('p', 'pt', 'letter'); source = $('#ap')[0]; specialElementHandlers = { '#bypassme': function(element, renderer) { return true; } }; margins = { bottom: 60, width: 522 }; pdf.fromHTML( source, // HTML string or DOM elem ref. margins.left, // x coord margins.top, { // y coord 'width': margins.width, // max width of content on PDF 'elementHandlers': specialElementHandlers }, function(dispose) { // dispose: object with X, Y of the last line add to the PDF // this allow the insertion of new lines after html pdf.save('Test.pdf'); }, margins); } </script> </html>
O relatório é montado no lbl_conteudo.text
Junior
-
Junior,
Cole esse conteúdo abaixo do seu label
<asp:Label ID="lbl_conteudo" name="lbl_conteudo" runat="server" Text="Label"></asp:Label> <iframe class="preview-pane" type="application/pdf" width="100%" height="650" frameborder="0" style=";z-index:999"></iframe> <div class="text-center"> <button id="gerarPdf" class="btn btn-primary">PDF</button> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script> <script type="text/javascript"> // Botao var button = $("#gerarPdf"); // PDF - Init the configs var pdf = new jsPDF('p', 'pt', 'letter'); // source can be HTML-formatted string, or a reference // to an actual DOM element from which the text will be scraped. source = $('span[name=lbl_conteudo]')[0]; // we support special element handlers. Register them with jQuery-style // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.) // There is no support for any other type of selectors // (class, of compound) at this time. specialElementHandlers = { // element with id of "bypass" - jQuery style selector '#bypassme': function (element, renderer) { // true = "handled elsewhere, bypass text extraction" return true } }; margins = { top: 80, bottom: 60, left: 40, width: 522 }; // all coords and widths are in jsPDF instance's declared units // 'inches' in this case pdf.fromHTML( source, // HTML string or DOM elem ref. margins.left, // x coord margins.top, {// y coord 'width': margins.width, // max width of content on PDF 'elementHandlers': specialElementHandlers }, margins); var conteudoPDF = pdf.output('dataurl'); console.log(conteudoPDF); $('.preview-pane').attr('src', conteudoPDF); // handle click and add class button.on("click", function () { // dispose: object with X, Y of the last line add to the PDF // this allow the insertion of new lines after html pdf.save('Test.pdf'); }) </script>
Espero ter ajudado! Se consegui, não esquece de marcar no fórum como útil! Obrigado :)
#fullstack dev - MCSA, MCTS and actually blogging at www.saindodacaixinha.com.br- Marcado como Resposta Filipe B CastroModerator quinta-feira, 2 de agosto de 2018 19:45
-
Bruno fiz exatamente como vc indicou, colei todo o código abaixo da label, ele executou e já mostrou um pdf vazio, quando cliquei no botão PDF ele baixou o arquivo test.pdf, porém vazio.
Percebi que vc alterou o label e coloquei o name="lbl_conteudo" e executei novamente, porém, ele não mostra nada e qdo clico no botão PDF ele executa tudo novamente e não mostra nada muito menos baixa o arquivo test.pdf
Junior
-
Junior,
Pode ser que há algum erro do javascript que esteja impedindo o componente / jquery.
O que posso fazer é disponibilizar um projeto no GitHub em WebForms que pode te guiar nesse problema.
Projeto do GitHub: WebFormsComJSPdf
Espero ter ajudado! Se consegui, não esquece de marcar no fórum como útil! Obrigado :)
#fullstack dev - MCSA, MCTS and actually blogging at www.saindodacaixinha.com.br -
Olá Bruno, inspecionando verifiquei que ocorre um erro no jspdf na linha 97 diz que "não conseguiu ler a propriedade name ou é indefinida"
function(t){var T,F,i,a,s,h,c,l,P,v,f,u,d,n,E,q,p,g,m,O;T=function()
a[r[o].name]=s.cells[o].textContent.replace(/\r?\n/g,"")
Junior