Javascript Pdfjs Canvas to Img

时间:2016-07-05 11:25:04

标签: javascript jquery canvas todataurl pdfjs

我将画布转换为img是一个问题。 使用toDataURL()并将其插入img src的最佳方法是什么? 当我启动脚本时,它给了我正确的画布,但img是空白的.. 这是我的代码:



<!DOCTYPE HTML>
<html>
<head>
<script type='text/javascript' src='//code.jquery.com/jquery-2.2.3.js'></script>
<script type="text/javascript" src="https://raw.github.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
</head>
<body>
<div id='anteprima' ></div>
<div id='anteprima_img' ></div>

<script type="text/javascript">
var file = 'http://www.businessmodelgeneration.com/downloads/businessmodelgeneration_preview.pdf';
pdftoimg(file, 1, 0.5, 'anteprima');

function pdftoimg(file, num, scale2, idd) {
    PDFJS.disableWorker = true;
    PDFJS.getDocument(file).then(function(pdf) {
        pdf.getPage(num).then(function(page) {
            var canvas = document.createElement('canvas');
            canvas.id = 'pag' + num;
            canvas.className = 'grande';
            canvasContainer = document.getElementById(idd);
            var context = canvas.getContext('2d');
            var viewport = page.getViewport(scale2);
            canvas.height = viewport.height;
            canvas.width = viewport.width;
            var renderContext = {
                canvasContext: context,
                viewport: viewport
            };
            page.render(renderContext);
            canvasContainer.appendChild(canvas);

            var dataUrl = canvas.toDataURL();
            image = document.createElement('img');
            image.src = dataUrl;
            $('#anteprima_img').html(image);


        });
    });
};

</script>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您的代码非常好,您需要等待渲染画布才能将其转换为数据URL。

You are looking for wrong object rather you should be doing e.files

$scope.handleFile = function(e) {

 console.log(e.files);
 var files = e.files;
 var i,f;
 for (i = 0, f = files[i]; i != files.length; ++i) {
    var reader = new FileReader();
    var name = f.name;
    reader.onload = function(e) {
        var data = e.target.result;

        var workbook = XLSX.read(data, {type: 'binary'});

        /* DO SOMETHING WITH workbook HERE */
    };
    reader.readAsBinaryString(f);
}

}