0

I render the pdf page on canvas. Then, I want to save url created from canvas blob to array so that I can access outside of this method. I can save it to array. But when I console.log array it show me {key:Array(0)}instead of {key:Array(2)} . 0 should be 2 in my case because I added two values. I can see the values of array on console. But, could not access values by index outside of this method.

Outside the method:

outside the method

Inside the method (I show second output from loop so it show all values inside):

inside the method

In second output it shows Array(2) that are numbers of value inside.

I could not access the value with the index(a['key'][0]). It show undefined. When I try inside the function, It show desired output.

<?php
ob_start();
require_once('../../../library/tcpdf/tcpdf.php');
$pdf = new TCPDF();
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$html_p1 = 'Text messaging, or texting, is the act of composing and sending electronic messages, typically consisting of alphabetic and numeric characters, between two or more users of mobile devices, desktops/laptops, or other type of compatible computer. Text messages may be sent over a cellular network, or may also be sent via an Internet connection';
//echo $html;
$pdf->writeHTML($html_p1, true, 0, true, 0);
$pdf->AddPage();
$html_p2 = 'A telephone call is a connection over a telephone network between the called party and the calling party.';
$pdf->writeHTML($html_p2, true, 0, true, 0);
$base64PdfString = $pdf->Output('', 'E');
$base64PdfArray  = explode("\r\n", $base64PdfString);
$base64          = '';
for($i = 5; $i < count($base64PdfArray); $i++)
{
    $base64 .= $base64PdfArray[$i];
}

?>

<html>
    <head>
    <script type="text/javascript" src="../../../library/jquery/jquery-3.4.1.min.js"></script>
    <script type="text/javascript" src="../plugin/pdf-flipbook-master/pdfjs/build/pdf.js"></script>

    <script>
        //function
        const b64toBlob = (b64Data, contentType='', sliceSize=512) =>
            {
                const byteCharacters = atob(b64Data);
                const byteArrays = [];

                for (let offset = 0; offset < byteCharacters.length; offset += sliceSize)
                {
                    const slice = byteCharacters.slice(offset, offset + sliceSize);
                    const byteNumbers = new Array(slice.length);
                    for (let i = 0; i < slice.length; i++)
                    {
                        byteNumbers[i] = slice.charCodeAt(i);
                    }
                    const byteArray = new Uint8Array(byteNumbers);
                    byteArrays.push(byteArray);
                }

                const blob = new Blob(byteArrays, {type: contentType});
                return blob;
            }
            function getCanvasBlob(canvas) 
            {
              return new Promise(function(resolve, reject) 
              {
                canvas.toBlob(function(blob) 
                {
                  resolve(blob)
                })
              })
            }
    </script>
        <script>

            $(document).ready(() =>
                {
                    const contentType   ='application/pdf';
                    const b64Data       ='<?php echo $base64;?>';
                    const blob          =b64toBlob(b64Data, contentType);
                    const blobUrl       =URL.createObjectURL(blob);

                    var a={key:[]};
                        PDFJS.getDocument({ url: blobUrl }).then(function(pdf_doc)
                        {

                            __PDF_DOC       = pdf_doc;
                            __TOTAL_PAGES   = __PDF_DOC.numPages;

                            var div_container = document.querySelector('.flipbook');
                            for(let i=1; i<=__TOTAL_PAGES; i++) 
                            {
                                pdf_doc.getPage(i).then(function(page)
                                    {

                                        var scale = 1;
                                        var viewport = page.getViewport(scale);

                                        var pag1        =document.createElement('canvas');
                                        //pag1.id           ='Pg_1';
                                        //$("#Pg_1").hide();
                                        var context1    =pag1.getContext('2d');
                                        pag1.height     =viewport.height;
                                        pag1.width      =viewport.width;

                                        var renderContext =
                                        {
                                            canvasContext: context1,
                                            viewport: viewport
                                        };

                                        page.render(renderContext).then(function()
                                            {
                                                div_container.appendChild(pag1);
                                                pag1.toBlob(function(blob)
                                                {
                                                    var burl                        =URL.createObjectURL(blob);
                                                    a['key'].push(burl);
                                                    console.log(a);
                                                    console.log(a['key'][0]);
                                                }, 'image/png');


                                                /*c_blob=getCanvasBlob(blob);
                                                c_blob.then(function(blob) 
                                                {
                                                         //do stuff with blob
                                                        var burl                        =URL.createObjectURL(blob); 
                                                        a['key'].push(burl);    
                                                }, function(err) {
                                                    console.log(err)
                                                });*/
                                                //$("#Pg_1").remove();

                                            });
                                    });
                            }

                        })
            console.log(a['key'][0]);
            console.log(a);
            //b={key:[]}
            //b['key'].push(1234);
            //console.log(b);
                })
        </script>
    </head>
    <body>
    <div class="flipbook"></div>
    </body>
</html>

Thanks in advance.

1 Answer 1

0

Variable a is inside the anonymous function that runs when the document is ready -- it is not globally scoped. It will work if you move the line

var a={key:[]};

before the line

$(document).ready(() =>

which will make it a global variable.

1
  • Thank you for response. @Samyok Nepal, I tried. But , still showing same result.
    – Premlatha
    Jan 10, 2020 at 3:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.