html2canvas+jsPDF将页面DOM输出为PDF

jsPDF 是一个使用 Javascript 语言生成 PDF 的开源库。你可以在 Firefox 插件,服务端脚本或是浏览器脚本中使用它。

客户端 Safari 和 iPhone Safari 支持得最好,其次是 Opera 和 Windows 下的 Firefox 3 等。IE 暂不支持。

示例代码:

var doc = new jsPDF();
doc.text(20, 20, 'Hello world.');
doc.save('Test.pdf');

服务器端可以完美运行。

html2canvas 的作用就是允许让我们直接在用户浏览器上拍摄网页或其部分的“截图”。

它的屏幕截图是基于 DOM 的,因此可能不会 100% 精确到真实的表示,因为它不会生成实际的屏幕截图,而是基于页面上可用的信息构建屏幕截图。

import html2canvas from "html2canvas";

// 生成快照
const convertToImage = (container, options = {}) => {
  // 设置放大倍数
  const scale = window.devicePixelRatio;

  // 传入节点原始宽高
  const _width = container.offsetWidth;
  const _height = container.offsetHeight;

  let { width, height } = options;
  width = width || _width;
  height = height || _height;

  // html2canvas配置项
  const ops = {
    scale,
    // width,
    // height,
    useCORS: true,
    allowTaint: false,
    ...options
  };
  
  return html2canvas(container, ops).then(canvas => {
    // 返回图片的二进制数据
    return canvas.toDataURL("image/png");
  });
}

// 调用函数,取到截图的二进制数据,对图片进行处理(保存本地、展示等)
const imgBlobData = await convertToImage(element);

二者结合,最近看公司项目,看了下前辈的操作,具体如下:

  element.appendChild(div1);
  html2canvas(element, {
  allowTaint: true,
  scale: 2, // 提升画面质量,但是会增加文件大小
  useCORS: true
  }).then(function (canvas) {
  const contentWidth = canvas.width;
  const contentHeight = canvas.height;
  const pageData = canvas.toDataURL('image/jpeg', 1);
  const pdfWidth = (contentWidth + 10) / 2 * 0.75;
  const pdfHeight = (contentHeight + 200) / 2 * 0.75<900?900:(contentHeight + 200) / 2 * 0.75;
  const imgWidth = pdfWidth;
  const imgHeight = (contentHeight / 2 * 0.75); //内容图片这里不需要留白的距离
  const pdf = new jsPDF('', 'pt', [pdfWidth, pdfHeight]);
  pdf.addImage(pageData, 'jpeg', 0, 0, imgWidth, imgHeight);
  pdf.save('visit_report_' + new Date().getTime() + '.pdf');

你可能感兴趣的:(react,react,奇怪的库,firefox,safari,javascript)