Is it possible to convert html template to PDF file in flutter

3.1k Views Asked by At

is it possible to convert an HTML file to pdf?

I have a ready-made HTML template form, and I have a flutter page as a form filling, I want to take the data after filling the form and compile it with the HTML template and convert it to PDF.

is it possible to do that?

what i'm doing at the moment is : filling the form in flutter app, the data saved in firebase, nodejs function take the data and compile it with html template and extract it to PDF and send it via email.

1

There are 1 best solutions below

0
Ahmad F On

Although the question might be a bit broad, let's give a simple answer.

is it possible to convert an HTML file to pdf?

Yes, it is.

Utilizing flutter_html_to_pdf would make it easy for you.


Example(s):

◾ HTML String:

final htmlContent =
"""
<!DOCTYPE html>
<html>
<head>
  <style>
  table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
  }
  th, td, p {
    padding: 5px;
    text-align: left;
  }
  </style>
</head>
  <body>
    <h2>PDF Generated with flutter_html_to_pdf plugin</h2>
    <table style="width:100%">
      <caption>Sample HTML Table</caption>
      <tr>
        <th>Month</th>
        <th>Savings</th>
      </tr>
      <tr>
        <td>January</td>
        <td>100</td>
      </tr>
      <tr>
        <td>February</td>
        <td>50</td>
      </tr>
    </table>
    <p>Image loaded from web</p>
    <img src="https://i.imgur.com/wxaJsXF.png" alt="web-img">
  </body>
</html>
""";

Thus:

final generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlContent(
    htmlContent, targetPath, targetFileName,);

◾ HTML File:

final file = File("assets/html/example.html");
final generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlFile(
    file, targetPath, targetFileName,);

◾ HTML File Path:

final filePath = "assets/html/example.html";
final generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlFilePath(
    filePath, targetPath, targetFileName,);

In your case, the file should be saved corresponding to the provided targetPath, therefore you can access it and send it as an email.