feder-cr/Jobs_Applier_AI_Agent_AIHawk · error · ValueError

Il contenuto HTML deve essere una stringa non vuota.

Error message

Il contenuto HTML deve essere una stringa non vuota.

What it means

Validation error from HTML_to_PDF: the html_content argument is not a string or is empty/whitespace-only. The function refuses to proceed because loading an empty data: URL into Chrome would produce a blank or broken PDF. Raised as a plain ValueError before any WebDriver work.

Source

Thrown at src/utils/chrome_utils.py:63

    except Exception as e:
        logger.error(f"Failed to initialize browser: {str(e)}")
        raise RuntimeError(f"Failed to initialize browser: {str(e)}")



def HTML_to_PDF(html_content, driver):
    """
    Converte una stringa HTML in un PDF e restituisce il PDF come stringa base64.

    :param html_content: Stringa contenente il codice HTML da convertire.
    :param driver: Istanza del WebDriver di Selenium.
    :return: Stringa base64 del PDF generato.
    :raises ValueError: Se l'input HTML non è una stringa valida.
    :raises RuntimeError: Se si verifica un'eccezione nel WebDriver.
    """
    # Validazione del contenuto HTML
    if not isinstance(html_content, str) or not html_content.strip():
        raise ValueError("Il contenuto HTML deve essere una stringa non vuota.")

    # Codifica l'HTML in un URL di tipo data
    encoded_html = urllib.parse.quote(html_content)
    data_url = f"data:text/html;charset=utf-8,{encoded_html}"

    try:
        driver.get(data_url)
        # Attendi che la pagina si carichi completamente
        time.sleep(2)  # Potrebbe essere necessario aumentare questo tempo per HTML complessi

        # Esegue il comando CDP per stampare la pagina in PDF
        pdf_base64 = driver.execute_cdp_cmd("Page.printToPDF", {
            "printBackground": True,          # Includi lo sfondo nella stampa
            "landscape": False,               # Stampa in verticale (False per ritratto)
            "paperWidth": 8.27,               # Larghezza del foglio in pollici (A4)
            "paperHeight": 11.69,             # Altezza del foglio in pollici (A4)
            "marginTop": 0.8,                  # Margine superiore in pollici (circa 2 cm)
            "marginBottom": 0.8,               # Margine inferiore in pollici (circa 2 cm)

View on GitHub (pinned to 79155b52fa)

Solutions

  1. Check what produces html_content upstream — fix the empty/None render (missing template variables, wrong template path).
  2. If reading from a file, open with mode='r' (text) or decode bytes: f.read().decode('utf-8').
  3. Guard before calling: if not html_content or not html_content.strip(): raise/log early with context.
  4. Pass the rendered template's actual output, not the template object (str(JinjaTemplate.render(...))).

Example fix

// before
html = template.render(user=user)  # may be '' if template path wrong
pdf_b64 = HTML_to_PDF(html, driver)

# after
html = template.render(user=user)
if not html or not html.strip():
    raise ValueError(f"rendered template is empty: {template_name}")
pdf_b64 = HTML_to_PDF(html, driver)
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(html_content, str) or not html_content.strip():
    raise ValueError(f"html_content empty or wrong type: {type(html_content).__name__}")

Type guard

def is_non_empty_str(x: Any) -> TypeGuard[str]:
    return isinstance(x, str) and bool(x.strip())

Try / catch

try:
    pdf_b64 = HTML_to_PDF(html, driver)
except ValueError as e:
    logger.error("refusing to render empty HTML: %s", e)
    # fix template/render upstream instead of retrying
    raise

Prevention

When it happens

Trigger: HTML_to_PDF('', driver), HTML_to_PDF(None, driver), or passing bytes/a template object instead of str; a template render that silently produced an empty string.

Common situations: Upstream template rendering failed silently and returned ''; passing file contents opened in binary mode; None from a failed fetch of the HTML; whitespace-only output from an empty Jinja template.

Related errors


AI-assisted analysis of feder-cr/Jobs_Applier_AI_Agent_AIHawk@79155b52fa (2026-08-28). Data as JSON: /api/errors/2b827afc6ea6d48a. Report an issue: GitHub.