我有一个名为 print.php 的 PHP 文件:
<?php
require_once("modules/pdf/dompdf_config.inc.php");
$html = $_POST["toRender"];
$number = $_POST["number"];
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream($number.".pdf");
如您所见,HTML 和数字是通过 POST 接收的。
JavaScript 文件如下所示:
$("#btnViewPDF").click(function() {
var theHtml = $("#printable").html();
var theNumber = $("#invoiceNumber").val();
$.ajax({
type : "post",
url : "views/print.php",
data : {toRender : theHtml, number : theNumber},
beforeSend: function() {
$(".ajax-loader-bg").fadeIn();
}
}).always(function() {
$(".ajax-loader-bg").fadeOut();
});
return false;
});
基本上它需要一个名为“printable”的 DIV 中的所有内容,但我接下来想要显示的是 print.php 中生成的 PDF,我一直无法弄清楚如何制作它。
当我在 print.php 中生成测试 HTML,然后输入 url mysite.com/print.php 时,它就可以工作了...它会呈现 PDF 并允许我下载它或在另一个浏览器选项卡中查看它。
如何通过 AJAX 实现此目的?
您无法通过 AJAX 下载某些内容,您可以使用隐藏的 iframe 来模拟该行为。
并不是说你不能下载它,而是,它永远不会出于保存目的而出现在文件系统中,因为出于安全原因,javascript 无法这样做。
无论如何人们总能找到解决方案,你可以尝试这个:https://stackoverflow.com/a/23797348/1131176
我确实做到了这一点,通过一个技巧,这个例子是在codeigniter中制作的,所以你可以调整它,首先是ajax方法:
$.ajax({
url: base_url+"controladorapr/exportComprobanteIngresos", //method i called
data: $(this).serialize() //i serialized data from a form,
type:"POST",
dataType: 'JSON',
success: function (data) {
//create a link to download the pdf file
var link=document.createElement('a');
//i used the base url to target a file on mi proyect folder
link.href=window.URL = base_url+"exportacion.pdf";
//download the name with a different name given in the php method
link.download=data.nombre_archivo;
link.click();
//this js function hides the loading gif i use
hideLoad();
}
});
现在,让我们看看控制器上的方法:
function exportComprobanteIngresos(){
//receive your ajax data
$fecha = $this->input->post("fecha_comprobante_ingresos");
$fecha = date_format(DateTime::createFromFormat('d/m/Y', $fecha), "Y-m-d");
//send data to pdf
$data["fecha"] = $fecha;
//do some query here to send data and save it into $data[] array
//pdf size
$tamaño = 'A4';
//create a file name
$nombre_archivo = "Comprobante_ingresos".date_format(DateTime::createFromFormat('Y-m-d', $fecha), "Y_m_d").".pdf";
//load dompdf method, i will show this later, and send the data from db and file name
$pdf = $this->pdf->load_view("pdf/comprobanteIngresos", $data, $tamaño, $nombre_archivo);
//save the pdf content into the file we are downloading
file_put_contents('exportacion.pdf', $pdf);
//send data back to javascript
$data2["nombre_archivo"] = $nombre_archivo;
echo json_encode($data2);
}
现在,我们将包含 dompdf,要在 codeigniter 上使用 dompdf,请参阅此答案:Codeigniter with dompdf
现在,这是我在函数“$this->pdf->load_view”中使用的 dompdf 代码:
$dompdf = new Dompdf();
$html = $this->ci()->load->view($view, $data, TRUE);
$dompdf->loadHtml($html);
// (Optional) Setup the paper size and orientation
$dompdf->setPaper($size, 'portrait');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to variable and return it to save it into the file
$output = $dompdf->output();
return $output;
现在有了这个,我设法将ajax与dompdf一起使用,并在其中添加一个加载gif,效果很好,最后,您在“$this->pdf->load_view”上加载的php文件没有标题或者,是纯 html 和 php,希望这有帮助!
document.addEventListener("DOMContentLoaded", function () { var form = document.getElementById("make_pdf");
form.onsubmit = function (event) {
event.preventDefault(); // Prevent the default form submission
loaderFun(true, "Getting pdf please wait..."); //loader function manage loader
var formData = new FormData(form);
var url = base_url + "create_pdf.php";
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.responseType = "blob";
req.onload = function () {
if (req.status === 200) {
console.log("Form data submitted successfully");
var blob = req.response;
let newUrl = null
const binaryData = [];
binaryData.push(blob);
newUrl = window.URL.createObjectURL(new Blob (binaryData, {type: 'application/pdf; chartset=UTF-8'}));
var link=document.createElement('a');
link.href=newUrl
link.download="Dossier_" + new Date() + ".pdf";
link.click();
loaderFun(false); //loader function manage loader
} else {
console.error("Error submitting form data");
}
};
req.onerror = function () {
console.error("Request error");
};
req.send(formData);
};
});