{"id":28059573,"url":"https://github.com/priom7/json2pdf","last_synced_at":"2025-05-12T08:07:19.249Z","repository":{"id":289470340,"uuid":"966687485","full_name":"Priom7/json2pdf","owner":"Priom7","description":"A lightweight, browserless REST API that generates print-ready PDF question papers from structured JSON data using PDFKit — ideal for educational platforms that require professional formatting without the overhead of headless browsers like Puppeteer.","archived":false,"fork":false,"pushed_at":"2025-05-08T15:36:55.000Z","size":5816,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-12T08:07:11.346Z","etag":null,"topics":["devtool","json","nodejs","npm-package","opensource","pdf","tool"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/@priom7/json2pdf","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Priom7.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-04-15T09:54:44.000Z","updated_at":"2025-05-08T15:37:25.000Z","dependencies_parsed_at":null,"dependency_job_id":"6c6b9d34-1e06-4cff-ad33-554480c0ce92","html_url":"https://github.com/Priom7/json2pdf","commit_stats":null,"previous_names":["priom7/json-to-pdf-generator"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Priom7%2Fjson2pdf","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Priom7%2Fjson2pdf/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Priom7%2Fjson2pdf/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Priom7%2Fjson2pdf/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Priom7","download_url":"https://codeload.github.com/Priom7/json2pdf/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253700617,"owners_count":21949694,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["devtool","json","nodejs","npm-package","opensource","pdf","tool"],"created_at":"2025-05-12T08:07:18.502Z","updated_at":"2025-05-12T08:07:19.227Z","avatar_url":"https://github.com/Priom7.png","language":"JavaScript","readme":"# 📄 Custom PDF Generator for Question Papers\n\nA lightweight, browserless REST API that generates print-ready PDF question papers from structured JSON data using **PDFKit** — ideal for educational platforms that require professional formatting without the overhead of headless browsers like Puppeteer.\n\n---\n\n## 🚀 Features\n\n- 📘 Generates PDF directly from JSON using [PDFKit](https://github.com/foliojs/pdfkit)\n- 🧾 Structured two-column question format\n- ✅ Supports multiple question types: **MCQ, numerical, descriptive**\n- 📑 Separate sections for **questions**, **answer key**, and **solutions**\n- ✏️ Clean and print-friendly layout\n- ⚡ Fast and efficient (no browser required)\n- 🖼️ Supports images, formulas (SVG), and custom logos/fonts\n\n---\n\u003cimg src=\"https://github.com/Priom7/JSON-to-PDF-Generator/blob/main/sample-output.png\" alt=\"JSON to PDF Generator\" width=\"100%\" height=\"auto\"\u003e\n---\n\n## 🛠️ Setup Instructions\n\n### 📋 Prerequisites\n\n- Node.js (v14 or higher)\n- npm or yarn\n\n### 📦 Installation\n\n```bash\ngit clone https://github.com/Priom7/JSON-to-PDF-Generator.git\ncd JSON-to-PDF-Generator\n\n# Install dependencies\nnpm install\n\n# Start the server\nnpm start\n```\n\nAPI will be available at:  \n**`http://localhost:3000/api/generate-pdf`**\n\n---\n\n## 📡 API Documentation\n\n### 📍 Endpoint\n\n```\nPOST /api/generate-pdf\n```\n\n**Content-Type**: `application/json`  \n**Response**: `application/pdf`\n\n### 📥 Request Body Example\n\n```json\n{\n  \"title\": \"Physics Examination Paper\",\n  \"subject\": \"Physics\",\n  \"date\": \"April 15, 2025\",\n  \"duration\": \"3 hours\",\n  \"totalMarks\": 100,\n  \"instructions\": [\n    \"All questions are compulsory\",\n    \"There is no negative marking\"\n  ],\n  \"questions\": [\n    {\n      \"type\": \"mcq\",\n      \"text\": \"A particle moves along the x-axis...\",\n      \"options\": [\"300 J\", \"900 J\", \"1000 J\", \"3000 J\"],\n      \"correctOption\": 3,\n      \"solution\": \"Work done = ∫F(x)dx from x=0 to x=10...\"\n    }\n  ]\n}\n```\n\n### ✅ Success Response\n\n- `Status: 200 OK`\n- `Content-Type: application/pdf`\n- Body: Binary PDF file\n\n### ❌ Error Responses\n\n- `400 Bad Request` – Invalid JSON\n- `500 Internal Server Error` – PDF generation failed\n\n---\n\n## 📐 JSON Schema\n\n| Field         | Type               | Description                                |\n| ------------- | ------------------ | ------------------------------------------ |\n| `title`       | `String`           | Title of the examination paper             |\n| `subject`     | `String`           | Subject name                               |\n| `date`        | `String`           | Exam date                                  |\n| `duration`    | `String`           | Exam duration (e.g., `\"3 hours\"`)          |\n| `totalMarks`  | `Number`           | Total marks                                |\n| `instructions`| `Array\u003cString\u003e`    | Exam instructions                          |\n| `questions`   | `Array\u003cObject\u003e`    | List of questions                          |\n\n### 🎯 Question Object\n\n| Field          | Type               | Description                                               |\n| -------------- | ------------------ | --------------------------------------------------------- |\n| `type`         | `String`           | `\"mcq\"`, `\"numerical\"`, or `\"descriptive\"`                |\n| `text`         | `String`           | Question text                                             |\n| `options`      | `Array\u003cString\u003e`    | (For MCQ) Answer options                                  |\n| `correctOption`| `Number`           | (For MCQ) Index of correct option                         |\n| `answer`       | `String`           | Correct answer (numerical/descriptive)                   |\n| `solution`     | `String`           | Detailed solution explanation                            |\n| `images`       | `Array\u003cObject\u003e`    | (Optional) Images with `path`, `width`, `height`, `position` |\n\n---\n\n## 🎨 Customization\n\n### 🧱 Layout Configuration (`pdfGenerator.js`)\n\n```js\nconst CONFIG = {\n  pageSize: 'A4',\n  margin: { top: 50, bottom: 50, left: 40, right: 40 },\n  columns: 2,\n  columnGap: 20,\n  fonts: {\n    regular: 'Helvetica',\n    bold: 'Helvetica-Bold',\n    italic: 'Helvetica-Oblique'\n  },\n  fontSize: {\n    title: 16,\n    header: 12,\n    subHeader: 10,\n    normal: 10,\n    small: 8\n  }\n};\n```\n\n### 🔡 Custom Fonts\n\n1. Add your `.ttf` font files to a `fonts/` directory.\n2. Register them in `pdfGenerator.js`:\n\n```js\ndoc.registerFont('CustomFont', 'fonts/CustomFont.ttf');\n```\n\nUpdate config:\n\n```js\nfonts: {\n  regular: 'CustomFont',\n  bold: 'CustomFont-Bold',\n  italic: 'CustomFont-Italic'\n}\n```\n\n### 🖼️ Logo Support\n\nInclude in JSON:\n\n```json\n\"logoPath\": \"path/to/logo.png\"\n```\n\n---\n\n## 🔢 Math \u0026 Image Support\n\n- **Simple Math**: Unicode math characters\n- **Complex Math**: Include `\u003csvg\u003e` in question text or integrate [mathjax-node](https://github.com/mathjax/MathJax-node)\n- **Images**:\n\n```json\n\"images\": [\n  {\n    \"path\": \"path/to/image.png\",\n    \"width\": 300,\n    \"height\": 200,\n    \"position\": \"center\"\n  }\n]\n```\n\n---\n\n## 📄 Page Numbering\n\nAdd to `pdfGenerator.js`:\n\n```js\ndoc.on('pageAdded', () =\u003e {\n  const pageCount = doc.bufferedPageRange().count;\n  doc.switchToPage(pageCount - 1);\n  doc.fontSize(8)\n     .text(`Page ${pageCount}`, doc.page.width / 2, doc.page.height - 20, { align: 'center' });\n});\n```\n\n---\n\n## 🐳 Docker Deployment\n\n### 🧾 Dockerfile\n\n```dockerfile\nFROM node:16-alpine\n\nWORKDIR /usr/src/app\n\nCOPY package*.json ./\nRUN npm install\n\nCOPY . .\n\nEXPOSE 3000\n\nCMD [\"node\", \"server.js\"]\n```\n\n### 📦 Build \u0026 Run\n\n```bash\ndocker build -t pdf-generator .\ndocker run -p 3000:3000 pdf-generator\n```\n\n---\n\n## ☁️ Cloud Deployment\n\n### AWS Elastic Beanstalk\n\n```bash\neb init\neb create pdf-generator-env\neb deploy\n```\n\n### Heroku\n\n```bash\nheroku create\ngit push heroku main\n```\n\n---\n\n## 🧪 Test Script\n\nCreate `sample-data.json`, then run:\n\n```bash\nnode test.js\n```\n\n**`test.js`** example:\n\n```js\nconst fs = require('fs');\nconst path = require('path');\nconst { generatePDF } = require('./pdfGenerator');\n\nasync function testPDFGeneration() {\n  const dataPath = path.join(__dirname, 'sample-data.json');\n  if (!fs.existsSync(dataPath)) return console.error('sample-data.json not found');\n\n  const data = JSON.parse(fs.readFileSync(dataPath, 'utf8'));\n  const pdf = await generatePDF(data);\n  fs.writeFileSync('output-test.pdf', pdf);\n  console.log('PDF generated → output-test.pdf');\n}\n\ntestPDFGeneration().catch(console.error);\n```\n\n---\n\n## 🛡️ Security \u0026 Optimization\n\n- ✅ Input validation \u0026 sanitization\n- 🔐 Add authentication for production\n- ⏳ Use queues for batch requests\n- 🧠 Add caching for templates\n- 🚫 Rate limiting to prevent abuse\n\n---\n\n## 🐞 Troubleshooting\n\n| Issue                           | Solution                                                      |\n| ------------------------------ | ------------------------------------------------------------- |\n| Large JSON payload              | `bodyParser.json({ limit: '50mb' })`                         |\n| Fonts not rendering             | Ensure correct path and supported format (TTF/OTF)           |\n| Images not displaying           | Check file path and permissions                              |\n| Memory issues with large PDFs  | Use streaming instead of buffering                           |\n\nEnable debug logs:\n\n```bash\nDEBUG=true node server.js\n```\n\n---\n\n## 🤝 Contributing\n\n1. Fork the repo\n2. Create a feature branch: `git checkout -b feature/your-feature`\n3. Commit: `git commit -m \"Add your feature\"`\n4. Push: `git push origin feature/your-feature`\n5. Open a Pull Request 🚀\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpriom7%2Fjson2pdf","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpriom7%2Fjson2pdf","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpriom7%2Fjson2pdf/lists"}