Puppeteer PDF generator [closed]

I’m currently working on implementing a PDF generation feature where the frontend sends a user ID to the backend, which then uses Puppeteer to create the PDF. As a junior frontend developer, this is a challenging task for me. My supervisor has set up Entities and Serializers system to handle all data going to and from the backend, which helps streamline our development process. I want to send the userId to the backend when the user press the button to download the PDF, the backend then creates a PDF using handlebars or html and puppeeter, then return this PDF to the frontend allowing the user to download the PDF.

This is the formula in the front end

interface PropsForFxclusion {
  id: string;
  nome?: string;
  finalized?: boolean;
  pdf: Buffer;
}
async function handleFindJsonToPDF(id: string) {
    const token = Cookies.get('auth_token');
    const backendApi = new BackendApiGet(token);
    setIsLoadingPdf(true);
  
    try {
      const response = await backendApi.generatePDF(id);
  
      if (!Array.isArray(response) || response.length === 0) {
        throw new Error('Invalid response format or empty data');
      }
  
      const pdfBuffer = response[0].pdf;
  
      const blob = new Blob([pdfBuffer], { type: 'application/pdf' });
  
      const url = window.URL.createObjectURL(blob);
  
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = `${id}.pdf`;
      document.body.appendChild(a);
      a.click();

      window.URL.revokeObjectURL(url);
    } catch (error) {
      handleApiErrors(error, setError, setMsgError);
    } finally {
      setIsLoadingPdf(false);
    }
  }

<div className={styles.container}>
      {isLoadingPdf && <ComponentInfos message={'Your pdf is being generated'} />}
      {props.finalized ? (
        <Tooltip text="Download PDF">
          <Action
            icon={renderIcon(MdOutlineFileDownload)}
            onClick={() => handleFindJsonToPDF(props.id)}
          />
        </Tooltip>

Backend code

const fs = require('fs-extra');
const hbs = require('handlebars');
const puppeteer = require('puppeteer');
const path = require('path');
const connection = require("../../connection");

async function fetchPDFDataById(id) {
  const query = `
    SELECT a.*, c.*
    FROM files f
    JOIN files_criteria c ON f.id = c.id_files
    JOIN users u ON a.id_ee = u.id_ee
    WHERE a.id_user = $1
  `;
  const { rows } = await connection.query(query, [id]);
  return rows;
}

async function compileHTML(templatePath, data) {
  const template = await fs.readFile(templatePath, 'utf8');
  const compiledTemplate = hbs.compile(template);
  return compiledTemplate(data);
}

async function generatePDF(htmlContent) {
  try {
    const browser = await puppeteer.launch({
      headless: true,
      args: ['--no-sandbox', '--disable-setuid-sandbox'],
    });
    const page = await browser.newPage();
    await page.goto('about:blank', { timeout: 60000 });
    await page.setContent(htmlContent);

    const pdfBuffer = await page.pdf({
      format: 'A4',
      printBackground: true,
      timeout: 60000
    });

    await browser.close();
    return pdfBuffer;
  } catch (error) {
    console.error('Error generating Puppeteer:', error);
    throw error;
  }
}

async function GeneratePDF(req, res) {
  const { id } = req.user;
  console.log("arrived here")
  console.log(id)
  if (!id) {
    return res.status(400).json({ menssage: "Missing user ID" });
  }

  try {
    const dataRows = await fetchPDFDataById(id);

    if (!dataRows || dataRows.length === 0) {
      return res.status(404).json({ ,message: "No file for this user" });
    }

    const data = dataRows.map(row => ({
      dateofobservation: row.dateofobservation,
    }));

    const templatePath = path.join(__dirname, 'pdf.hbs');
    const htmlContent = await compileHTML(templatePath, { data });

    const pdfBuffer = await generatePDF(htmlContent);

    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename=pdfgenerate.pdf');
    console.log(typeof(pdfBuffer))
    return res.send(pdfBuffer);
  } catch (error) {
    console.error('Error generating PDF:', error);
    return res.status(500).json({ message: "Failing generating PDF" });
  }
}

module.exports = {
  GeneratePDF,
};

HBS file

<html>
<head>
  <meta charset="utf-8">
  <title>PDF Template</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      line-height: 1.6;
      margin: 20px;
    }
    .header {
      text-align: center;
      margin-bottom: 20px;
    }
    .data-table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }
    .data-table th, .data-table td {
      border: 1px solid #ddd;
      padding: 8px;
    }
    .data-table th {
      background-color: #f2f2f2;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>PDF Report</h1>
  </div>
  
  <table class="data-table">
    <thead>
      <tr>
        <th>Date of Observation</th>
      </tr>
    </thead>
    <tbody>
      {{#each data}}
      <tr>
        <td>{{dateofobservation}}</td>
      </tr>
      {{/each}}
    </tbody>
  </table>
  
</body>
</html>

  • I am testing sending only one parameter

Is generating a PDF that I cannot even open

I don’t even know what can I try anymore, I am really stuck.

The error I was getting before was

Type 'EntitiesGeneratePDF[]' is not assignable to type 'BlobPart'.
  Type 'EntitiesGeneratePDF[]' is missing the following properties from type 'Blob': size, type, arrayBuffer, stream, textts(2322)

New contributor

Gustavo Cortez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật