本文分享使用 JavaScript 和 Tailwind CSS 打印发票的最佳实践,总结了多次尝试后的经验。
Tailwind CSS 配置 (可选)
若使用 Tailwind CSS 设计发票样式,建议配置如下,以便使用 print 和 screen 前缀来控制不同媒体下的显示内容:
/** @type {import('tailwindcss').config} */ export default { content: ['./src/**/*.{html,js,svelte,ts}'], theme: { extend: { screens: { print: { raw: 'print' }, screen: { raw: 'screen' } }, // ... } }, plugins: [] };
使用方法:
立即学习“前端免费学习笔记(深入)”;
<div class="screen:bg-red-300 print:bg-white"></div>
主 CSS 文件调整
添加以下 CSS 代码,可隐藏浏览器额外添加的页眉和页脚内容,并自定义屏幕样式:
/* 隐藏浏览器额外页眉页脚 */ @media print { @page { margin: 0.3in 0.7in 0.3in 0.7in !important; } } /* 自定义屏幕样式 */ @media screen { html, body { width: 100vw; height: 100vh; display: flex; overflow: auto; background-color: #982b44; } }
最佳实践:独立路由,避免弹窗
为获得最佳打印体验,建议使用独立路由而非弹窗,并设置文档标题:
<title>your-file-name</title>
或
document.title = "your-file-name";
处理项目循环,避免多余逗号
如果需要循环渲染项目,使用 join('') 方法连接字符串,避免多余逗号:
const tablerows = orders.map((item, index) => { // ... return ` <tr class="border-b border-gray-200 break-inside-avoid break-before-auto"><td class="max-w-0 py-2 pl-4 pr-3 text-sm sm:pl-0"> <div class="font-medium text-gray-900">${index + 1}.${item.name}</div> </td> <td class="hidden px-3 py-2 text-right text-sm text-gray-500 sm:table-cell">${quantity}${weightunit}</td> <td class="hidden px-3 py-2 text-right text-sm text-gray-500 sm:table-cell">${price}</td> <td class="py-2 pl-3 pr-4 text-right text-sm text-gray-500 sm:pr-0">${item.currency} ${total}</td> </tr> `; });
渲染时使用:
<tbody> ${tablerows.join('')} </tbody>
收据样本代码
以下是一个收据生成函数示例:
export function receiptGenerator(seller: any, order: any): string { const panNum = 'XXXXXXXX'; const companyLogo = // your-company-logo const deliveryAddr = order.deliveryAddress; let vat = 0.0; let subTotal = 0; let currency = ''; const tableRows = order.items.map((item, index) => { // ... return ` <tr class="border-b border-gray-200 break-inside-avoid break-before-auto"><td class="max-w-0 py-2 pl-4 pr-3 text-sm sm:pl-0"> <div class="font-medium text-gray-900">${index + 1}.${item.name}</div> </td> <td class="hidden px-3 py-2 text-right text-sm text-gray-500 sm:table-cell">${quantity}${weightUnit}</td> <td class="hidden px-3 py-2 text-right text-sm text-gray-500 sm:table-cell">${price}</td> <td class="py-2 pl-3 pr-4 text-right text-sm text-gray-500 sm:pr-0">${item.currency} ${total}</td> </tr> `; }); // ... (其余代码保持不变) ... }
希望以上信息对您有所帮助! 作者花费两天时间优化此方案。
以上就是使用样本收据打印 HTML 最佳技术的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号