InvoicePrinter JSON API使用指南:从Node.js到Python的简单集成方案
2026/6/22 23:56:21 网站建设 项目流程

InvoicePrinter JSON API使用指南:从Node.js到Python的简单集成方案

【免费下载链接】invoice_printerSuper simple PDF invoicing项目地址: https://gitcode.com/gh_mirrors/in/invoice_printer

InvoicePrinter是一款超级简单的PDF发票生成工具,它提供了强大的JSON API接口,让开发者可以轻松地在各种编程语言中集成发票生成功能。无论是Node.js还是Python,通过简洁的API调用,你都能快速生成专业美观的PDF发票。

🚀 快速了解InvoicePrinter JSON API

InvoicePrinter的JSON API基于HTTP协议设计,主要提供两个核心端点:

  • POST /print:生成PDF文件并保存到指定路径
  • POST /render:生成PDF数据流并以Base64格式返回

这两个接口都接受JSON格式的请求数据,让跨语言集成变得异常简单。

🔍 API请求结构概览

所有API请求都需要设置正确的Content-Type: application/json头信息,并包含以下主要参数:

  • document:发票核心数据(必填)
  • labels:自定义标签(可选)
  • font/bold_font:字体设置(可选)
  • logo/qr/stamp:图像资源路径(可选)
  • background:背景图片(可选)
  • page_size:纸张尺寸(可选,默认A4)

下面是一个典型的发票生成效果示例,展示了InvoicePrinter的排版能力:

🔧 开始使用前的准备工作

1️⃣ 安装InvoicePrinter

首先需要安装InvoicePrinter工具,你可以通过RubyGems安装:

gem install invoice_printer

或者从源码仓库克隆并安装:

git clone https://gitcode.com/gh_mirrors/in/invoice_printer cd invoice_printer bundle install

2️⃣ 启动API服务器

安装完成后,启动内置的API服务器:

invoice_printer server

默认情况下,服务器会在本地的9292端口运行,你可以通过http://localhost:9292访问API。

💻 Node.js集成指南

基础请求示例

以下是一个使用Node.js调用InvoicePrinter API的基本示例:

const axios = require('axios'); const fs = require('fs'); async function generateInvoice() { const invoiceData = { document: { provider: { name: "ACME Corp", address: "123 Business St", city: "New York", zip: "10001", country: "USA" }, purchaser: { name: "John Doe", address: "456 Customer Ave", city: "Boston", zip: "02108", country: "USA" }, items: [ { name: "Web Development", quantity: 10, unit: "hour", price: 100, amount: 1000 }, { name: "Design Services", quantity: 5, unit: "hour", price: 80, amount: 400 } ], number: "INV-2023-001", issue_date: "2023-06-01", due_date: "2023-06-15", subtotal: 1400, tax: 280, total: 1680 } }; try { // 调用render接口获取Base64编码的PDF const response = await axios.post('http://localhost:9292/render', invoiceData, { headers: { 'Content-Type': 'application/json' } }); // 解码并保存PDF文件 const pdfBuffer = Buffer.from(response.data.data, 'base64'); fs.writeFileSync('invoice.pdf', pdfBuffer); console.log('Invoice generated successfully!'); } catch (error) { console.error('Error generating invoice:', error.response?.data || error.message); } } generateInvoice();

保存文件到服务器

如果你希望直接保存文件到服务器,可以使用/print接口:

// 修改请求数据,添加filename参数 const printData = { ...invoiceData, filename: "/path/to/save/invoice.pdf" }; // 调用print接口 const response = await axios.post('http://localhost:9292/print', printData, { headers: { 'Content-Type': 'application/json' } }); console.log('Invoice saved to:', response.data.path);

🐍 Python集成指南

使用requests库调用API

以下是使用Python的requests库调用InvoicePrinter API的示例:

import requests import base64 def generate_invoice(): invoice_data = { "document": { "provider": { "name": "ACME Corp", "address": "123 Business St", "city": "New York", "zip": "10001", "country": "USA" }, "purchaser": { "name": "John Doe", "address": "456 Customer Ave", "city": "Boston", "zip": "02108", "country": "USA" }, "items": [ {"name": "Web Development", "quantity": 10, "unit": "hour", "price": 100, "amount": 1000}, {"name": "Design Services", "quantity": 5, "unit": "hour", "price": 80, "amount": 400} ], "number": "INV-2023-001", "issue_date": "2023-06-01", "due_date": "2023-06-15", "subtotal": 1400, "tax": 280, "total": 1680 } } try: # 调用render接口 response = requests.post( "http://localhost:9292/render", json=invoice_data, headers={"Content-Type": "application/json"} ) response.raise_for_status() # 解码并保存PDF pdf_data = base64.b64decode(response.json()["data"]) with open("invoice.pdf", "wb") as f: f.write(pdf_data) print("Invoice generated successfully!") except requests.exceptions.RequestException as e: print(f"Error generating invoice: {e}") generate_invoice()

添加自定义样式和图片

你可以通过添加可选参数来自定义发票样式:

# 添加logo和背景图片 invoice_data["logo"] = "path/to/logo.png" invoice_data["background"] = "examples/background.png" invoice_data["qr"] = "examples/qr.png" # 自定义标签(多语言支持) invoice_data["labels"] = { "invoice": "Factura", "provider": "Proveedor", "purchaser": "Comprador", "issue_date": "Fecha de emisión", "due_date": "Fecha de vencimiento" }

📝 API响应处理

InvoicePrinter API始终返回JSON格式的响应,包含以下字段:

  • result: "ok" 或 "error"
  • path: 当使用/print时,返回保存的文件路径
  • data: 当使用/render时,返回Base64编码的PDF数据
  • error: 发生错误时,返回错误信息

错误处理最佳实践

// Node.js错误处理示例 try { // API调用代码 } catch (error) { if (error.response) { console.error('API Error:', error.response.data.error); if (error.response.status === 400) { console.error('Check your JSON format or document structure'); } } else { console.error('Connection Error:', error.message); } }

📚 进阶功能

自定义字体

InvoicePrinter支持自定义字体,项目中已包含多种字体供选择:

  • assets/fonts/opensans/
  • assets/fonts/overpass/
  • assets/fonts/roboto/

使用自定义字体:

{ "font": "assets/fonts/roboto/Roboto-Regular.ttf", "bold_font": "assets/fonts/roboto/Roboto-Bold.ttf" }

多页面支持

当发票项目较多时,InvoicePrinter会自动分页。你可以通过查看测试文件了解分页实现:

  • test/page_numbers_test.rb

国际化支持

通过自定义标签实现多语言支持:

{ "labels": { "invoice": "Rechnung", "provider": "Anbieter", "purchaser": "Kunde", "item": "Artikel", "quantity": "Menge", "unit": "Einheit", "price": "Preis", "amount": "Betrag" } }

🛠️ 故障排除

常见问题解决

  1. Invalid JSON错误:检查请求数据是否为有效的JSON格式
  2. Invalid file path错误:确保图片路径正确且服务器有权限访问
  3. 服务器启动失败:检查Ruby版本是否符合要求(项目需要Ruby 2.5+)

获取帮助

如果遇到问题,可以查阅项目文档:

  • docs/ - 项目文档目录
  • test/ - 包含API测试用例,可参考示例请求

🎯 总结

InvoicePrinter JSON API为不同编程语言提供了统一的发票生成接口,无论是Node.js还是Python开发者,都能轻松集成。通过简单的JSON数据结构,你可以快速生成专业的PDF发票,满足各种业务需求。

无论是小型企业的简单账单,还是复杂的国际贸易发票,InvoicePrinter都能提供高效、可靠的解决方案。立即尝试将它集成到你的应用中,提升发票处理效率!

【免费下载链接】invoice_printerSuper simple PDF invoicing项目地址: https://gitcode.com/gh_mirrors/in/invoice_printer

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询