Search code examples
phphttpsautohotkeydompdf

How to download pdf created by dompdf by WinHttpRequest post request from autohotkey


Below is my autohotkey code to send WinHttpRequest to php to download pdf file from stream function of PHP created by dompdf.

AutoHotkey:

whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
whr.Open("POST", "https://spm/htmltopdf.php",false)
whr.SetRequestHeader("Content-Type","application/pdf")
whr.SetRequestHeader("Content-Disposition","attachment")
whr.SetRequestHeader("filename","file.pdf'")
whr.Send("html=" . %html%)
version := whr.ResponseText
FileAppend, %version%, *d:\cc.pdf

PHP:

<?php
header('Access-Control-Allow-Origin: *'); //to get data from firefox addon
require_once "dompdf/dompdf_config.inc.php";
$dompdf = new DOMPDF();
$html = $_POST["html"];
$dompdf->load_html($html);
$dompdf->render();
//$output = $dompdf->output();
//file_put_contents("output/file.pdf", $output);
$dompdf->stream("file.pdf");
?>

I could get pdf by direct navigation from browser with GET method with 'http' protocol. But for this autohotkey script it does nothing. And it gives an error 'The certificate authority is invalid or incorrect'.


Solution

  • Try something like this... I think you are confusing server headers with client headers...

    ahk

    whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
    whr.Open("POST", "https://spm/htmltopdf.php",false)
    whr.SetRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
    whr.SetRequestHeader("Content-Type","application/x-www-form-urlencoded")
    whr.Send("html=" . html)
    version := whr.ResponseText
    FileAppend, %version%, *d:\cc.pdf
    

    php

    <?php
    header('Access-Control-Allow-Origin: *'); //to get data from firefox addon
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment');
    header('filename: file.pdf');
    require_once "dompdf/dompdf_config.inc.php";
    $dompdf = new DOMPDF();
    $html = $_POST["html"];
    $dompdf->load_html($html);
    $dompdf->render();
    //$output = $dompdf->output();
    //file_put_contents("output/file.pdf", $output);
    $dompdf->stream("file.pdf");
    ?>
    

    or since you said your browser was able to get it via GET and with http, try that:

    whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
    whr.Open("GET", "http://spm/htmltopdf.php",false)
    whr.SetRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
    whr.Send()
    version := whr.ResponseText
    FileAppend, %version%, *d:\cc.pdf
    

    Or go with UrlDownloadToFile in the first place:

    UrlDownloadToFile, http://spm/htmltopdf.php, file.pdf