Vue前端如何从Appwrite Storage获取PDF并编辑下载
实现Vue前端从Appwrite获取PDF并编辑下载
步骤1:安装PDF编辑依赖
前端处理PDF编辑需要第三方库支持,推荐使用pdf-lib,先完成安装:
npm install pdf-lib
步骤2:完整实现代码(获取-编辑-下载流程)
替换你现有代码,用以下逻辑实现完整流程:
import { storage } from './appwrite-config' // 导入你的Appwrite配置文件 import { PDFDocument, StandardFonts, rgb } from 'pdf-lib' async function processPDF() { try { // 1. 从Appwrite获取PDF响应并转成Blob const response = await storage.getFileView("[BUCKET ID]", "[FILE ID]") const pdfBlob = await response.blob() // 2. 加载PDF并添加自定义文本 const pdfBytes = await pdfBlob.arrayBuffer() const pdfDoc = await PDFDocument.load(pdfBytes) // 嵌入基础字体(也可自定义嵌入其他字体) const baseFont = await pdfDoc.embedFont(StandardFonts.Helvetica) // 获取PDF第一页(如需编辑多页,循环pages数组即可) const firstPage = pdfDoc.getPages()[0] const { width, height } = firstPage.getSize() // 在指定位置添加文本,Y坐标从页面底部开始计算 firstPage.drawText('新增文本行1', { x: 40, y: height - 60, size: 14, font: baseFont, color: rgb(0, 0, 0), }) firstPage.drawText('新增文本行2', { x: 40, y: height - 85, size: 14, font: baseFont, color: rgb(0.2, 0.4, 0.6), }) // 3. 导出编辑后的PDF并触发本地下载 const editedPdfBytes = await pdfDoc.save() const editedBlob = new Blob([editedPdfBytes], { type: 'application/pdf' }) const downloadUrl = URL.createObjectURL(editedBlob) // 创建临时a标签触发下载 const downloadLink = document.createElement('a') downloadLink.href = downloadUrl downloadLink.download = '编辑后的文档.pdf' // 自定义下载文件名 downloadLink.click() // 释放临时URL资源 URL.revokeObjectURL(downloadUrl) } catch (err) { console.error('PDF处理失败:', err) } } // 在Vue组件中调用(比如绑定到按钮点击事件) // <button @click="processPDF">下载编辑后的PDF</button>
关键细节说明
getFileView返回的是HTTP响应对象,必须通过.blob()转换后才能被pdf-lib解析- 文本坐标可按需调整:X为页面左侧偏移,Y为页面底部偏移(
height - N即距离顶部N像素) - 如需编辑多页内容,遍历
pdfDoc.getPages()数组即可
内容的提问来源于stack exchange,提问作者Harsh Jhunjhunwala
相关产品推荐
相关产品推荐

