纯 JS 图片转 PDF:基于 jsPDF 实现单图预览与下载
本文将详细演示如何利用 JavaScript 原生能力结合 jsPDF 开源库,在前端实现从图片上传、预览到生成 PDF 下载的完整流程。该方案无需后端支持,直接在浏览器中完成格式转换。
准备工作
要实现此功能,需准备以下基础环境:
- jsPDF 库:引入
jspdf.js(建议下载最新版或 CDN 链接)。 - HTML 结构:用于构建页面布局、上传图片及展示按钮。
- CSS 样式:美化容器、图片预览区域和操作按钮。
- JavaScript 逻辑:处理文件读取、图片显示及调用 PDF 生成函数。
第1步:搭建页面基本结构
首先定义页面的整体布局,包含一个居中显示的白色容器,背景采用渐变设计。
<style>
*, *:after, *:before { box-sizing: border-box; }
body {
font-family: arial;
margin: 0;
background: linear-gradient(133deg, #4abeb2, #3c57d2);
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.container {
background: white;
width: 450px;
padding: 30px;
border-radius: 5px;
}
</style>
<div class="container">
<!-- 后续内容放于此 -->
</div>
第2步:创建图片预览框
为了让用户知道选择了什么图片,需要在容器中增加一个 <img> 元素作为预览区,设置最小高度以占位,并在默认状态下隐藏或显示占位图。
<img id="showImg" src="default-placeholder.png" alt="预览区" style="display:block; margin:0 auto; max-width:400px; min-height:200px; background:#174353; border-radius:5px;"
第3步:编写操作按钮
核心交互区包含两个部分:一是通过隐藏的 <input type="file"> 配合自定义样式的 <div> 来上传 PNG、JPG 或 JPEG 图片;二是直接调用的“下载PDF”按钮。
<div class="button">
<div class="upload" onclick="document.getElementById('fileInput').click()">
<input type="file" id="fileInput" accept=".png, .jpg, .jpeg" onchange="loadFile(event)" style="opacity:0; position:absolute; z-index:-1;"
上传图片
</div>
<button onclick="pdfDown()">下载PDF</button>
</div>
<style>
.button { display: flex; justify-content: space-between; }
.upload, button {
padding: 10px; color: white; cursor: pointer;
font-size: 16px; border-radius: 5px; text-align: center;
}
.upload { background-color: #a74901; }
button { background-color: #023780; }
</style>
第4步:实现转换逻辑 (JavaScript)
这是核心步骤。我们需要监听文件选择事件,将本地图片转换为 DataURL 或 ObjectURL,然后通过 jsPDF 库将其放入 PDF 文档中。
// 定义全局变量存储图片信息
let selectedImage = null;
function loadFile(event) {
const file = event.target.files[0];
if (!file) return;
// 1. 更新页面上的预览图
const previewImg = document.getElementById('showImg');
previewImg.src = URL.createObjectURL(file);
// 2. 保存图片引用供后续使用
// 注意:实际项目中建议转为 ArrayBuffer 或 Base64 以兼容不同 jsPDF 版本需求
// 这里使用简单的 Image 对象配合 jsPDF 的标准用法
const img = new Image();
img.onload = function () {
selectedImage = img;
};
img.src = URL.createObjectURL(file);
}
function pdfDown() {
if (!selectedImage || !selectedImage.complete) {
alert("请先上传一张图片!");
return;
}
// 初始化 jsPDF (方向, 单位, A4纸张)
const doc = new jsPDF('l', 'mm', 'a4');
// 获取图片尺寸
const imgWidth = selectedImage.width;
const imgHeight = selectedImage.height;
// 将图片添加至 PDF (x, y, w, h, name/uri, orientation)
// 使用 addImage(imgObj, format, x, y, w, h) 是较新版本的推荐写法
// 若旧版本报错,可尝试 doc.addImage(selectedImage.src, 'JPEG', ...)
try {
// 根据原图宽高比例调整在PDF中的位置
const pageWidth = doc.internal.pageSize.getWidth();
const pageHeight = doc.internal.pageSize.getHeight();
// 简单缩放以适应页面宽度
let pdfWidth = pageWidth - 20;
let pdfHeight = (imgHeight * pdfWidth) / imgWidth;
// 如果高度超出页面则限制高度并重新计算宽度
if (pdfHeight > pageHeight - 20) {
pdfHeight = pageHeight - 20;
pdfWidth = (imgWidth * pdfHeight) / imgHeight;
}
// 居中打印
const x = (pageWidth - pdfWidth) / 2;
const y = (pageHeight - pdfHeight) / 2;
doc.addImage(selectedImage, 'JPEG', x, y, pdfWidth, pdfHeight);
doc.save('converted-image.pdf');
} catch (e) {
console.error(e);
alert('生成PDF失败,请检查图片或控制台错误');
}
}
常见问题排查
- 跨域问题 (CORS):如果在本地运行出现安全限制,建议使用本地 HTTP 服务器(如 VS Code Live Server)打开项目,而非直接双击
.html文件,部分现代浏览器对file://协议下的 Blob URL 处理有严格限制。 - 图片格式识别:确保保存时填写正确的文件格式标识(如
'JPEG','PNG'),否则导出的 PDF 可能无法正常显示。
以上就是基于JavaScript编写一个图片转PDF转换器的详细内容,更多关于JavaScript图片转PDF的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









