2017-06-14 110 views
1

我想使用PDF.js從PDF文件生成縮略圖,但它不像其他的js只有一個文件,並且都需要將js包含在您的項目是寫:使用PDF.js生成PDF的縮略圖

<script src="any.js"></script> 

如何在我的項目中使用PDF.js?我在後端使用PHP。

+0

你嘗試這個解決方案? https://stackoverflow.com/questions/467793/how-do-i-convert-a-pdf-document-to-a-preview-image-in-php –

回答

1

基於helloworld example

function makeThumb(page) { 
 
    // draw page to fit into 96x96 canvas 
 
    var vp = page.getViewport(1); 
 
    var canvas = document.createElement("canvas"); 
 
    canvas.width = canvas.height = 96; 
 
    var scale = Math.min(canvas.width/vp.width, canvas.height/vp.height); 
 
    return page.render({canvasContext: canvas.getContext("2d"), viewport: page.getViewport(scale)}).promise.then(function() { 
 
    return canvas; 
 
    }); 
 
} 
 

 
PDFJS.getDocument("//cdn.mozilla.net/pdfjs/tracemonkey.pdf").promise.then(function (doc) { 
 
    var pages = []; while (pages.length < doc.numPages) pages.push(pages.length + 1); 
 
    return Promise.all(pages.map(function (num) { 
 
    // create a div for each page and build a small canvas for it 
 
    var div = document.createElement("div"); 
 
    document.body.appendChild(div); 
 
    return doc.getPage(num).then(makeThumb) 
 
     .then(function (canvas) { 
 
     div.appendChild(canvas); 
 
    }); 
 
    })); 
 
}).catch(console.error);
<script src="//npmcdn.com/pdfjs-dist/build/pdf.js"></script>

+0

謝謝你,但我已嘗試與另一個URL( http://www.shellgreenier.com/MGreenier-Resume.pdf)並得到此問題:請求的資源上沒有「Access-Control-Allow-Origin」標題。因此不允許Origin'http:// localhost'訪問。 –

+0

cdn.mozilla.net已啓用CORS - 您不能要求隨機URL爲不同網站提供數據。在您的網站上下載PDF和代碼以播放劇本。另見https://github.com/mozilla/pdf.js/wiki/Frequently-Asked-Questions#faq-xhr – async5