从 canvas.toDataURL() 创建图像 bloburl

Create image bloburl from canvas.toDataURL()

我将 pdf 输出为 base64 字符串。我想用这种格式为每个页面创建 bloburl。因此,我使用这个 base64 字符串为整个 pdf 创建了 bloburl 。然后,我使用 pdfjs 并在新创建的 canvas 中显示第一页。现在,我尝试将显示的图片作为图像 blob。

  1. 创建 blob 时出现错误 (Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.) 执行代码 b64toBlob(pag1.toDataURL('image/png',1.0),'image/png').
  2. 然后我试了 b64toBlob(window.btoa(pag1.toDataURL('image/png',1.0)),'image/png') 它显示为该 blob 创建的 url 中的空图像。
  3. var b2 =pag1.toBlob(function(blob) {}, 'image/png') 输出未定义。

    <?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';
    $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>
      <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/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;
    }
    
    
    
    $( document ).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;
                var div_container = document.querySelector('#flipbook');
                pdf_doc.getPage(1).then(function(page) 
                {
                    var scale = 1;
                    var viewport = page.getViewport(scale);
    
                    // Prepare canvas using PDF page dimensions
                   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
                    };
                 page.render(renderContext).then(function()
                {
                    div_container.appendChild(pag1);
                    var dataUrl =pag1.toDataURL(); 
    
                //const b   =b64toBlob(dataUrl,'image/png');
                //const b   =b64toBlob(window.btoa(dataUrl),'image/png');
                //const burl =URL.createObjectURL(b); 
                //console.log(b);
    
                //var b2 =pag1.toBlob(function(blob) {}, 'image/png');
    
            var element                     = document.createElement("div");
            element.style.backgroundImage   = "url(" + dataUrl + ")";
            div_container.appendChild(element);
             $("#Pg_1").remove(); 
    
              });
                });
    
        })
    
    })
     </script>
    </head>
    
    <body>
     <!--<div id="magazine">
        <canvas id="pdf"></canvas>
     </div>-->
    
     <div class="flipbook-viewport">
      <div class="container">
          <div class="flipbook" id="flipbook">
              <!--<canvas id="pdf"></canvas>-->
          </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>
    

当我执行console.log(dataURL)时,它以data:image/png;base64开头。所以,我认为它是 base-64 编码的。但是,错误提示未正确解码。为什么会这样how to create imagebloburl from canvas displaying pdf page?

提前致谢。

这能够创建图像 bloburl。但是在函数外访问burl变量时显示undefined。

  pag1.toBlob(function(blob) 
    {
       var burl =URL.createObjectURL(blob); 

    }, 'image/png');

期待更好的解决方案。