pdf_plugins.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. (function(window){
  2. var canvasPdf = {};
  3. //创建canvas元素
  4. function createPdfContainer(id, className,el) {
  5. var pdfContainer = document.getElementById('canvas');
  6. var canvasNew = document.createElement('canvas');
  7. canvasNew.id = id;
  8. canvasNew.className = className;
  9. pdfContainer.appendChild(canvasNew);
  10. };
  11. //建议给定pdf宽度
  12. function renderPDF(pdf, i, id,canvasWidth,canvasHeight) {
  13. pdf.getPage(i).then(function (page) {
  14. var scale =0.5; //scale的值是canvas的渲染尺寸,影响清晰度
  15. var viewport = page.getViewport({
  16. scale: scale
  17. });
  18. // 准备用于渲染的 canvas 元素
  19. var canvas = document.getElementById(id);
  20. var context = canvas.getContext('2d');
  21. canvas.width = canvasWidth;
  22. canvas.height = canvasHeight;
  23. // 将 PDF 页面渲染到 canvas 上下文中
  24. var renderContext = {
  25. canvasContext: context,
  26. viewport: viewport
  27. };
  28. page.render(renderContext);
  29. });
  30. };
  31. //创建和pdf页数等同的canvas数
  32. function createSeriesCanvas(num, template) {
  33. var id = '';
  34. for (var j = 1; j <= num; j++) {
  35. id = template + j;
  36. createPdfContainer(id, 'pdfClass');
  37. }
  38. }
  39. console.log("******")
  40. //读取pdf文件,并加载到页面中
  41. canvasPdf.loadPDF = function LoadPDF(fileURL,canvasWidth,canvasHeight) {
  42. pdfjsLib.getDocument(fileURL).promise.then(function (pdf) {
  43. console.log(pdf)
  44. //用 promise 获取页面
  45. var id = '';
  46. var idTemplate = 'cw-pdf-';
  47. var pageNum = pdf.numPages; //pdf文件总页数
  48. //根据页码创建画布
  49. createSeriesCanvas(1, idTemplate);//pageNum
  50. // $("#pdf-canvas canvas").css("width", "100%"); //canvas展示宽度
  51. //将pdf渲染到画布上去
  52. for (var i = 1; i <= 1; i++) {
  53. id = idTemplate + i;
  54. renderPDF(pdf, i, id,canvasWidth,canvasHeight);
  55. }
  56. });
  57. }
  58. window.$canvasPdf = canvasPdf;
  59. })(window);