Home » Javascript » How do I add JavaScript into FPDF?

How do I add JavaScript into FPDF?

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’m using FDPF and I want to add a JavaScript chart that I created with D3 into the pdf. I was able to visualize the chart into an HTML webpage with the following code. I’m simply appending the chart into the div id “chart.”

<!-- Circular Bar Chart start -->
<div class="row">
    <div class="large-12 large-centered columns chart-container">
        <h2>Circular Bar Chart</h2>
        <div id="chart" class="text-center"></div>
    </div>
</div>                                                                                                        

Usually, when you add an image into a PDF with FDPF you use the following code. I’m simply appending the chart to the div id “chart”

// Insert image
$pdf->Image('images/graphic_cropped.jpg',15,3,130);

How can I insert the chart that I generated with D3 into my PDF with FPDF?

Answers:

Since FDPF is a server-side (php) library and you are generating the image on the client, you need to do something like this:

  • Generate the chart
  • Save chart to SVG (see, for example this question)
  • Encode the image into base64 string (see, for example this)
  • Post the image to your php server (I think you can find how to POST data from javascript to php and you already have your image as a string)
  • On php side – decode the base64 string back to binary image
  • Now use FDPF to insert the image into PDF

You may also consider generating PDF on the client side.