javascript - Jquery $.post html 到外部 php 并将 html 打印为 pdf。需要找到最优解
问题描述
我得到mysql数据。
创建 - 将 mysql 数据回显为 html。
如果访问者想要将数据打印为 pdf(我的意思是创建 pdf 文件并保存在计算机上),我使用 jquery 获取数据并发送到外部 php 文件。在外部 php 文件中,使用http://www.tcpdf.org
解决方案我想创建 pdf 文件(即时,仅作为变量;我不想将文件保存在我的服务器上)以便用户可以保存它。
用户保持在同一个 url 上,就在用户单击按钮后,我让用户保存呈现的 pdf。我不想更改 url 或将 html 内容添加到 url(如print_pdf.php?html_content
)。
目前我使用如下代码。
<div id="to_print_as_pdf">
<div>Some content from mysql</div>
<table>Another content from mysql</table>
</div>
<button type="button">Click to print as pdf</button>
<span id="result_print_pdf"></span>
jquery发送数据
<script>
$("button").click(function(){
$.post('_prepare_to_print_pdf.php',
{ content_to_print: $('#to_print_as_pdf').html() },
function(result_print_pdf) {
$('#result_print_pdf').html(result_print_pdf).css('color', 'black');
});
});
</script>
文件_prepare_to_print_pdf.php
$_SESSION['content_to_print'] = trim($_POST['content_to_print']);
<script>
window.location.href = "https://www.example.com/_print_pdf.php";
</script>
文件_print_pdf.php
//Use http://www.tcpdf.org solution
$html = $_SESSION['content_to_print'];
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
$pdf->Output('example_001.pdf', 'I');
如何在没有 的情况下做同样的事情_prepare_to_print_pdf.php
?以上解决方案浪费服务器资源(创建会话)。
我尝试$.post
将 html 内容直接发送到_print_pdf.php
,但在这种情况下,我没有提示保存 pdf 文件,而是看到“垃圾”字符...
目前的解决方案
可能会对某人有所帮助
$('#for_hidden_form_for_print_pdf').append('<form action="_print_pdf.php" method="post" target="_blank" id="hidden_form_for_print_pdf">' +
'<textarea id="content_to_print" name="content_to_print">html content to send </textarea>' +
'<div><button style="display: none;" id="btn_to_print_pdf">Print pdf</button></div></form>');
$('#btn_to_print_pdf').trigger('click');
$( "#hidden_form_for_print_pdf" ).remove();
因此,当访问者单击按钮/图标时,我会获取必要的 html 数据,插入textarea id="content_to_print"
. 然后触发 click for btn_to_print_pdf
,然后删除附加的表单。所以我发送到外部 php 文件,必要的 html 代码。在 php 文件中,我处理 html 代码,为 pdf 文件创建内容并打印。
解决方案
推荐阅读
- python - 使用 python 我正在尝试通过请求将数据提交到网站。如何通过确认对话框?
- scala - 使用列值列表收集多个 RDD - Spark
- javascript - 如何在流中获取由 Promise 类型包装的类型?
- cuda - 复数累积乘积的 CUDA 内核
- node.js - 解构 require(d) 模块是否对节点有任何性能优势?
- r - 使用 Reshape 重塑 R 中的数据
- ruby - Programmatically skip a test in RSpec
- c++ - 如何在 EGL 中使用 gtkmm
- java - mybatis 是否允许在 oracle 中插入所有并返回序列(useGenerateKeys)?
- java - Simple-jndi 没有看到我的初始上下文