整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

前端页面如何原样快速导出PDF?附示例

何保持页面样式基本不变的前提下将HTML页面导出为PDF,下面提供一些示例代码,纯属个人原创,如对你有帮助请记得加关注、加收藏、点赞、转发、分享~谢谢~~

  • 基本思路:保持页面样式基本不变,使用 `html2canvas` 将页面转换为图片,然后再通过 `jspdf` 将图片分页导出为PDF文件(中间会遇到图片或文字等内容在分页处被切割开的问题,如何解决了?详见末尾干货)
  • 上基础代码:下面为项目中实际代码截取
<div>
    <!-- 要打印的内容区 -->
    <div ref="contentRef">
        <div class="print-item print-out-flow">这是脱离文档流的内容区域</div>
        <div class="print-item">这是一行内容,也是最小叶子元素内容</div>
    </div>
    <!-- 打印内容容器 -->
    <div ref="printContainerRef" class="print-container"></div>
</div>
/**
  * 1.使用一个隐藏div装载有滚动条的div.innerHTML
  * 2.隐藏div使用position: absolute, z-index: -999, left: -9999px, width: 900px 控制让用户无感知
  * 3.根据需要覆写隐藏div内html样式(例如textarea多行显示有问题, 可以新增一个隐藏的div
  *    包裹textarea的绑定值, 然后在打印样式中覆写样式, 隐藏textarea并显示对应div)
  */
handleExport() {
   // 下面是VUE组件内获取DOM元素代码,将内容放置到打印区(定义的隐藏DIV)中
    const contentRef = this.$refs.contentRef as HTMLElement;
    const printContainerRef = this.$refs.printContainerRef as HTMLElement;
    // 打印区的需额外处理绝对定位值, 调整使得第一个元素的.top值为0, 以便于页面计算
    printContainerRef.innerHTML = contentRef.innerHTML;	
    
    // 所有叶子div元素加上 print-item 样式名, 脱离文档流的额外添加 print-out-flow
    handlePrintItem(printContainerRef);  // 解决多页内容可能被切割问题
    
    html2canvas(printContainerRef, {allowTaint: false, useCORS: true}).then((canvas: any) => {
      const contentHeight = canvas.height;
      const contentWidth = canvas.width;
      // pdf每页显示的内容高度
      const pageHeight = contentWidth / 595.28 * 841.89;
      // 未生成pdf的页面高度
      let offsetHeight = contentHeight;
      // 页面偏移值
      let position = 0;
      // a4纸的尺寸[595.28, 841.89], canvas图片按a4纸大小缩放后的宽高
      const imgWidth = 595.28;
      const imgHeight = 595.28 / contentWidth * contentHeight;

      const dataURL = canvas.toDataURL('image/jpeg', 1.0);
      const doc = new jsPDF('p', 'pt', 'a4');

      if (offsetHeight < pageHeight) {
        doc.addImage(dataURL, 'JPEG', 0, 0, imgWidth, imgHeight);
      } else {
        while (offsetHeight > 0) {
          doc.addImage(dataURL, 'JPEG', 0, position, imgWidth, imgHeight);
          offsetHeight -= pageHeight;
          position -= 841.89;

          if (offsetHeight > 0) {
            doc.addPage();
          }
        }
      }

      doc.save(this.generateReportFileName());
      printContainerRef.innerHTML = '';
    });
}

上干货代码:上面分页导出PDF可能网上能看到类型代码,但绝对找不到下面的代码,纯手搓解决分页元素被切开问题(思路:获取自身定位,如自己刚好在被分页处,则加上一定的margin-top值将内容向下移)

/** 
 * 处理打印元素项, 修复分页后被切割的元素
 * @param printContainerRef 打印内容div容器
 * @param itemClassName 打印最小元素标识类名
 * @param outFlowClassName 脱离文档流的元素标识类名
 */
export function handlePrintItem(
  printContainerRef: HTMLElement,
  itemClassName: string = 'print-item',
  outFlowClassName: string = 'print-out-flow'
): void {
  const rootClientRect = printContainerRef.getBoundingClientRect();
  // 初始化页面相关数据
  const totalHeight = rootClientRect.height;  // 内容总高度
  const a4PageHeight = (printContainerRef.clientWidth / 595.28) * 841.89; // a4纸高度
  let pageNum = Math.ceil(totalHeight / a4PageHeight);  // 总页数
  let addPageHeight = 0;  // 修正被分割元素而增加的页面高度总和
  let currentPage = 1;  // 当前正在处理切割的页面
  const splitItemObj: { [key: number]: HTMLElement[] } = {};  // 内容中各页被切割元素存储对象

  const printItemNodes: NodeListOf<HTMLElement> = printContainerRef.querySelectorAll(`.${itemClassName}`);
  for (let item of printItemNodes) {
    // 如果当前页已经是最后一页, 则中断判断
    if (currentPage >= pageNum) {
      break;
    }

    // 获取元素绝对定位数据
    const clientRect = item.getBoundingClientRect();
    let top = clientRect.top;
    const selfHeight = clientRect.height;
    // 如果当前元素距离顶部高度大于当前页面页脚高度, 则开始判断下一页页脚被切割元素
    if (top > currentPage * a4PageHeight) {
      // 换页前修正上一页被切割元素
      addPageHeight += fixSplitItems(currentPage, a4PageHeight, splitItemObj[currentPage], outFlowClassName);
      pageNum = Math.ceil((totalHeight + addPageHeight) / a4PageHeight);
      top = item.getBoundingClientRect().top;
      currentPage++;
    }
    // 如果元素刚好处于两页之间, 则记录该元素
    if (top > (currentPage - 1) * a4PageHeight && top < currentPage * a4PageHeight && top + selfHeight > currentPage * a4PageHeight) {
      if (!splitItemObj[currentPage]) {
        splitItemObj[currentPage] = [];
      }
      splitItemObj[currentPage].unshift(item);
      // 如果当前元素是最后一个元素, 则直接处理切割元素, 否则交由处理下一页元素时再处理切割
      if (item === printItemNodes[printItemNodes.length - 1]) {
        fixSplitItems(currentPage, a4PageHeight, splitItemObj[currentPage], outFlowClassName);
      }
    }
  }
}

/**
  * 修复当前页所有被切割元素
  * @param currentPage 当前页
  * @param pageHeight 每页高度
  * @param splitElementItems 当前被切割元素数组
  * @param outFlowClassName 脱离文档流的样式类名
  */
function fixSplitItems(
  currentPage: number,
  pageHeight: number,
  splitElementItems: HTMLElement[],
  outFlowClassName: string
): number {
  if (!splitElementItems || !splitElementItems.length) {
    return 0;
  }

  const yMargin = 5;  // y方向距离页眉的距离
  const splitItemsMinTop = getSplitItemsMinTop(splitElementItems);
  if (!splitItemsMinTop) {
    return 0;
  }

  let fixHeight = currentPage * pageHeight - splitItemsMinTop + yMargin;
  const outFlowElement = splitElementItems.find((item) => item.classList.contains(outFlowClassName));
  if (outFlowElement && outFlowElement.parentElement) {
    const parentPreviousElement = outFlowElement.parentElement.previousElementSibling as HTMLElement;
    fixHeight += getMarinTopNum(parentPreviousElement, outFlowElement.parentElement);
    outFlowElement.parentElement.style.marginTop = `${fixHeight}px`;
    return fixHeight;
  }

  splitElementItems.forEach((splitElement) => {
    splitElement.style.marginTop = `${fixHeight}px`;
  });
  return fixHeight;
}

/**
  * 获取被切割元素数组中最小高度值(如一行有多个元素被切割,则选出距离顶部最小的高度值)
  * @param splitElementItems 当前被切割元素数组
  */
function getSplitItemsMinTop(
  splitElementItems: HTMLElement[]
): number | undefined {
  // 获取元素中最小top值作为基准进行修正
  let minTop: number | undefined;
  let minElement: HTMLElement | undefined;
  splitElementItems.forEach((splitElement) => {
    let top = splitElement.getBoundingClientRect().top;
    if (minTop) {
      minTop = top < minTop ? top : minTop;
      minElement = top < minTop ? splitElement : minElement;
    } else {
      minTop = top;
      minElement = splitElement;
    }
  });

  // 修正当前节点及其前面同层级节点的margin值
  if (minTop && minElement) {
    const previousElement = splitElementItems[splitElementItems.length - 1].previousElementSibling as HTMLElement;
    minTop -= getMarinTopNum(previousElement, minElement);
  }
  return minTop;
}

/**
  * 通过前一个兄弟元素和元素自身的位置确认一个距离顶部高度修正值
  * @param previousElement 前一个兄弟元素
  * @param curElement 当前元素
  */
function getMarinTopNum(previousElement: HTMLElement, curElement: HTMLElement): number {
  let preMarginNum = 0;
  let curMarginNum = 0;
  if (previousElement) {
    // 获取外联样式需要getComputedStyle(), 直接.style时对象的值都为空
    const previousMarginBottom = window.getComputedStyle(previousElement).marginBottom;
    preMarginNum = previousMarginBottom ? Number(previousMarginBottom.replace('px', '')) : 0;
  }
  const marginTop = window.getComputedStyle(curElement).marginTop;
  curMarginNum = marginTop ? Number(marginTop.replace('px', '')) : 0;
  return preMarginNum > curMarginNum ? preMarginNum : curMarginNum;
}

以上纯原创!欢迎加关注、加收藏、点赞、转发、分享(代码闲聊站)~

家好,我是IT共享者,人称皮皮。这篇文章我们来讲讲CSS的文本样式。

一、文本颜色Color

颜色属性被用来设置文字的颜色。

颜色是通过CSS最经常的指定:

  • 十六进制值 - 如"#FF0000"。
  • 一个RGB值 - "RGB(255,0,0)"。
  • 颜色的名称 - 如"红"。

一个网页的文本颜色是指在主体内的选择:

<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=640, user-scalable=no">
        <title>项目</title>
        <style>
            body {
                color: blue;
            }


            h1 {
                color: #00ff00;
            }


            h2 {
                color: rgb(255, 0, 0);
            }
</style>
    </head>


    <body>
        <h2>hello world</h2>
        <h1>welcome to CaoZhou</h1>
    </body>


</html>

注:对于W3C标准的CSS:如果你定义了颜色属性,你还必须定义背景色属性。


二、属性

1. text-align 文本的对齐方式

文本排列属性是用来设置文本的水平对齐方式。

文本可居中或对齐到左或右,两端对齐。

当text-align设置为"justify",每一行被展开为宽度相等,左,右外边距是对齐(如杂志和报纸)。

<!doctype html>
<html lang="en">


    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            h1 {
                text-align: center;
            }


            p.date {
                text-align: right;
            }


            p.main {
                text-align: justify;
            }
</style>
    </head>


    <body>


        <p class="date">2015 年 3 月 14 号</p>
        <p class="main"> 从前有个书生,和未婚妻约好在某年某月某日结婚。到那一天,未婚妻却嫁给了别人。书生受此打击, 一病不起。  这时,路过一游方僧人,从怀里摸出一面镜子叫书生看。书生看到茫茫大海,一名遇害的女子一丝不挂地躺在海滩上。路过一人, 看一眼,摇摇头,走了。又路过一人,将衣服脱下,给女尸盖上,走了。再路过一人,过去,挖个坑,小心翼翼把尸体掩埋了。  僧人解释道, 那具海滩上的女尸,就是你未婚妻的前世。你是第二个路过的人,曾给过他一件衣服。她今生和你相恋,只为还你一个情。但是她最终要报答一生一世的人,是最后那个把她掩埋的人,那人就是他现在的丈夫。书生大悟,病愈。


        </p>
        <p><b>注意:</b> 重置浏览器窗口大小查看 "justify" 是如何工作的。</p>
    </body>


</html>

2. text-decoration文本修饰

text-decoration 属性用来设置或删除文本的装饰。

从设计的角度看 text-decoration属性主要是用来删除链接的下划线:

<!doctype html>
<html lang="en">


    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            .none {}


            .del {
                text-decoration: none;
            }
</style>
    </head>


    <body>
        <p>原来的样子</p>
        <a href="#" class="none">wwwwwwwwwwwwwwwwww</a>
        <p>去掉下划线</p>
        <a href="#" class="del">wwwwwwwwwwwwwwwwwwwww</a>
    </body>


</html>

也可以这样装饰文字:

<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=640, user-scalable=no">
        <title>项目</title>
        <style>
            h1 {
                text-decoration: overline;
            }


            h2 {
                text-decoration: line-through;
            }


            h3 {
                text-decoration: underline;
            }
</style>
    </head>


    <body>
        <h1>This is heading 1</h1>
        <h2>This is heading 2</h2>
        <h3>This is heading 3</h3>
    </body>


</html>

注:不建议强调指出不是链接的文本,因为这常常混淆用户。


3. text-transform文本转换

text-transform文本转换属性是用来指定在一个文本中的大写和小写字母。

  • uppercase:转换为全部大写。
  • lowercase:转换为全部小写。
  • capitalize :每个单词的首字母大写。
<!DOCTYPE html>
<html>


    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=640, user-scalable=no">
        <title>项目</title>
        <style>
            p.uppercase {
                text-transform: uppercase;
            }


            p.lowercase {
                text-transform: lowercase;
            }


            p.capitalize {
                text-transform: capitalize;
            }
</style>
    </head>


    <body>
        <p class="uppercase">This is some text.</p>
        <p class="lowercase">This is some text.</p>
        <p class="capitalize">This is some text.</p>
    </body>


</html>

4. text-indent文本缩进

text-indent文本缩进属性是用来指定文本的第一行的缩进。

p {text-indent:50px;}

5. letter-spacing 设置字符间距

增加或减少字符之间的空间。

<style>
     h1 {
       letter-spacing:2px;
}
      h2 {
        letter-spacing:-3px;
}
</style>

6. line-height设置行高

指定在一个段落中行之间的空间。

<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=640, user-scalable=no">
        <title>项目</title>
        <style>
            p.small {
                line-height: 70%;
            }


            p.big {
                line-height: 200%;
            }
</style>
    </head>


    <body>
        <p>
            This is a paragraph with a standard line-height.<br> This is a paragraph with a standard line-height.<br> The default line height in most browsers is about 110% to 120%.<br>
        </p>


        <p class="small">
            This is a paragraph with a smaller line-height.<br> This is a paragraph with a smaller line-height.<br> This is a paragraph with a smaller line-height.<br> This is a paragraph with a smaller line-height.<br>
        </p>


        <p class="big">
            This is a paragraph with a bigger line-height.<br> This is a paragraph with a bigger line-height.<br> This is a paragraph with a bigger line-height.<br> This is a paragraph with a bigger line-height.<br>
        </p>


    </body>


</html>

7. word-spacing 设置字间距

增加一个段落中的单词之间的空白空间。

<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=640, user-scalable=no">
        <title>项目</title>
        <style type="text/css">
            p {
                word-spacing: 30px;
            }
</style>
    </head>


    <body>


        <p>
            This is some text. This is some text.
        </p>


    </body>


</html>

8. vertical-align 设置元垂直居中

设置文本的垂直对齐图像。

<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=640, user-scalable=no">
        <title>项目</title>
        <style>
            img{
                width: 200px;
                height: 100px;
            }
            img.top {
                vertical-align: text-top;


            }


            img.bottom {
                vertical-align: text-bottom;


            }
</style>
    </head>


    <body>
        <p>An <img src="img/logo.png"  /> image with a default alignment.</p>
        <p>An <img class="top" src="img/logo.png" /> image with a text-top alignment.</p>
        <p>An <img class="bottom" src="img/logo.png" /> image with a text-bottom alignment.</p>
    </body>


</html>

9. text-shadow 设置文本阴影

设置文本阴影。

<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=640, user-scalable=no">
        <title>项目</title>
        <style>
         h1{
            text-shadow: 2px 2px #FF0000;
     }
</style>
    </head>


    <body>
    <h1>Text-shadow effect</h1>
    </body>


</html>

三、总结

本文主要介绍了CSS文本样式实际应用中应该如何去操作,通过讲解文本中对应的属性去改变文本的表现形式。使用丰富的效果图的展示,能够更直观的看到运行的效果,能够更好的理解。使用Html语言,代码结构更佳的清晰,能够帮助你更好的学习。

、行级标签转换为块级标签

转换为块级标签,各自独占一行,且可以设置宽高

代码:<a href="">我是a标签</a>

<a href="">我是a标签</a>

<a href="">我是a标签</a>

CSS :display:block;

width: 100px;

height: 30px;

border: 1px solid black;

在浏览器中的样式:

二、块级标签转换为行级标签

转化为行级标签,共同占一行,不能设置宽高

代码:<h3>我是块级标签</h3>

<h3>我是块级标签</h3>

<h3>我是块级标签</h3>

CSS:display: inline;

width: 200px;

height: 100px;

border: 1px solid red;

在浏览器中的样式:

三、转化为行内块级标签

能共占一行,而且可以设置各自的宽高

1.行级元素转化为行内块级元素

代码:<a class="a1" href="">我是a标签</a>

<a class="a2" href="">我是a标签</a>

CSS: a{ display:inline-block; border: 1px solid black; }

.a1{width: 100px; height: 30px; }

.a2{ width: 50px; height: 50px; }

在浏览器中的样式:

2.块级标签转化为行内块级标签

代码:<h3 class="h3_1">我是块级标签</h3>

<h3 class="h3_2">我是块级标签</h3>

CSS:h3{display: inline-block;border: 1px solid red;}

.h3_1{width: 100px;height: 100px;}

.h3_2{width: 200px;height: 50px;}

在浏览器中的样式:

四、display的另一个属性,可以将元素隐藏

display:none;

如果想了解更多块级标签和行内标签的属性,请关注,参看上一篇文章,有写的不对或不全面的地方,请大家多多指出。