使用 PDF.js 渲染到屏幕外 canvas

Using PDF.js to render to an offscreen canvas

目标是将 pdf 页面呈现为偏移 canvas,以便我可以将页面的部分内容复制到可见 canvas。作为第一步,下面的代码旨在呈现 pdf 的整个第一页。它渲染到屏幕外 canvas,然后从屏幕外复制到可见 canvas。或者那是我的意图。什么都没有出现。

<!doctype html>

<html lang="en">
<head>
  <!--The pdf.js stuff, from Mozilla.-->
  <script src="pdf.js"></script>
  <script src="pdf.worker.min.js"></script>
  <style>
    canvas { border: 1px solid black; }
  </style>
</head>

<body onload="main()">

<canvas id="pdf_renderer"></canvas>

<script>

var myState = {
  pdf: null,
  zoom: 1,
  testcvs: null
}

async function main() {

  await openDocument();
  await getpage(1);
  
  var canvas = document.getElementById("pdf_renderer");
  var ctx = canvas.getContext('2d');
  
  canvas.width = myState.testcvs.width;
  canvas.height = myState.testcvs.height;
  
  ctx.drawImage(myState.testcvs,0,0);
}

async function openDocument() {
  await pdfjsLib.getDocument('ex01gear.pdf').then((pdf) => {
    myState.pdf = pdf;
  });
}

async function getpage(pagenum) {

  await myState.pdf.getPage(pagenum).then((page) => {
    
    var offcanvas = document.createElement('canvas');
    var offctx = offcanvas.getContext('2d');
    var viewport = page.getViewport(myState.zoom);
    
    offcanvas.width = viewport.width;
    offcanvas.height = viewport.height;

    page.render({
      canvasContext: offctx,
      viewport: viewport
    });

    myState.testcvs = offcanvas;
  }); 
}

</script>

</body>
</html>

下面的代码完成了预期的工作。我仍然不确定为什么原始代码无法工作。我最好的猜测是,这是由于正在做的事情 asynchronously.There 除此以外,这两个实现几乎没有什么不同。

<!doctype html>

<html lang="en">
<head>
  <!--The pdf.js stuff, from Mozilla.-->
  <script src="pdf.js"></script>
  <script src="pdf.worker.min.js"></script>
  <style>
    canvas { border: 1px solid black; }
  </style>
</head>


<body onload="main()">

<canvas id="pdf_renderer"></canvas>

<script>

var myState = {
  pdf: null,
  zoom: 1,
  testcvs: null,
  curpage: null
}

async function main() {

  await openDocument();
  await getpage(1);
  await renderOff();

  var canvas = document.getElementById("pdf_renderer");
  var ctx = canvas.getContext('2d');
  
  var viewport = myState.curpage.getViewport(myState.zoom);

  canvas.width = viewport.width;
  canvas.height = viewport.height;

  ctx.drawImage(myState.testcvs, 0, 0);
}

async function openDocument() {
  await pdfjsLib.getDocument('ex01gear.pdf').then((pdf) => {
    myState.pdf = pdf;
  });
}

async function getpage(pagenum) {
  await myState.pdf.getPage(pagenum).then((page) => {
    myState.curpage = page;
  }); 
}

async function renderOff() {

  myState.testcvs = document.createElement('canvas');
  var offctx = myState.testcvs.getContext('2d');
  var viewport = myState.curpage.getViewport(myState.zoom);

  myState.testcvs.width = viewport.width;
  myState.testcvs.height = viewport.height;
  
  await myState.curpage.render({
    canvasContext: offctx,
    viewport: viewport
  });
}

</script>

</body>
</html>