简体   繁体   English

Dompdf将画布转换为pdf

[英]Dompdf convert canvas to pdf

I'm trying to print a PDF with Dompdf filled with canvas elements. 我正在尝试使用填充了canvas元素的Dompdf打印PDF。

I can include and print png images with no problem but when trying to include a canvas and then convert it to a png it just won't display it in the exported PDF (no broken image, etc). 我可以毫无问题地包含和打印png图像,但是当尝试包含画布然后将其转换为png时,它将不会在导出的PDF中显示它(没有损坏的图像等)。

What to do? 该怎么办?

It is a Codeigniter project: 这是一个Codeigniter项目:

Loading view in controller with Dompdf: 使用Dompdf在控制器中加载视图:

$this->load->library('pdf');
$this->pdf->load_view('print_pdf', $data);
$this->pdf->render();
$this->pdf->stream("new_pdf_file.pdf");

View to be printed: 要打印的视图:

<!doctype and so on..>

<canvas id="myCanvas" width="578" height="200"></canvas>

<script>
   context.beginPath();
   context.moveTo(170, 80);
   context.bezierCurveTo(130, 100, 130, 150, 230, 150);
   context.closePath();
   context.lineWidth = 5;
   context.fillStyle = '#8ED6FF';
   context.fill();
   context.strokeStyle = '#0000ff';
   context.stroke();

   var canvas = document.getElementById("myCanvas");
   var img = canvas.toDataURL("image/png");

   $(document).ready(function() {
      $('<img />', { 
         src: img
      });
      img.appendTo($('#testDiv'));
   });
</script>

<div id="testDiv">

</div>

<../html>

DomPDF is a HTML to DOM to PDF parser not a full fledged web browser. DomPDF是一个HTML到DOM到PDF解析器,而不是一个完整的Web浏览器。

Things are bound to not always work as intended and there may be differences in rendering. 事情必定并不总是按预期工作,并且渲染可能存在差异。

If the canvas would be as simple as in the example you've provided there is no need to make it with javascript - just save it as png an include with <img src=""/> 如果画布就像你提供的示例一样简单,则无需使用javascript - 只需将其保存为包含<img src=""/> png

If the picture generated on the canvas is more complicated and is dependent on the $data passed to view - which is probably the case - then you still have an option to use PHP to generate SVG (either view inline PHP or in the controller and passed with $data ). 如果在画布上生成的图片更复杂并且依赖于传递给视图的$data - 可能就是这种情况 - 那么您仍然可以选择使用PHP来生成SVG(查看内联PHP或在控制器中传递并传递与$data )。

If SVG is not an option then you can use PHP GD (or other library) to generate the image and either save it in temporary location (and include the file in src="path/to/file.png" ) or transform the image to data URI and embed it in the view. 如果SVG不是一个选项,那么您可以使用PHP GD(或其他库)生成图像并将其保存在临时位置(并将文件包含在src="path/to/file.png" )或转换图像到数据URI并将其嵌入视图中。

Personally, as a rule of thumb I wouldn't use anything more complex than a simple CSS and old plain HTML in the view 就个人而言,作为一个经验法则,我不会在视图中使用比简单的CSS和旧的纯HTML更复杂的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM