spipu / html2pdf

OFFICIAL PROJECT | HTML to PDF converter written in PHP
http://html2pdf.fr/en/default
Open Software License 3.0
1.68k stars 751 forks source link

How do I add an image to a header and footer pdf? #791

Closed rogigs closed 8 months ago

rogigs commented 8 months ago

My solution isn't working and doesn't generate any errors in the terminal. How can I solve my problem? I need an image in the footer and header. I tried putting an image in the header, but it doesn't work and my PDF isn't being saved.

 const pdf = this.pdf.nativeElement;

    html2pdf()
      .from(pdf)
      .set({
        margin: [25, 15, 25, 15],
        filename: 'name.pdf',
        image: { type: 'png', quality: 1 },
        html2canvas: {
          scale: 2,
          dpi: 192,
          letterRendering: true,
          useCORS: true,
        },
        jsPDF: { unit: 'mm', format: 'a4', orientation: 'p' },
        pagebreak: { mode: 'avoid-all' },
      })
      .toPdf()
      .get('pdf')
      .then(function (pdf) {
        const totalPages = pdf.internal.getNumberOfPages();
        const date = '10/10/2024';
        const width = pdf.internal.pageSize.getWidth();
        const height = pdf.internal.pageSize.getHeight();

        for (let i = 1; i <= totalPages; i++) {
          pdf.setPage(i);
          pdf.setFontSize();

          // Header
          const img = new Image();
          img.src = images.logo // it's a base64 ->data:image/png;base64, ...;
          img.height = 10;
          img.width = 10;
          pdf.addImage(img, 'PNG', 10, 78, 12, 15);

          // Footer
          pdf.line(0, height - 25, width, height - 25);
          pdf.setTextColor(11, 67, 110);
          pdf.text('Relatório emitido para', width - 35, height - 20);
        }
      })
      .save();

I'm trying to put this into an Angular 14.2.3 project

rogigs commented 8 months ago

[Solved] I had problems with the structure of my compents that for any reason affected to build a image in pdf. The following code also helped:

 const imgHeader = new Image();
 imgHeader.src = '../../../../../assets/images/logo/logo.png';
 pdf.addImage(imgHeader, 'png', 15, 5, 10, 10);