Save pdf file local and on webserver with html2pdf.js

134 Views Asked by At

UPDATE: I solved this problem.

See this javascript code:

 const pdfData = pdf.output('blob');
    const formData = new FormData();

    formData.append('pdf', pdfData, 'document.pdf');
    formData.append('filename', filename); // Hier den Dateinamen hinzufügen

    fetch('/pdf.php', {
      method: 'POST',
      body: formData
    })
      .then(response => response.text())
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));

And php:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $pdfContent = file_get_contents($_FILES['pdf']['tmp_name']);


    $uploadPath = '/absolute/path/to/folder/';
    $fileName = $_POST['filename'] . '.pdf';
    $targetPath = $uploadPath . $fileName;

    if (move_uploaded_file($_FILES['pdf']['tmp_name'], $targetPath)) {
        echo "Die PDF-Datei wurde erfolgreich gespeichert2.";
    } else {
        http_response_code(500);
        echo "Es gab ein Problem beim Speichern der Datei.";
    }
} else {
    http_response_code(400);
    echo "Ungültige Anfrage.";
}
?>


Currently I am struggling with downloading the pdf file to my webserver. This is my current situation: I am testing my development in a local development scenario. I have a index.html as well as a javascript file for the generation of the pdf.

This is my code generating the pdf:

    function generatePDF() {
  const content = document.getElementById('site');

  const opt = {
    margin: 1,
    filename: filename,
    image: { type: 'jpeg', quality: 0.99 },
    html2canvas: { scale: 2 },
    jsPDF: { unit: 'mm', format: 'letter', orientation: 'portrait' },
    pagebreak: { before: '#bestaetigung' },
  }

  html2pdf().from(content).set(opt).toPdf().get('pdf').then(function (pdf) {
    var totalPages = pdf.internal.getNumberOfPages();

    for (let i = 1; i <= totalPages; i++) {
      pdf.setPage(i);
      if (i === totalPages) {
        // Nur auf der letzten Seite den Footer hinzufügen
        pdf.setFontSize(8);
        pdf.setTextColor(150);
        pdf.text(formattedDateUK + ' ' + time + ' ' + besteller.toLocaleString(), pdf.internal.pageSize.getWidth() - 50, pdf.internal.pageSize.getHeight() - 8);
      }
    }
  }).save();
}

Is it possible to download the file to the computer of the user AND to a folder on the webserver without using NodeJS or something like that? Note: I am generating the filename dynamically: let filename = formattedDate + "_" + besteller + "_Getränkebestellung";

BR Mark

0

There are 0 best solutions below