Thursday, March 31, 2022

Easy APEX email using JsPDF

 In my previous post, I explained how to easily create a PDF document of a part of a web page created with APEX.

Now that we know how to create, download and possibly print the PDF, the question arises: can we email this PDF file?

So, here is our APEX again, now with button Email:



The JavaScript to create the PDF file is more or less the same. Instead of downloading the file, we now upload the file to the database, and email the file from there using APEX_MAIL.

The JavaScript function called from the Click Dynamic Action is:


function mailJsPDF() {
    // This isn't mentioned anywhere, but it is needed since 2.0!
    window.jsPDF = window.jspdf.jsPDF;
    var doc = new jsPDF ();
    doc.html(document.getElementById('container'), {
       callback: function (doc) {
         // Save blob:
         var blob = new Blob ( [doc.output('blob')], {type: 'application.pdf'} );
         // Base64 encode:
         var reader = new FileReader();
         reader.onload = function () {
            // Since it contains the Data URI, we should remove the prefix and keep only Base64 string
            var b64 = reader.result.replace(/^data:.+;base64,/, '');
            //Send the blob to the server via Ajax process
            apex.server.process(
              'UPLOAD',
               {
                 p_clob_01: b64
               },
               {
                success: function(data) {
                    alert("The invoice was mailed");
                 }
               }
            );
         };
         reader.readAsDataURL(blob);
       },
            width: 170,
        windowWidth:700,
        margin: [20, 0, 0, 20],
        html2canvas: {
          scale: .238
        }    
    });
  }

The UPLOAD process gets the uploaded CLOB, converts it back to a BLOB, and emails it as an attachment. In a real application you will probably also store the generated PDF file in the database, get the email address from the website etc.

declare
  l_clob   clob;
  l_blob   blob;
  l_id     number;
begin
  --Get the clob passed in from the Ajax process
  l_clob := apex_application.g_clob_01;
  apex_debug.message('Uploaded: '||dbms_lob.substr(l_clob, 200, 1));

  -- Covert it back to a blob
  l_blob := APEX_WEB_SERVICE.CLOBBASE642BLOB (p_clob => l_clob);

  l_id := APEX_MAIL.SEND(
        p_to        => 'you@gmail.com',
        p_from      => 'me@gmail.com',
        p_subj      => 'Invoice with attachment',
        p_body      => 'Goodday, see the attachment.',
        p_body_html => 'Goodday, see the attachment.');
  APEX_MAIL.ADD_ATTACHMENT(
        p_mail_id    => l_id,
        p_attachment => l_blob,
        p_filename   => 'invoice.pdf',
        p_mime_type  => 'application/pdf');
  COMMIT;
  APEX_MAIL.PUSH_QUEUE();
 
  --Write some JSON out for the response
  apex_json.open_object();
  apex_json.write('status', 'success');
  apex_json.close_object();  
end;