canvas绘制dom计算分页自定义打印
2.1k9WEBcanvas2021-03-15

原生打印香吗?当然香啊,window.print() 页头页尾页码统统有,还能用 @media print 设置打印样式,没什么问题,棒棒的舒舒服服的;但是(没有但是也没这篇文章了🙃🙃🙃)分享分享一些我踩到的坑,以及我的解决方案

在打印页面加粗的字体的显示

现在字体大部分都用苹方,微软雅黑之类的,好看又百搭,但是偶尔也会有UI要求或者其他原因引起的特殊需求需要其他字体,就会惊喜的发现明明设置了 css,页面显示出来的也是font-weight: bold 的效果,但是在打印下却还是和 font-weight: normal 一样。

我用的是宋体,如果你和我一样 1.字体是动态 2.需要加粗 3.这个字体没有加粗的版本 4.还需要打印
可以试试我的替代方案:

1. 更换字体

在 @media print 为需要加粗的文字更换其他字体,缺点就是因为不是配套的字体可能会不协调,而且文字如果是动态的,那么加载一个字体包可能会影响用户体验

2. canvas 绘制 dom

虽然我后来也用了这个但是是因为另外的问题,所以如果仅仅因为字体加粗的话…嗯 …. 🤐🤐,看第三个👇👇👇

3. 使用多个字体重叠达到加粗效果

这是我当时用的办法,用 before + after + attr() 重叠达到加粗效果

    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
.strong {
font-weight: normal;
position: relative;
}
.strong::before {
content: attr(data-text);
z-index: -1;
line-height: 100%;
position: absolute;
display: inline-block;
left: -0.8px;
top: 0;
bottom: 0;
}
.strong::after {
content: attr(data-text);
z-index: -1;
line-height: 100%;
position: absolute;
display: inline-block;
left: 0;
top: -0.4px;
bottom: 0;
}

页头页脚自定义

原生打印含有页头页脚,可以自定义 margin, size,但无法自定义页头页脚内容,页头页脚含有日期,url,页码,网站 title,但我…只需要页码
在 f12 查看打印样式:ctrl + shift + p 展开命令菜单输入 show rendering,在 emulate css media type 选择 print

1. 在 @page 里设置 margin

不要页头 margin-top:0;不要页脚 margin-bottom:0, 如果不要页脚 url 是没了同样的页码也没了;什么都不需要 margin: 0,也可以在打印高级设置里隐藏页头页脚;

不管是margin-top:0,margin: 0,页头页脚是没了且页面的边距也没了,可以用元素 padding 或 margin 撑开但是如果是多页在分页的地方有可能会出现没有边距的情况

2. 修改 url

使用 history API 修改 url, MDN History.pushState()

1
2
3
history.pushState({}, "", "/");
window.print()
history.back()

最后只剩下网站域名,但对我来说好像不是很行

3. 尝试使用 counter-increment、counter() 加上页码

全部隐藏后尝试使用 counter-increment 和 CSS计数器 counter() 加上页码, MDN counter-increment MDN CSS counter

body 里重置 page,固定 #pageNum 在页面重复渲染,counter-increment 增加 page 值,couter() 显示 page

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
body {
counter-reset: page
}
#pageNum {
position: fixed;
top: 0;
left: 0;
}
@media print {
@page {
size: auto;
margin: 0;
}
#pageNum::after {
counter-increment: page;
content: "Page "counter(page);
}
}

在 Google 不生效始终显示 0,Firefox 只在第一页显示总页面数….. 😶😶😶😶

4. 最终方案:使用 canvas 绘制 dom 计算分页最后生成图片打印,解决所有原生问题

如果你不太了解 canvas,底部👇👇👇可以查看以往相关文章

1.dom 变 svg, 再变 image src

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var scale = 3
var el = document.querySelector("content"), svg, img = new Image(),
cav = document.createElement("canvas"), ctx, imagedata,
pages = 0, margintop = 100 * scale, marginleft = 0 * scale, height = 1122 * scale, pageheight;
pageheight = height - margintop * 2
ctx = cav.getContext("2d")
img.setAttribute('crossOrigin', '')
img.className = "printpage"
svg = `data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="${el.clientWidth}" height="${el.clientHeight}">
<foreignObject x="0" y="0" width="100%" height="100%">
<style>${style}</style>
${new XMLSerializer().serializeToString(el)}
</foreignObject>
</svg>`;
img.src = svg.replace(/\n/g, '').replace(/\t/g, '').replace(/#/g, '%23')
  1. canvas 是根据像素绘制,所以 canvas 绘制的时候使用同样的和 dom 一样的尺寸正常在电脑看没问题但是打印就会变得模糊,而 svg 是矢量图,所以应该放大 image 再绘制 canvas,但是同样的如果绘制尺寸太大会非常影响性能所以根据情况调整,我是设置放大三倍左右;
1
2
3
4
5
6
cav.height = img.height * scale
cav.width = img.width * scale
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, cav.width, cav.height)
ctx.drawImage(img, 0, 0, img.width * scale, img.height * scale)
img.src = cav.toDataURL()
  1. 按照打印页面高度计算总页数,这个总页数不一定是最后的总页数,扣除上边距后开始绘制图片,图片绘制完成后再绘制页脚,页脚的位置也应该是计算总长度后取中间位置
  2. 循环页数绘制图片,由于是图片所以分页的地方需要尤其注意,避免在文字中间被分开;循环 imagedata 扫描像素点,对比背景
  3. 如果一行文字因为分页从中间被截掉那么被截的上半部分应该要留到下一页再绘制,同时要记下这上部分的高度
    ps: 因为我的页面是纯文字白色背景,所以如果你的页面有图片或者其他色块,那么可能需要注意如果是被截的是图片或者其他的和文字颜色相同的色块,通常可能是不需要去避免这个截断,那么或许可以在 dom 的时候做一些准备比如记下位置什么的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
pages = Math.ceil(img.height / pageh)
cav.height = pages * height
cav.width = img.width
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, cav.width, cav.height)
var point = 0, tw = 0
for (var p = 0; p < pages; p++) {
ctx.drawImage(
img,
0, point, img.width, pageh,
marginl, margint + p * height, img.width, pageh
)
var iscut = true, rows = 0
while (iscut && rows < 120) {
imagedata = ctx.getImageData(marginl, (p + 1) * height - margint - (rows + 1), img.width, 1)
iscut = false
for (var i = 0; i < imagedata.data.length; i += 2 * 4) {
if (imagedata.data[i] === 0) {
rows++
iscut = true
rows === 120 && console.log("陷入循环" + p)
break
}
}
}
point += (pageh - rows)
ctx.fillRect(marginl, (p + 1) * height - margint - rows, img.width, rows)
}
  1. 由于我们的高度已经算好了,那么现在由于被截掉的文字的原因,剩余的需要绘制的高度也发生了变化,所以在画完当前总页数的最后一页后如果还有图片还未绘制完成应该加一,再绘制一页,canvas 尺寸也要进行同步更新
1
2
3
4
5
6
7
8
if (pages === p + 1 && point < img.height) {
pages += 1
var oldcav = ctx.getImageData(0, 0, cav.width, cav.height)
cav.height = pages * height
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, cav.width, cav.height)
ctx.putImageData(oldcav, 0, 0)
}
  1. ok,现在图片绘制完成,页数也算完了,就可以绘制页码了
1
2
3
4
5
6
7
ctx.fillStyle = '#000'
ctx.font = "normal normal " + scale * 14 + "px SimSun, Avenir, Helvetica Neue, Helvetica, Arial, sans-serif"
for (var p = 0; p < pages; p++) {
tw = ctx.measureText("第" + (p + 1) + "页 共" + pages + "页")
ctx.fillText("第" + (p + 1) + "页 共" + pages + "页", (cav.width - tw.width) / 2, (p + 1) * height - (margint / 2))
}
img.src = cav.toDataURL()
  1. 页码绘制完成后将 image 调成原始尺寸进行打印,放入body进行打印
1
2
3
4
5
img.width = img.width / scale
document.querySelector(".printpage") && document.querySelector(".printpage").remove()
document.querySelector("body").insertBefore(img, el)
window.print()

  1. css 样式部分可以做一些简单隐藏显示处理,在打印时隐藏正常页面内容,显示绘制完成的image
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.content {
display: block;
}
.printpage {
display: none;
}
@media print {
@page {
size: auto;
margin: 0;
}
.printpage {
display: block;
}
.content {
display: none;
}
}

其他

实际上我之前还有一个问题是 input 或 textarea 在打印下不显示输入的内容,因为,后来手动赋值解决,但是在写博客我发现我没办法复现那个问题了,尝试了 js 赋值、插入 dom、手动输入各种操作并没有出现我预期的 bug,everything is fine….,所以🤐🤐🤐

相关文章

canvas 相关
canvas 的 imagedata 对象

参考文章

MDN: Displaying a counter

How to hide an element when printing a web page using CSS?

stackoverflow: How to change the URL from the printing page?