Turning HTML into PDF

Asked

Viewed 24,420 times

12

I noticed that on the website of Banco do Brasil it is possible to choose the output format of a voucher txt, pdf, csv without the need to resubmit the page. Is there a library that converts the html displayed in the PDF page without the need for new Ubmit and page processing? The back-end will be considered php or Node.

  • May JQuery? Because if it is with PHP, without leaving the page, it is impossible (unless Ajax)

  • You can. I thought of using angular or jquery. What you suggest?

  • Hello, Have you looked at dompdf (https://github.com/dompdf/dompdf) ? You can capture the document and submit it to a php that does the conversion.

  • I like Jquery (particularly), I replied...I think it’s perfect for you

  • I recommend using iText7 and pdfHTML (the latest add-on for iText7 that handles exactly your use case). Further explanation can be found on our website at http://itextpdf.com/blog/pdfhtml-introduction

  • Very simple, I am using this API: https://htmlparapdf.com.br/como-usar-api.cshtml

Show 1 more comment

4 answers

14


You can do it using jsPDF.

HTML

<div id="conteudo">
     <h3>Olá, esta é uma tag H3</h3>

    <p>Um parágrafo.</p>
</div>
<div id="editor"></div>
<button id="btGerarPDF">gerar PDF</button>

Javascript (Jquery)

var doc = new jsPDF();
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};

$('#btGerarPDF').click(function () {
    doc.fromHTML($('#conteudo').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('exemplo-pdf.pdf');
});

Jsfiddle

  • it only redenrizes html or if you put some css it transforms tbm ?

  • Unhappiness does not interpret CSS. But a simple solution would be to convert HTML to Canvas (example) and instead of pdf.fromHTML(), use pdf.addHTML(), example: pdf.addHTML($('#ElementoCanvasQueVoceQuerConverterParaPDF')[0], function () { pdf.save('Teste.pdf'); });

  • I get it, this way addHTML() seems to be new from what I saw in the documentation, have you tested ? I modified your jsfiddle for it to work and it appeared that pdf.addHTML não e uma função.

  • 1

    I haven’t tested this new function yet, but I saw it here: http://stackoverflow.com/questions/25946275/exporting-pdf-with-jspdf-not-rendering-css

3

I already make use of the Headless Browser Phantomjs to download COMPLETE WEB pages FAITHFULLY rendered to displayed in the common browser (it interprets JS and CSS) but with it it is also possible to perform a print screen of the desired page of the shape sequinte:

  • Create a file with extension . js
  • Paste and save the following content:

Command that accesses a given page and saves the contents of it in a . png (but can save as PDF):

var page = require('webpage').create();
page.open('http://stackoverflow.com/', function() {
  page.render('stackoverflow.png');
  phantom.exit();
});
  • call it from the following foma at the command line: program name (if it has been inserted in the path) plus npath of the javascript file created in the above item so it is as follows:

    phantomjs test.js

With it it is also possible to establish the dimensions of the window where the site is displayed (this is useful if you want to see how a responsive site is being rendered) as follows (this setting should be done before the page.open()):

var webPage = require('webpage');
var page = webPage.create();

page.viewportSize = {
  width: 480,
  height: 800
};

You can call it using the shell_exec command in this way:

    $pathToPhantomJS = 'C:\phantomjs-2.0.0-windows\bin\phantomjs';
    $pathToJSScript = 'GetPage.js';
    $comand = $pathToPhantomJS . ' ' . $pathToJSScript . ' ' . $site;
    shell_exec($comand);

Note: step a third variable that represents the site to have its page printada the site is picked up by the vector of args that are passed to the shell.

It is possible to create a CRON JOB to execute the command phantomjs teste.js at a certain time.

Phantomjs was very useful to me and is very configurable and I could not describe all the possibilities here so I am pasting some links Official and not Official that may be useful:

Download

Link: http://phantomjs.org/download.html

Documentation

Screen Capture: Link

viewportSize: Link

shell_exec (PHP): Link

1

1º Make generate the pdf by an AJAX instance, in Jquery to be faster. 2º Run a url with the return of ajax, containing the file name, in another php file which will force the download. This way will get your pdf generated unreflected:

<script>

$.get('mypdf.php?id='.$_GET['IDCLIENTE'], function(data){
location.href = 'download.php?file='+data;
});

</script>

To generate the PDF faster recommend the library: http://html2pdf.fr/en/example. The same just pass the HTML in a variable it generates the PDF.

The PHP code of the download below:

<?php

$file_url = $_GET['file'];
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url);

?>
  • Place inside your function by passing the Javascript/Jquery parameters of my code.

-3

Follow JS code using Html API For PDF:

// Code DEMO here
var settings = {
    "url": "//v1/Consultar?user=<string>&key=<string>&ArquivoID=<string>",
    "method": "GET",
    "timeout": 0,
};

$.ajax(settings).done(function (response) {
    console.log(response);
});

inserir a descrição da imagem aqui

Browser other questions tagged

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