pdf.jsturnjs

TurnJsError:The page 1 does not exist


I am creating flipbook from pdf blob using turnjs. I create blob image url for each page by canvas.toBlob, add that url to div and placed that div in flipbook div. But, I receive this error:

TurnJsError:The page 1 does not exist

I did same way for creating flipbook from blob images. That run successfully. When I compare in inspect elements tab, I found that div that have blob source missing two outer div layer (<div class="page-wrapper" page="1" style="position: absolute; overflow: hidden; width: 461px; height: 600px; top: 0px; right: 0px; left: auto; z-index: 2;">,<div style="position: absolute; top: 0px; left: 0px; overflow: hidden; z-index: auto; width: 757px; height: 757px;">). I thought this will created automatically when we add image with div to flipbook div because I did not do any extra action in flipbook from blob images to make it run. I will attach both codes.

Flipbook from blob images

<?php
include 'function.php';
//blob images from sql
$array_image        =GetSqlData_Assoc($query_getimg,$db);
 /*
 var_dump of $array_image
array(2) 
{
[0]=>
 array(1) 
   {
    ["File"]=>blob
   }
[1]=>
 array(1) 
   {
    ["File"]=>blob
   }
 }
*/
$array_image_encode =array();

foreach($array_image as $key=>$value)
{
    $base64_encode          =base64_encode($value['file']);
    $array_image_encode[]   =$base64_encode;        

}

?>

<!doctype html>
<!--[if lt IE 7 ]> <html lang="en" class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!--> <html lang="en"> <!--<![endif]-->
<head>
<meta name="viewport" content="width = 1050, user-scalable = no" />
<script type="text/javascript" src="plugin/turnjs4/extras/jquery.min.1.7.js"></script>
<script type="text/javascript" src="plugin/turnjs4/extras/modernizr.2.5.3.min.js"></script>
<script>
    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;
    }
    $( document ).ready(function() {

        var options = {
                                    pages:
                                    [
/*                                    {src:blobUrl},*/                                 
                                    ]
                                };    

                var array_sql_imgs = <?php echo JSON_encode($array_image_encode); ?>;


                for(var i=0; i<array_sql_imgs.length; i++)
                {
                    //alert(jArray[i]);
                    var img     =array_sql_imgs[i];
                    const contentType   ='image/jpeg';
                    const b64Data       =img;
                    const blob          =b64toBlob(b64Data, contentType);
                    //console.log(blob);
                    const blobUrl       =URL.createObjectURL(blob);
                    options['pages'].push(blobUrl);
                }
                //console.log(options);
                var div_container = document.querySelector('#flipbook');
                for(j=0;j<options['pages'].length;j++)
                {
                        url                             = options['pages'][j];
                        //console.log(url);
                        var element                     = document.createElement("div");
                        element.style.backgroundImage   = "url(" + url + ")";
                        div_container.appendChild(element);
                }
    })
</script>

</head>

<body>

<div class="flipbook-viewport">
    <div class="container">
        <div class="flipbook" id="flipbook">

        </div>
    </div>
</div>


<script type="text/javascript">

function loadApp() {

    // Create the flipbook

    $('.flipbook').turn({
            // Width

            width:922,

            // Height

            height:600,

            // Elevation

            elevation: 50,

            // Enable gradients

            gradients: true,

            // Auto center this flipbook

            autoCenter: true

    });
}

// Load the HTML4 version if there's not CSS transform

yepnope({
    test : Modernizr.csstransforms,
    yep: ['plugin/turnjs4/lib/turn.js'],
    nope: ['plugin/turnjs4/lib/turn.html4.min.js'],
    both: ['plugin/turnjs4/samples/basic/css/basic.css'],
    complete: loadApp
});

</script>

</body>
</html>

Flipbook from Pdf blob

<?php
ob_start();
require_once('plugin/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];
}
//$pdf->lastPage();
//$pdf_file = $pdf->Output('test_flipbook.pdf', 'S');
//$pdf_file = $pdf->Output('test_flipbook.pdf', 'I');
//$base64_encode = base64_encode($pdf->Output('test_flipbook.pdf', 'I'));
?>

<!doctype html>
<html>
    <head>
        <meta name="viewport" content="width = 1050, user-scalable = no" />
        <script type="text/javascript" src="plugin/turnjs4/extras/jquery.min.1.7.js">
        </script>
        <script type="text/javascript" src="plugin/turnjs4/extras/modernizr.2.5.3.min.js">
        </script>
        <script type="text/javascript" src="plugin/turnjs4/lib/turn.js">
        </script>
        <script type="text/javascript" src="plugin/pdfjs_ex/pdf.js">
        </script>

        <script type="text/javascript">
            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;
            }

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

                    const blobUrl       =URL.createObjectURL(blob);

                    PDFJS.getDocument({ url: blobUrl }).then(function(pdf_doc)
                        {
                            var options =
                            {
                                pages:
                                [
                                ]
                            };
                            __PDF_DOC       = pdf_doc;
                            __TOTAL_PAGES   = __PDF_DOC.numPages;

                            var div_container = document.querySelector('#flipbook');
                            for(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);
                                                var dataUrl =pag1.toDataURL();


                                                pag1.toBlob(function(blob)
                                                    {

                                                        var burl                        =URL.createObjectURL(blob);
                                                        options['pages'].push(burl);
                                                        $("#Pg_1").remove();
                                                        var element                     = document.createElement("div");
                                                        element.style.backgroundImage   = "url(" + burl + ")";
                                                        element.style.width             = '600px';
                                                        element.style.height            = '922px';
                                                        div_container.appendChild(element);

                                                    }, 'image/png');

                                            });
                                    });
                            }

                        })

                });

        </script>
    </head>
    <body>

        <div class="flipbook-viewport">
            <div class="container">
                <div class="flipbook" id="flipbook">

                </div>
            </div>
        </div>

        <script type="text/javascript">

            function loadApp()
            {

                // Create the flipbook

                $('.flipbook').turn(
                    {
                        // Width

                        width:922,

                        // Height

                        height:600,

                        // Elevation

                        elevation: 50,

                        // Enable gradients

                        gradients: true,

                        // Auto center this flipbook

                        autoCenter: true

                    });
            }

            // Load the HTML4 version if there's not CSS transform

            yepnope(
                {
                    test : Modernizr.csstransforms,
                    yep: ['plugin/turnjs4/lib/turn.js'],
                    nope: ['plugin/turnjs4/lib/turn.html4.min.js'],
                    both: ['plugin/turnjs4/samples/basic/css/basic.css'],
                    complete: loadApp
                });

        </script>




    </body>
</html>

Thanks in advance.


Solution

  • I define $('#book').turn and then add pages using turnjs method. It adding the wrapper on div holding the blob.

     <?php
    ob_start();
    require_once('plugin/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];
    }
    ?>
    
    <!doctype html>
    <html>
        <head>
            <style type="text/css">
                body
                {
                    background: #ccc;
                }
                #book
                {
                    width: 800px;
                    height: 500px;
                }
    
                #book .turn-page
                {
                    background-color: white;
                }
    
                #book .cover
                {
                    background: #333;
                }
    
                #book .cover h1
                {
                    color: white;
                    text-align: center;
                    font-size: 50px;
                    line-height: 500px;
                    margin: 0px;
                }
    
                #book .loader
                {
                    background-image: url(loader.gif);
                    width: 24px;
                    height: 24px;
                    display: block;
                    position: absolute;
                    top: 238px;
                    left: 188px;
                }
    
                #book .data
                {
                    text-align: center;
                    font-size: 40px;
                    color: #999;
                    line-height: 500px;
                }
    
                #controls
                {
                    width: 800px;
                    text-align: center;
                    margin: 20px 0px;
                    font: 30px arial;
                }
    
                #controls input, #controls label
                {
                    font: 30px arial;
                }
    
                #book .odd
                {
                    background-image: -webkit-linear-gradient(left, #FFF 95%, #ddd 100%);
                    background-image: -moz-linear-gradient(left, #FFF 95%, #ddd 100%);
                    background-image: -o-linear-gradient(left, #FFF 95%, #ddd 100%);
                    background-image: -ms-linear-gradient(left, #FFF 95%, #ddd 100%);
                }
    
                #book .even
                {
                    background-image: -webkit-linear-gradient(right, #FFF 95%, #ddd 100%);
                    background-image: -moz-linear-gradient(right, #FFF 95%, #ddd 100%);
                    background-image: -o-linear-gradient(right, #FFF 95%, #ddd 100%);
                    background-image: -ms-linear-gradient(right, #FFF 95%, #ddd 100%);
                }
            </style>
            <script type="text/javascript" src="plugin/turnjs4/extras/jquery.min.1.7.js">
            </script>
            <script type="text/javascript" src="plugin/turnjs4/extras/jgestures.min.js">
            </script>
            <script type="text/javascript" src="plugin/turnjs4/extras/jquery-ui-1.8.20.custom.min.js">
            </script>           
            <script type="text/javascript" src="plugin/turnjs4/extras/jquery.mousewheel.min.js">
            </script>
            <script type="text/javascript" src="plugin/turnjs4/extras/modernizr.2.5.3.min.js">
            </script>
            <script type="text/javascript" src="plugin/turnjs4/lib/turn.js">
            </script>
            <script type="text/javascript" src="plugin/turnjs4/lib/zoom.js">
            </script>           
            <script type="text/javascript" src="plugin/pdfjs_ex/pdf.js">
            </script>
            <script>
                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 addPage(page, book, pdf_doc)
                {
                    //  First check if the page is already in the book
                    if (!book.turn('hasPage', page))
                    {
                        // Create an element for this page
                        var element = $('<div />', {'class': 'page '+((page%2==0) ? 'odd' : 'even'), 'id': 'page-'+page}).html('<i class="loader"></i>');
                        // If not then add the page
                        book.turn('addPage', element, page);
    
                        pdf_doc.getPage(page).then(function(p)
                                        {
    
                                            var scale = 1;
                                            var viewport = p.getViewport(scale);
    
                                            var pag1        =document.createElement('canvas');
                                            pag1.id         ='Pg_1';
    
                                            var context1    =pag1.getContext('2d');
                                            pag1.height     =viewport.height;
                                            pag1.width      =viewport.width;
    
                                            var renderContext =
                                            {
                                                canvasContext: context1,
                                                viewport: viewport
                                            };
    
                                            p.render(renderContext).then(function()
                                                {
                                                    pag1.toBlob(function(blob)
                                                    {
                                                        var burl                        =URL.createObjectURL(blob);                                                         
    
                                                    setTimeout(function()
                                                    {                                                       
                                                        element.html('<div style="background-image:url('+burl+'); width: 400px; height: 500px; background-size: cover;"></div><div style="top: 0px; left: 0px; overflow: hidden; z-index: 1; width: 461px; height: 600px;"></div>');
    
                                                    }, 1000);
                                                    })
                                                })
                                        })                                                                      
                    }
                }
            </script>           
        </head>
        <body>    
            <div id="book">             
            </div>    
            <script type="text/javascript">
                // Adds the pages that the book will need    
                $(window).ready(function()
                    {
                        const contentType   ='application/pdf';
                        const b64Data       ='<?php echo $base64;?>';
                        const blob          =b64toBlob(b64Data, contentType);
    
                        const blobUrl       =URL.createObjectURL(blob);
                        PDFJS.getDocument({ url: blobUrl }).then(function(pdf_doc)
                        {
                            __PDF_DOC       = pdf_doc;
                            __TOTAL_PAGES   = __PDF_DOC.numPages;
    
                            $('#book').turn(
                            {
                                acceleration: true,
                                pages: __TOTAL_PAGES,
                                elevation: 50,
                                gradients: !$.isTouch,
                                turnCorners:'tl',
                            })
    
                            $("#book").turn("pages", __TOTAL_PAGES);
                            var list = [];
                            for (var i = 1; i <= __TOTAL_PAGES; i++) 
                            {
                                list.push(i);
                            }
                            for (page = 0; page<list.length; page++)
                            addPage(list[page], $("#book"),pdf_doc);
    
    
                        })                                      
                    });
    
                $("#book").bind("start", function(event, pageObject, corner) 
                {
    
                })    
            </script>        
        </body>
    </html>