如何自动将bindery.js生成的PDF通过浏览器打印对话框发送至服务器
可行实现方案
方案1:基于Bindery渲染结果,用html2canvas+jsPDF生成可上传PDF
Bindery完成排版后,页面会生成分页的DOM容器(默认是.bindery-pages下的.page元素)。直接利用浏览器已渲染好的SVG视觉内容,用html2canvas捕获每页为Canvas,再通过jsPDF拼合成PDF Blob,最后通过HTTP发送到服务器,完美避开其他库解析SVG的兼容性问题。
示例代码:
// 等待Bindery完成排版 Bindery.makeBook({ content: '.content', // 你的Bindery配置项 }).then(() => { const pages = document.querySelectorAll('.bindery-pages .page'); const pdf = new jsPDF('p', 'mm', 'a4'); const pageWidth = pdf.internal.pageSize.getWidth(); const pageHeight = pdf.internal.pageSize.getHeight(); // 批量捕获所有页面为Canvas const capturePromises = Array.from(pages).map(page => html2canvas(page, { scale: 2, // 提升PDF清晰度 useCORS: true, // 若SVG含跨域资源需开启 logging: false }) ); Promise.all(capturePromises).then(canvases => { canvases.forEach((canvas, index) => { if (index > 0) pdf.addPage(); const imgData = canvas.toDataURL('image/png'); const imgHeight = (canvas.height * pageWidth) / canvas.width; pdf.addImage(imgData, 'PNG', 0, 0, pageWidth, imgHeight); }); // 生成Blob并上传 const pdfBlob = pdf.output('blob'); const formData = new FormData(); formData.append('pdfFile', pdfBlob, 'document.pdf'); fetch('/upload-pdf', { method: 'POST', body: formData }).then(res => { res.ok ? console.log('PDF上传成功') : console.error('上传失败'); }).catch(err => console.error('请求错误:', err)); }); });
方案2:用无头浏览器(Puppeteer/Electron)捕获原生打印PDF
如果你的场景支持服务器端或桌面应用部署,直接用无头浏览器触发window.print(),将输出导向PDF文件,再直接上传。这种方式完全复用浏览器原生PDF渲染能力,SVG显示效果和Bindery预览完全一致。
示例代码(Puppeteer环境):
const puppeteer = require('puppeteer'); const axios = require('axios'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('你的目标页面URL', { waitUntil: 'networkidle0' }); // 等待Bindery完成排版 await page.waitForSelector('.bindery-pages'); // 生成PDF Buffer const pdfBuffer = await page.pdf({ format: 'A4', printBackground: true, // 确保SVG背景、样式被完整渲染 }); // 发送到服务器 await axios.post('/upload-pdf', pdfBuffer, { headers: { 'Content-Type': 'application/pdf', 'Content-Disposition': 'attachment; filename="document.pdf"' } }); await browser.close(); })();
方案3:重写Bindery打印逻辑
Bindery本身仅调用window.print()触发浏览器打印,你可以在其排版完成后,跳过原生打印弹窗,直接执行方案1的PDF生成+上传逻辑,完全适配现有Bindery工作流。
注意事项
- 调整
html2canvas的scale参数可平衡PDF清晰度和文件大小; - 若SVG包含跨域外部资源,需提前将资源转为Base64嵌入或配置CORS;
- Puppeteer方案适合批量生成、自动化场景,无需前端用户操作。
内容的提问来源于stack exchange,提问作者AD1TYA
相关产品推荐
相关产品推荐

