0

I am struggling with html2pdf - when trying to add the pdf to an email. It is a simple php-form on bootstrap, a modal, and some other nasty code - all works well. Until I come to this part:

The PDF-Creation: The download version works without issues, yet the pdf which should go with the email remains empty. I have no idea, where I am going the wrong path, so any kind of help would be highly appreciated (as usual) These are my scripts - the "generatePDF" works perfect, yet the 2nd one not:

<script>
        function generatePDF() {
        // Choose the element that our container is rendered in.
        const element = document.getElementById("form1");
        var opt = {
        margin:       0.5, //margin for pages
        filename:     '<?php echo $_POST['Consultant-Nummer']; ?>.pdf',
        html2canvas:  { scale: 2 },
        jsPDF:        { unit: 'cm', format: 'A4', orientation: 'portrait' },
        pagebreak:    { mode: [ 'css', 'legacy'] } //It determines how HTML elements should be split.    
        };

        // Choose the element and save the PDF for our user.  
        html2pdf(element, opt);
    }
        </script> 



    <script>
        window.onload = function pdfDivload (){
setTimeout( function pdfDivload (){            
let el = document.getElementById('form1');
let opt = {
    margin:       1,
    filename:     '<?php echo $_POST['Consultant-Nummer']; ?>.pdf',
    html2canvas:  { scale: 2 },
    jsPDF:        { unit: 'cm', format: 'A4', orientation: 'portrait' },
    pagebreak:    { mode: [ 'css', 'legacy'] } //It determines how HTML elements should be split.    
    };

html2pdf().set( opt ).from( el ).toPdf().output('datauristring').then(function( pdfAsString ) {
    let data = {
        'fileDataURI': pdfAsString,
    }
    $.post( "preview.php", data);
    console.log( data );
    } );
}, 3000);
        };
        </script>

So, where is the issue...?

Edit - here is the full code for this page, is submits the email correctly on load...:

<?php 
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
   require("src/PHPMailer.php");
   require("src/SMTP.php");
   require("src/Exception.php");

    if (array_key_exists('Consultant-Nummer', $_POST)) {
    $err = false;
    $msg = '';    
    $email = '';
        


    $pdfdoc     = $_POST['fileDataURI'];
    $b64file        = trim( str_replace( 'data:application/pdf;"Konform.pdf";base64,', '', $pdfdoc ) );
    $b64file        = str_replace( ' ', '+', $b64file );
    $decoded_pdf    = base64_decode( $b64file );
                if (!$err){
                $mail = new PHPMailer(true);
                $mail->isSMTP();
                // $mail->SMTPDebug = 3;
                $mail->SMTPSecure = 'tls';
                $mail->Host = 'hostname';
                // set a port
                $mail->Port = 587;
                $mail->SMTPAuth = true;
                // set login detail for gmail account
                $mail->Username = 'username';
                $mail->Password = 'password';
                $mail->CharSet = 'utf-8';
                // set subject
                $mail->setFrom('email', 'sendername');
                $mail->addAddress('recipient-email');
                $mail->addReplyTo('return-email');
              //  $mail->addAttachment($uploadfile);
                $mail->IsHTML(true);
                $mail->Subject = "Kontrollformular von: ".$_POST['Consultant-Nummer']."".$_POST['Land']." wegen Auftrag: ".$_POST['Rechnungsnummer']." vom ".$_POST['Rechnungsdatum']."";
                $mail->Body = "Some text goes here";
                $mail->addStringAttachment($decoded_pdf, "Kontrollformular ".$_POST['Consultant-Nummer'].".pdf",base64);
                // $mail->Body = "Hier sind die Daten: ".$_POST['form1']."";
                if (!$mail->send()) {
                    $msg .= "Mailer Error: " . $mail->ErrorInfo;
                } else {
                    header("Refresh:20; url=https://example.com/previouspage.php");
                    echo '<div class="alert alert-success alert-dismissible">';
   echo '<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>';
   echo '<strong>Dankeschön!</strong> Deine Daten sind jetzt zu uns unterwegs!';
 echo '</div>';
                                   }
            }
        } 
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>MK Online-Form</title>
<link rel="stylesheet" href="css/forms_control.css" type="text/css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">  
<script src="js/html2pdf.bundle.min.js" type="text/javascript"></script>
<script>
        function generatePDF() {
        // Choose the element that our container is rendered in.
        const element = document.getElementById("form1");
        var opt = {
        margin:       0.5, //margin for pages
        filename:     '<?php echo $_POST['Consultant-Nummer']; ?>.pdf',
        html2canvas:  { scale: 2 },
        jsPDF:        { unit: 'cm', format: 'A4', orientation: 'portrait' },
        pagebreak:    { mode: [ 'css', 'legacy'] } //It determines how HTML elements should be split.    
        };

        // Choose the element and save the PDF for our user.  
        html2pdf(element, opt);
    }
        </script> 
    <script>
        window.onload = function pdfDivload (){
setTimeout( function pdfDivload (){            
let el = document.getElementById('form1');
let opt = {
    margin:       1,
    filename:     '<?php echo $_POST['Consultant-Nummer']; ?>.pdf',
    html2canvas:  { scale: 2 },
    jsPDF:        { unit: 'cm', format: 'A4', orientation: 'portrait' },
    pagebreak:    { mode: [ 'css', 'legacy'] } //It determines how HTML elements should be split.    
    };

html2pdf().set( opt ).from( el ).toPdf().output('datauristring').then(function( pdfAsString ) {
    let data = {
        'fileDataURI': pdfAsString,
    }
    $.post( "preview.php", data);
    console.log( data );
    } );
}, 3000);
        };
        </script>
    
    </head>
<form spellcheck="false" enctype="multipart/form-data" method="post" name="form1" id="form1">
  <div class="container sub-page form1">
               <div class="row">
     <div class="col-25">
           </div>
           <div class="col-50">
        <img src="../img/thumbnail_Logo_Final.jpg" width="50%" title="Image">
           </div>
      <div class="col-25">
                   </div>
    </div>
    <h2>KONTROLLFORMULAR</h2>

                        <div class="row">
                            <div class="col-lg-6 text-center">
                                  <button type="button"  class="btn btn-success pull-left" onclick="generatePDF()" >PDF herunterladen</button>
                            </div>
                        </div> 
    <hr />
    <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
      <div class="panel panel-success">
        <div class="panel-heading" role="tab" id="generalHeading">
          <h4 class="panel-title">
            Your entries
          </h4>

        </div>
        <div id="generalInfo" class="panel-collapse collapse in" role="tabpanel">
          <div class="panel-body">
            <div class="form-horizontal">
                <div class="form-group">
<?php 
    foreach ($_POST as $key => $value) {
        echo '<label class="control-label col-md-4">' .$key.'</label>';
        echo '<div class="col-md-8"><input type="text" disabled name="'.$key.'" value="'.$value.'"/></div></br>';
    }
?>
              </div>

              </div> 
          </div>
        </div>
      </div>
      </div>
    </div>
    </form>
      </html>
  • It will be either that the PDF string you're generating on the client side is not being submitted correctly, or you're not handling that submission correctly in PHP. Either way we can't tell without seeing your PHP code, since that's where it all happens. – Synchro Nov 18 '21 at 17:22
  • @Synchro added the full code for the page, it auto-submits on load. Thanks! – Dimitri Vlaanderen Nov 19 '21 at 09:18
  • In your call to `addStringAttachment`, you’ve used a bare string as the encoding value, which will treated as an undeclared constant and trigger a warning. Since you are providing a filename with an extension, you can skip that anyway and it will be set automatically. – Synchro Nov 20 '21 at 13:01
  • Enable debug output and you should be able to see the encoded PDF in the SMTP traffic, so inspect that carefully. – Synchro Nov 20 '21 at 13:02
  • @Synchro - debug from function as it is: Error in function Object.m (/conform/js/html2pdf.bundle.min.js:6:25951): Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range. Trying to get that fixed now... https://stackoverflow.com/questions/23223718/failed-to-execute-btoa-on-window-the-string-to-be-encoded-contains-characte – Dimitri Vlaanderen Nov 20 '21 at 16:50
  • @Synchro: I am lost with that topic. I have no idea, where to add that "latin-1 Fix". Do you happen to know, where to put this, in order to get it working? Issue is, I will need to keep using ü. ö. ä ß - typical German characters... :( – Dimitri Vlaanderen Nov 21 '21 at 17:47
  • I'm not the one to ask about JS issues, but I would guess that you should be working in UTF-8 everywhere, not latin-1, to avoid problems like this. I'd have a look at exactly what is the content that's failing to be encoded properly – perhaps the filename? – Synchro Nov 21 '21 at 19:15

0 Answers0