xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

How to print a web page without breaking the table content in JavaScript All In One

How to print a web page without breaking the table content in JavaScript All In One

使用 JavaScript 如何在不破坏表格内容的情况下打印一个网页

error

the table content is divided into two parts ❌

image

原理分析

  1. 导出全屏截图
  2. 把截图转换成 PDF 文件

solutions

html2canvas
puppeteer

print.css

Chrome API

Screen Capture API

async function startCapture(displayMediaOptions) {
  let captureStream = null;

  try {
    captureStream =
      await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
  } catch (err) {
    console.error(`Error: ${err}`);
  }
  return captureStream;
}

function startCapture(displayMediaOptions) {
  return navigator.mediaDevices
    .getDisplayMedia(displayMediaOptions)
    .catch((err) => {
      console.error(err);
      return null;
    });
}

https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API/Using_Screen_Capture

getDisplayMedia

getDisplayMedia()
getDisplayMedia(options)

https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia

https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API

https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API

demos

const capture = async () => {
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");
  const video = document.createElement("video");

  try {
    const captureStream = await navigator.mediaDevices.getDisplayMedia();
    video.srcObject = captureStream;
    context.drawImage(video, 0, 0, window.width, window.height);
    const frame = canvas.toDataURL("image/png");
    captureStream.getTracks().forEach(track => track.stop());
    window.location.href = frame;
  } catch (err) {
    console.error("Error: " + err);
  }
};

capture();

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://stackoverflow.com/questions/77071886/how-to-remove-table-breaking-from-puppeteer-pdf

https://stackoverflow.com/questions/4912092/using-html5-canvas-javascript-to-take-in-browser-screenshots

https://hackernoon.com/how-to-take-screenshots-in-the-browser-using-javascript-l92k3xq7



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-09-09 22:40  xgqfrms  阅读(9)  评论(3编辑  收藏  举报