import jsPDF from 'jspdf' import html2canvas from 'html2canvas' // PDF生成器类 export class PDFGenerator { // 生成制度PDF static async generateRegulationPDF(regulation: any): Promise { // 创建临时HTML元素 const tempDiv = document.createElement('div') tempDiv.style.position = 'absolute' tempDiv.style.left = '-9999px' tempDiv.style.top = '-9999px' tempDiv.style.width = '800px' tempDiv.style.padding = '40px' tempDiv.style.backgroundColor = 'white' tempDiv.style.fontFamily = 'Arial, sans-serif' tempDiv.style.fontSize = '14px' tempDiv.style.lineHeight = '1.6' tempDiv.style.color = '#333' // 添加水印样式 tempDiv.style.position = 'relative' tempDiv.style.overflow = 'hidden' // 生成HTML内容 tempDiv.innerHTML = `
制度管理系统

${regulation.title || '制度文档'}

制度类型:${regulation.regulationType || '-'} 发布人:${regulation.createBy || '-'}
发布时间:${regulation.publishTime || '-'} 生效日期:${regulation.effectiveTime || '-'}
适用范围:${regulation.scope || '-'} 制度级别:${regulation.level || '-'}
版本:${regulation.version || '1.0'}

制度内容:

${regulation.content || ''}
${regulation.remark ? `

备注:

${regulation.remark}
` : ''}
生成时间:${new Date().toLocaleString('zh-CN')} | 制度ID:${regulation.regulationId || '-'}
` // 添加到DOM document.body.appendChild(tempDiv) try { // 使用html2canvas转换为图片 const canvas = await html2canvas(tempDiv, { scale: 2, // 提高清晰度 useCORS: true, allowTaint: true, backgroundColor: '#ffffff', width: 800, height: tempDiv.scrollHeight }) // 创建PDF const imgData = canvas.toDataURL('image/png') const pdf = new jsPDF('p', 'mm', 'a4') const imgWidth = 210 // A4宽度 const pageHeight = 295 // A4高度 const imgHeight = (canvas.height * imgWidth) / canvas.width let heightLeft = imgHeight let position = 0 // 添加第一页 pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight) heightLeft -= pageHeight // 添加后续页面 while (heightLeft >= 0) { position = heightLeft - imgHeight pdf.addPage() pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight) heightLeft -= pageHeight } // 返回PDF blob return pdf.output('blob') } finally { // 清理临时元素 document.body.removeChild(tempDiv) } } // 下载PDF文件 static downloadPDF(blob: Blob, filename: string) { const url = URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = filename document.body.appendChild(link) link.click() document.body.removeChild(link) URL.revokeObjectURL(url) } }