/**
* @file PDF 处理相关 utils
*/
import { htmlToCanvas } from './dom'
/**
* 将指定 html 元素打印并下载为 pdf 文件.
* 内置了一些预处理逻辑:
* 1. 目标元素内带有 data-html-to-canvas-remove 属性的元素都会在打印前被移除
*
* @param el - 目标元素
* @param name - 下载的文件名, 应为 xx.pdf
* @param orientation - 指定打印方向, 默认逻辑为当元素宽 > 高时横向, 否则纵向
* @param padding - 页边距
* @param preprocess - 打印前的预处理, 一般用于对打印样式进行调整 (在 clone 的元素中进行, 不影响原元素)
*
* @returns Promise
*/
export function downloadHtmlAsPDF({
name,
orientation,
padding = {},
el,
preprocess,
}: {
el: HTMLElement
name: string
preprocess?: (el: HTMLElement) => HTMLElement
padding?: { top?: number; right?: number; bottom?: number; left?: number }
orientation?: 'portrait' | 'landscape'
}): Promise {
const { top = 0, right = 0, bottom = 0, left = 0 } = padding
const startPointX = left
const startPointY = top || 0
const addedWidth = right + left
const addedHeight = top + bottom
return new Promise(resolve => {
// scale 以增强清晰度
htmlToCanvas({ el, preprocess, scale: 3 }).then(canvas => {
const imgData = canvas.toDataURL('image/jpeg', 0.9)
import('jspdf').then(({ default: JSPDF }) => {
const doc = new JSPDF({
orientation:
orientation ?? canvas.width > canvas.height
? 'landscape'
: 'portrait',
unit: 'px',
format: [canvas.width + addedWidth, canvas.height + addedHeight],
})
doc.addImage(
imgData,
'JPEG',
startPointX,
startPointY,
canvas.width + startPointX,
canvas.height + startPointY,
)
doc.save(name)
resolve()
})
})
})
}