前端頁面直接生成PDF下載文件

前言

因為要實現業務需求如下圖,業務邏輯,該憑證為前端代碼實現,為了簡單方便實現下載為pdf的需求。
在這里插入圖片描述

一、怎么在前端直接生成PDF?

需求描述:瀏覽器打開的這個頁面,點擊下載,把當前彈框頁面的進行轉換為pdf

二、具體實現代碼如下:

代碼如下:

代碼如下(示例):

<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>可靠的彈框內容轉PDF</title><script src="https://cdn.tailwindcss.com"></script><link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet"><!-- 引入必要的PDF生成庫 --><script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script><script>tailwind.config = {theme: {extend: {colors: {primary: '#4F46E5',secondary: '#10B981',},}}}</script><style type="text/tailwindcss">@layer utilities {.modal-backdrop {@apply fixed inset-0 bg-black/50 flex items-center justify-center z-50 opacity-0 pointer-events-none transition-opacity duration-300;}.modal-backdrop.active {@apply opacity-100 pointer-events-auto;}.modal-content {@apply bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto transform scale-90 opacity-0 transition-all duration-300;}.modal-backdrop.active .modal-content {@apply scale-100 opacity-100;}.toast {@apply fixed bottom-4 right-4 px-4 py-3 rounded-lg shadow-lg z-50 transform translate-y-10 opacity-0 transition-all duration-300;}.toast.show {@apply translate-y-0 opacity-100;}}</style>
</head>
<body class="bg-gray-50 min-h-screen p-4 md:p-8"><div class="max-w-4xl mx-auto"><h1 class="text-2xl md:text-3xl font-bold text-gray-800 mb-8 text-center">員工信息管理系統</h1><button id="openModal" class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-all duration-300 mx-auto block"><i class="fa fa-user-circle mr-2"></i>查看員工信息</button></div><!-- 員工信息彈框 --><div id="employeeModal" class="modal-backdrop"><div class="modal-content"><div class="p-6 border-b border-gray-200"><h2 class="text-xl font-bold text-gray-800">員工詳細信息</h2></div><!-- 要導出為PDF的內容 --><div id="employeeInfo" class="p-6"><div class="flex flex-col md:flex-row gap-6 items-center mb-8"><div class="w-24 h-24 rounded-full bg-primary/10 flex items-center justify-center"><i class="fa fa-user text-4xl text-primary"></i></div><div><h3 class="text-2xl font-bold text-gray-800">張三</h3><p class="text-gray-600">軟件工程師</p></div></div><div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8"><div><h4 class="text-sm font-medium text-gray-500 mb-1">員工編號</h4><p class="text-gray-800">EMP2023001</p></div><div><h4 class="text-sm font-medium text-gray-500 mb-1">入職日期</h4><p class="text-gray-800">2023115</p></div><div><h4 class="text-sm font-medium text-gray-500 mb-1">聯系電話</h4><p class="text-gray-800">13800138000</p></div><div><h4 class="text-sm font-medium text-gray-500 mb-1">電子郵箱</h4><p class="text-gray-800">zhangsan@company.com</p></div></div><div class="mb-8"><h4 class="text-base font-semibold text-gray-800 mb-3">教育背景</h4><div class="pl-4 border-l-2 border-primary space-y-4"><div><p class="font-medium text-gray-800">計算機科學與技術 - 本科</p><p class="text-sm text-gray-600">北京大學 | 2016-2020</p></div><div><p class="font-medium text-gray-800">軟件工程 - 碩士</p><p class="text-sm text-gray-600">清華大學 | 2020-2022</p></div></div></div><div><h4 class="text-base font-semibold text-gray-800 mb-3">工作技能</h4><div class="flex flex-wrap gap-2"><span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">Java</span><span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">Spring Boot</span><span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">MySQL</span><span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">Redis</span><span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">微服務</span></div></div></div><div class="p-6 border-t border-gray-200 flex justify-end gap-4"><button id="closeModal" class="px-5 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">關閉</button><button id="exportPdf" class="px-5 py-2 bg-secondary text-white rounded-lg hover:bg-secondary/90 transition-colors"><i class="fa fa-download mr-2"></i>導出PDF</button></div></div></div><!-- 提示消息 --><div id="toast" class="toast"><span id="toastMessage"></span></div><script>// 等待DOM加載完成document.addEventListener('DOMContentLoaded', function() {// 獲取DOM元素const modal = document.getElementById('employeeModal');const openModalBtn = document.getElementById('openModal');const closeModalBtn = document.getElementById('closeModal');const exportPdfBtn = document.getElementById('exportPdf');const employeeInfo = document.getElementById('employeeInfo');const toast = document.getElementById('toast');const toastMessage = document.getElementById('toastMessage');// 顯示提示消息function showToast(message, isError = false) {toastMessage.textContent = message;toast.className = `toast show ${isError ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'}`;setTimeout(() => {toast.className = 'toast';}, 3000);}// 打開彈框openModalBtn.addEventListener('click', function() {modal.classList.add('active');document.body.style.overflow = 'hidden';});// 關閉彈框function closeModal() {modal.classList.remove('active');document.body.style.overflow = '';}closeModalBtn.addEventListener('click', closeModal);// 點擊彈框外部關閉modal.addEventListener('click', function(e) {if (e.target === modal) {closeModal();}});// 導出PDF功能exportPdfBtn.addEventListener('click', async function() {// 保存原始按鈕狀態const originalText = this.innerHTML;this.disabled = true;this.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>正在導出...';try {// 1. 創建一個臨時的內容容器,確保樣式正確const tempContainer = document.createElement('div');tempContainer.style.width = '210mm'; // A4寬度tempContainer.style.padding = '20mm';tempContainer.style.backgroundColor = 'white';tempContainer.style.position = 'absolute';tempContainer.style.top = '-9999px';tempContainer.style.left = 0;// 2. 克隆要導出的內容const contentClone = employeeInfo.cloneNode(true);// 3. 確保克隆內容的樣式正確應用contentClone.style.width = '100%';contentClone.style.maxWidth = 'none';// 4. 添加到臨時容器并插入文檔tempContainer.appendChild(contentClone);document.body.appendChild(tempContainer);// 5. 等待樣式應用await new Promise(resolve => setTimeout(resolve, 500));// 6. 使用html2canvas捕獲內容const canvas = await html2canvas(tempContainer, {scale: 2, // 高縮放確保清晰度useCORS: true,logging: false,backgroundColor: null});// 7. 創建PDFconst { jsPDF } = window.jspdf;const pdf = new jsPDF('p', 'mm', 'a4');const imgData = canvas.toDataURL('image/jpeg', 0.95);// 計算圖片尺寸以適應A4const imgWidth = 210; // A4寬度const imgHeight = canvas.height * imgWidth / canvas.width;// 添加圖片到PDFpdf.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight);// 8. 保存PDFpdf.save('員工信息_' + new Date().getTime() + '.pdf');showToast('PDF導出成功!');} catch (error) {console.error('PDF導出失敗:', error);showToast('導出失敗: ' + error.message, true);} finally {// 清理臨時元素const tempContainer = document.querySelector('div[style*="top: -9999px"]');if (tempContainer) {document.body.removeChild(tempContainer);}// 恢復按鈕狀態this.disabled = false;this.innerHTML = originalText;}});});</script>
</body>
</html>

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/918008.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/918008.shtml
英文地址,請注明出處:http://en.pswp.cn/news/918008.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

性能優化——GPU的影響

關閉MSAA 之前在查一個渲染問題&#xff0c;一開始是定位到了CPU在waitforFrame所以知道是GPU的問題但如何定義GPU的問題在哪里&#xff0c;就很麻煩。我一開始以為是drawcall的問題&#xff0c;因為我發現drawcall有350個但降低到30個后&#xff0c;依然情況沒有好轉。畢竟dra…

軟件需求關閉前的質量評估標準是什么

在 需求關閉前&#xff0c;進行 質量評估 是確保需求被完整實現、測試充分且滿足業務目標的關鍵步驟。以下是需求關閉前的質量評估標準&#xff0c;涵蓋了功能、非功能、測試覆蓋率和用戶滿意度等方面&#xff1a;一、功能實現的質量評估標準需求完整性&#xff1a;所有功能需求…

vscode中創建python虛擬環境的方法

文章目錄框架不同python解釋器vscode運行python需要的插件vscode可以改變執行python腳本的默認終端虛擬環境解釋創建虛擬環境的方法python的settings.json的一些好用配置框架 python解釋器->虛擬環境->vscode 不同python解釋器 在一臺電腦中我們可以安裝多個版本的pyt…

基于 ShardingSphere 的 Spring Boot 數據加密與模糊查詢實現

基于 ShardingSphere 的 Spring Boot 數據加密與模糊查詢實現 在數據安全與查詢便捷性并重的今天,敏感數據加密存儲后如何支持靈活查詢成為關鍵挑戰。本文將聚焦ShardingSphere 在實現數據加密的同時支持模糊查詢的核心能力,詳細介紹基于 Spring Boot 和 ShardingSphere 的完…

計算虛擬化技術

&#x1f9e0; 一、什么是計算虛擬化&#xff1f;&#xff08;基礎認識&#xff09; ? 基本概念&#xff1a; 計算虛擬化&#xff08;Compute Virtualization&#xff09; 是指&#xff1a;在一臺物理服務器上模擬多個“虛擬計算資源”&#xff0c;每個虛擬機看起來像是一臺獨…

Python編程基礎與實踐:Python基礎數據結構:列表、字典和集合

Python數據結構&#xff1a;掌握列表、字典和集合 學習目標 通過本課程的學習&#xff0c;學員將掌握Python中基本的數據結構&#xff1a;列表、字典和集合。學員將了解它們的特性、使用場景以及如何高效地使用它們來解決實際問題。 相關知識點 列表、字典和集合使用 學習…

三維偏序 -- cdq 套 cdq

似乎題解區并沒有 cdq 套 cdq 的作法&#xff0c;剛好今天講了&#xff0c;就來寫一發。 題意與記號 題目講的很清楚了。此方法并沒有樹狀數組好想也沒有其高效&#xff0c;但能很方便擴展。下文記原序列為 ddd&#xff0c;將每個點拆分成點與詢問&#xff0c;內部增加一個名為…

Effective C++ 條款27: 盡量用const、enum、inline替換 #define

Effective C 條款27&#xff1a;盡量用const、enum、inline替換#define核心思想&#xff1a;使用編譯器&#xff08;const, enum, inline&#xff09;替代預處理器&#xff08;#define&#xff09;&#xff0c;讓編譯器進行語義檢查&#xff0c;避免宏替換引發的錯誤和調試困難…

芯谷科技--高效噪聲降低解決方案壓縮擴展器D5015

在無繩電話系統中&#xff0c;噪聲降低是提升通話質量的關鍵。 D5015 壓縮擴展器&#xff0c;通過集成壓縮器和擴展器&#xff0c;有效降低了傳輸噪聲&#xff0c;同時保持了信號的完整性。D5015 采用 SOP20 和 DIP20 封裝形式&#xff0c;具有低電壓工作、低功耗、高集成度等特…

LabVIEW車床靜剛度自動測

?基于LabVIEW 平臺開發車床靜剛度自動測試系統&#xff0c;針對傳統生產法測量中人工誤差大、計算復雜、效率低等問題&#xff0c;結合誤差復映規律與剛度方程&#xff0c;通過高精度硬件與軟件協同&#xff0c;實現試件加工前后尺寸的在線采集、自動計算與報告生成&#xff0…

汽車流通行業4S門店生存性指標:零服吸收率

我們在做汽車4S集團的商業智能BI數據分析項目中&#xff0c;對于4S店的管理&#xff0c;大家經常會提到一個分析指標&#xff0c;叫“零服吸收率”&#xff0c;這個大概是什么意思呢&#xff1f;簡單來說就是4S門店一臺車都沒有賣出的情況下&#xff0c;光靠售后服務部分的收益…

第一性原理科學計算服務器如何選擇配置-CPU選擇篇

一、 大多數人知道的 (顯性因素)核心數與線程數 (Core Count & Thread Count): 重要性&#xff1a; 核心是王道。 科學計算任務&#xff08;如仿真、建模、數據分析、機器學習訓練&#xff09;絕大多數都高度并行化&#xff0c;可以同時利用多個核心進行計算。選擇建議&…

Java 后端 + JavaScript 前端 實現按鈕級別權限控制的解決方案

Java JavaScript 前后端協同實現按鈕權限控制 在后臺管理系統中&#xff0c;不同用戶根據角色和數據狀態應展示不同的操作按鈕&#xff0c;比如編輯、刪除、審批、提交等操作。本文將介紹一種通過 Java 后端生成按鈕權限 JSON&#xff0c;前端通過 jQuery 解析控制按鈕顯示的…

RAG面試內容整理-18. 向量量化與索引壓縮技術(PQ, HNSW 等)

當知識庫規模達到百萬甚至數億級文檔時,向量索引的存儲和查詢效率成為關鍵瓶頸。向量量化是一類用較低比特表示近似向量的方法,大幅壓縮內存占用并加速相似度計算。PQ(Product Quantization)是其中最著名的方法之一,被Faiss等庫廣泛實現。PQ的思想是將高維向量劃分為多個子…

如何顯示一個 Elasticsearch 索引的字段

作者&#xff1a;來自 Elastic JD Armada 學習如何使用 _mapping 和 _search API、子字段、合成 _source 和運行時字段來顯示 Elasticsearch 索引的字段。 更多閱讀&#xff1a; Elasticsearch&#xff1a;從搜索中獲取選定的字段 fields Elasticsearch&#xff1a;inverted …

vue3父組件把一個對象整體傳入子組件,還是把一個對象的多個屬性分成多個參數傳入

以一個對象整體傳入時&#xff0c;對象的定義&#xff1a;<template><div><p>姓名: {{ userInfo.name }}</p><p>年齡: {{ userInfo.age }}</p><p>郵箱: {{ userInfo.email }}</p></div> </template> <script s…

【unitrix數間混合計算】2.1 數間混合計算模塊(src/number/mod.rs)

一、源碼 這段代碼是一個Rust模塊的聲明和導出配置&#xff0c;主要用于實現"類型級數與基本類型混合計算"的功能。 //! 類型級數與基本類型混合計算// 模塊聲明 // -------------------------------- mod types; // 結構體定義 mod normalize; …

脫機部署k3s

離線部署 K3s 文檔 1. 準備工作 操作系統準備&#xff1a;確保服務器已安裝好基礎操作系統&#xff08;Ubuntu、CentOS 等&#xff09;。關閉防火墻或放通端口&#xff1a;建議關閉防火墻或確保 6443、10250 等端口已開放。準備離線資源文件&#xff1a; 下載地址 k3s-airga…

[失敗記錄] 使用HBuilderX創建的uniapp vue3項目添加tailwindcss3的完整過程

寫在前面 放棄了。。。 1&#xff09;方案1 - 參考下面的“完整步驟” - 安裝成功&#xff0c;運行成功&#xff0c;但是&#xff01;好多class不生效&#xff01; 2&#xff09;方案2 - 不安裝tailwindcss&#xff0c;直接使用獨立的編譯好的完整css文件&#xff01; …

使用Idea去git項目,發現拉取和推送都很慢的問題

在大多數情況下&#xff0c;用Idea去對項目進行拉取和推送是很方便的&#xff0c;對于新手來說也是非常友好的但是最近博主遇到了一個問題&#xff0c;就是我feat一個簡單的類&#xff0c;去提交推送都需要很長的時間&#xff0c;甚至是20分鐘&#xff0c;博主去找了很多方法。…