1. 程式人生 > >pdf.js 入門使用指南3-字型顯示問題

pdf.js 入門使用指南3-字型顯示問題

1:亂碼問題。最近遇到一個問題,一個pdf 檔案使用了冷門的字型,導致出現亂碼,字型空白,如下圖所示


2:問題排查,初步排查,治標。

   修改改pdf 檔案,把字型都修改成宋體。再次預覽,顯示正常 。

   

3:從問題上根治這個問題,治本

      總不能把每個pdf 都修改一下字型,這樣太麻煩。經過測試,找到治本的方法。

      下載  http://download.csdn.net/download/amu0521/10107388?web=web 

後,

         web目錄有一個資料夾名字叫cmap,拷貝出來,放到網站根目錄,如下圖 

          

     然後修改網頁程式碼,程式碼模組增加

     

PDFJS.cMapUrl = 'cmaps/';
PDFJS.cMapPacked = true;
然後執行後,問題解決
 
 
完成程式碼如下:

 
<html>
<head>
    <title
>pdf.js展示1,上一頁,下一頁</title> <meta charset="UTF-8"> </head> <h1>PDF.js Previous/Next example</h1> <div> <button id="prev">Previous</button> <button id="next">Next</button> &nbsp; &nbsp; <span>Page: <span id="page_num"
></span> / <span id="page_count"></span></span> </div> <canvas id="the-canvas"></canvas> <script src="js/pdf.js"></script> <script src="js/pdf.worker.js"></script> <script> var url = 'doc/demo2.pdf'; var pdfDoc = null, pageNum = 1, pageRendering = false, pageNumPending = null, scale = 1,//顯示比例,0到1之間 canvas = document.getElementById('the-canvas'), ctx = canvas.getContext('2d'); PDFJS.cMapUrl = 'cmaps/'; PDFJS.cMapPacked = true; /** * Get page info from document, resize canvas accordingly, and render page. * @param num Page number. */ function renderPage(num) { pageRendering = true; // Using promise to fetch the page pdfDoc.getPage(num).then(function(page) { var viewport = page.getViewport(scale); canvas.height = viewport.height; canvas.width = viewport.width; // Render PDF page into canvas context var renderContext = { canvasContext: ctx, viewport: viewport }; var renderTask = page.render(renderContext); // Wait for rendering to finish renderTask.promise.then(function() { pageRendering = false; if (pageNumPending !== null) { // New page rendering is pending renderPage(pageNumPending); pageNumPending = null; } }); }); // Update page counters document.getElementById('page_num').textContent = num; } /** * If another page rendering in progress, waits until the rendering is * finised. Otherwise, executes rendering immediately. */ function queueRenderPage(num) { if (pageRendering) { pageNumPending = num; } else { renderPage(num); } } /** * Displays previous page. */ function onPrevPage() { if (pageNum <= 1) { return; } pageNum--; queueRenderPage(pageNum); } document.getElementById('prev').addEventListener('click', onPrevPage); /** * Displays next page. */ function onNextPage() { if (pageNum >= pdfDoc.numPages) { return; } pageNum++; queueRenderPage(pageNum); } document.getElementById('next').addEventListener('click', onNextPage); /** * Asynchronously downloads PDF. */ PDFJS.getDocument(url).then(function(pdfDoc_) { pdfDoc = pdfDoc_; document.getElementById('page_count').textContent = pdfDoc.numPages; // Initial/first page rendering renderPage(pageNum); }); </script> </html>

最終的目錄佈局,如下圖