vitorric / html2pdf

MIT License
10 stars 0 forks source link

How can I include images? #1

Open JoelGarcia99 opened 1 year ago

JoelGarcia99 commented 1 year ago

Hi, I've defined an HTML template to generate PDFs on the server side using Nest.js, here's the HTML code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.tailwindcss.com"></script>
  </head>
  <body class="p-2">
    <head class="flex flex-col">
      <div class="flex flex-col justify-start items-center">
        <div id="head-date" class="w-full flex flex-start flex-row">
          <small class="text-xs">Hermes | Anomalías :time</small>
        </div>
      </div>
      <div id="logos-head" class="px-[4rem] py-[2rem] flex flex-row justify-center w-full items-center">
        <img 
          class="w-[7rem]"
          src="/app/src/pdf-util/images/rocafuerte alcaldia.png" 
          alt=""
        >
        <div class="flex w-full flex-col justify-center px-2 items-center flex-wrap">
          <h1 class="text-xl font-bold text-center">
            REPORTE DE ANOMALÍAS DEL SISTEMA HERMES
          </h1>
          <span>Desde :startDate hasta :endDate</span>
        </div>
        <img 
          class="w-[7rem]"
          src="../images/transito rocafuerte.png" 
          alt=""
        >
      </div>
    </head>
  </body>
</html>

An as you can see, I'm using some img tags with absolute and relative paths to some images stored on the server, both of them fail rendering the image. Even if I use an image from the internet and paste its url it doesn't work. Here's the TypeScript code:

  async generate(
    startDate: string,
    endDate: string
  ) {

    const bufferFile = fs.readFileSync('/app/src/pdf-util/templates/anomalies.html', {
      encoding: 'utf-8',
    });

    const options: HTML2PDFOptions = {
      format: 'A4',
      landscape: false,
      resolution: {
        height: 1920,
        width: 1080,
      },
    };

    let replacements = {
      ":time": dayjs().format('YYYY/MM/DD HH:mm'),
      ":startDate": startDate,
      ":endDate": endDate
    };

    let replaced = bufferFile;

    for (const [key, value] of Object.entries(replacements)) {
      replaced = replaced.replace(key, value);
    }

    let pdf = await html2pdf.createPDF(replaced, options);

    return pdf;
  }

Do I have to configure something?

vitorric commented 1 year ago

Hello @JoelGarcia99,

Try to convert your images to base64 or upload them to a cdn, and then you can use it.

maxrks commented 10 months ago

<img src="data:image/png;base64, BASE64STRING">