Created
March 21, 2024 22:23
-
-
Save dantetesta/d2d23fce35d09b816968e931f7e602bc to your computer and use it in GitHub Desktop.
Baixar Página Atual via API html to PDF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//https://portal.api2pdf.com/ | |
function my_enqueue_assets() { | |
wp_enqueue_script('jquery'); | |
wp_enqueue_style('font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css'); | |
} | |
add_action('wp_enqueue_scripts', 'my_enqueue_assets'); | |
function register_shortcode_button_pdf() { | |
add_shortcode('button_pdf', 'render_button_pdf'); | |
} | |
add_action('init', 'register_shortcode_button_pdf'); | |
function render_button_pdf() { | |
$button_html = '<button id="download-pdf"><i class="fa fa-file-pdf"></i> Download</button>'; | |
$script = <<<SCRIPT | |
<script> | |
jQuery(document).ready(function($) { | |
$('#download-pdf').click(function() { | |
var apiEndpoint = 'https://v2.api2pdf.com/chrome/pdf/url'; | |
var apiKey = 'acbc6c2c-6e70-4ff1-b52e-4dc5ac85ea71'; | |
var urlToConvert = window.location.href; // Or set the specific URL you want to convert | |
$(this).html('<i class="fa fa-spinner fa-spin"></i> Aguarde...').prop('disabled', true); | |
fetch(apiEndpoint + '?url=' + encodeURIComponent(urlToConvert) + '&apikey=' + apiKey) | |
.then(response => response.blob()) | |
.then(blob => { | |
var link = document.createElement('a'); | |
link.href = window.URL.createObjectURL(blob); | |
link.download = 'downloaded.pdf'; | |
document.body.appendChild(link); | |
link.click(); | |
document.body.removeChild(link); | |
$('#download-pdf').html('<i class="fa fa-file-pdf"></i> Download').prop('disabled', false); | |
}) | |
.catch(err => { | |
console.error(err); | |
alert('Error: Could not download the file.'); | |
$('#download-pdf').html('<i class="fa fa-file-pdf"></i> Download').prop('disabled', false); | |
}); | |
}); | |
}); | |
</script> | |
SCRIPT; | |
return $button_html . $script; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment