Amandeep Wadhawan Amandeep Wadhawan - 3 months ago 69
Bash Question

How to excute wkhtmltopdf command using ajax in wordpress

I have create a wp_ajax function and calling this function on button click. In ajax function i have added a command for excute wkhtmltopdf libarary but my code is not working. Please check.

add_action( 'wp_ajax_genratepdf', 'genratepdf' );
add_action( 'wp_ajax_nopriv_genratepdf', 'genratepdf' );

function genratepdf(){

shell_exec("wkhtmltopdf http://www.google.com /dir-path/pdf38.pdf");

die('Y');
}


Jquery Code:

jQuery("#myBtnPdf").click(function (event) {
event.preventDefault();
var divContents = jQuery(".pf-content").html();
jQuery.ajax({
type: "post",
url: ajaxurl,
data: { action: "genratepdf", content:divContents },
success:
function(data) {

}
});
});


Thanks in advance

Answer

I am not sure but Try with

function genratepdf(){
    $ds = DIRECTORY_SEPARATOR ;
    $pdf_path = WP_CONTENT_DIR. $ds. "xyz.pdf";
    exec ("wkhtmltopdf http://www.google.com ".$pdf_path);

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($pdf_path).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($pdf_path));
    ob_clean();
    readfile($pdf_path);
    die();

}

it will create pdf file into wordpress content directory

In Javascript code

function autoSubmitForm(method, url, post_data) {
    var element = document.getElementById("virtual_form");
    if(element != null )
    {
        element.parentNode.removeChild(element);
    }
    var form = document.createElement("form");
    form.setAttribute("id", "virtual_form");
    form.setAttribute("style", "display:none;");
    form.setAttribute("target", "_blank");
    form.method = method;
    form.action = url;   
    for(i in post_data)
    {
         var element=document.createElement("input");
         element.value=post_data[i];
         element.name=i;
         form.appendChild(element); 
    }
    document.body.appendChild(form);
    form.submit();
    form.parentNode.removeChild(form);

}


jQuery("#myBtnPdf").click(function (event) {
    event.preventDefault();
    var divContents = jQuery(".pf-content").html();

    autoSubmitForm('POST',ajaxurl,{action:"genratepdf",content:divContents});
});