javascript - 使用 wkhtmltopdf 转换 PDF 后未显示更改的值

标签 javascript php html pdf wkhtmltopdf

当前在我的 html 页面中我更改了一些值,其工作方式如下:

功能:

function change1(){
   var myNewTitle = document.getElementById('myTextField1').value;
   if( myNewTitle.length==0 ){
       alert('Write Some real Text please.');
   return;
   }
   var titles = document.getElementsByClassName('title1');
   Array.prototype.forEach.call(titles,title => {
    title.innerHTML = myNewTitle;
   });
}

更改的值和用于输入的文本字段:

      Voornaam: <h3 class="title1">Kevin</h3>
      <input type="text" id="myTextField1"/>
      <input type="submit" id="byBtn" value="Change" onclick="change1()"/><br/>

      <p class="title1">Test.</p>

我使用 wkhtmltopdf 进行转换,这是一个用于 html 到 PDF 转换的命令行工具。然而,我所做的更改当然不是在服务器上完成的,而是在本地完成的,这就是为什么我的更改没有显示在我的转换中。

我正在考虑先下载更改后的html页面,然后使用wkhtmltopdf将其转换。 有人能给我一个例子来说明如何做到这一点,或者也许给我提供另一种更好的方法吗?

最佳答案

您必须发送页面内容,服务器上的 wkhtmltopdf 将完成这项工作。

在客户端,您需要像这样的所有功能:

function send(){ 
  var f = document.createElement("form"),
     i = document.createElement("input"); //input element, hidden

  f.setAttribute('method',"post");
  f.setAttribute('action',"http://yourserver.com/script.php");

  i.setAttribute('type',"hidden");
  i.setAttribute('name',"content");
  i.setAttribute('value', document.body.innerHTML); // or the container you need

  f.appendChild(i);
  document.getElementsByTagName('body')[0].appendChild(f);
  f.submit();
};

在服务器端,例如在php中,您将获取内容,将其保存在临时文件中,然后调用工具将其转换为pdf,然后将pdf返回给客户端:

<?php
try {
   $content = $_REQUEST['content'];
    if(!file_exists('/tmp') ){
       mkdir('/tmp', 0777);
    }
   $fp = fopen('w+','/tmp/tmp.html');
   if($fp){
     fwrite($fp, $content);
     fclose($fp);

     $filename = '/tmp/out_' . time() .'.pdf'; // output filename
     shell_exec('wkhtmltopdf /tmp/tmp.html ' . $filename);

     //then eventually ask user for download the result
     header("Content-type:application/pdf");

     // It will be called output.pdf
     header("Content-Disposition:attachment;filename='output.pdf'");

    readfile($filename);
  }else{
     echo 'html file could not be created';
  }
} catch (Exception $e) {
  echo 'exception: ',  $e->getMessage(), "\n";
}

关于javascript - 使用 wkhtmltopdf 转换 PDF 后未显示更改的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44326305/

相关文章:

javascript - 带有文本的 POST 请求

javascript - 在 MongoDB 中将简单的列表数组键迁移到另一个具有额外属性的键

javascript - 使用 Jquery 定时淡入淡出

php - PythonPATH 和 PHP

php - curl - react 慢

JavaScript 无法在 Firefox 和 IE/edge 中运行

javascript - JQuery Ajax 强制页面刷新

javascript - 使用 Redux Reselect 过滤评论

html - 如何在html中的图像上添加 Logo 和菜单

php - 有没有办法在运行 composer 命令时隐藏 "funding"消息?