Я рендеринг PDF-страницы на холсте. Затем я хочу сохранить URL-адрес, созданный из большого двоичного объекта, в массив, чтобы получить доступ к нему вне этого метода. Я могу сохранить его в массив. Но когда я утешаю массив console.log, он показывает {key:Array(0)}
вместо {key:Array(2)}
. 0 должно быть 2 в моем случае, потому что я добавил два значения. Я могу видеть значения массива на консоли. Но не удалось получить доступ к значениям по индексу за пределами этого метода.
Вне метода:
Внутри метода (я показываю второй вывод из l oop, поэтому он показывает все значения внутри):
Во втором выводе он показывает Array(2)
, которые являются числами значений внутри.
Мне не удалось получить доступ к значению с индексом (a['key'][0]
). Это показывает неопределенное. Когда я пытаюсь внутри функции, он показывает желаемый результат.
<?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>
Заранее спасибо.