Skip to content

Sonucs12/Readmecode-pdf

Repository files navigation

Readmecode-pdf πŸš€

No description provided

This backend service provides functionalities for generating PDFs from HTML content and tracking visitor counts. It leverages technologies like Express.js, Puppeteer, and Firebase for its operations.

Table of Contents πŸ“œ

Project Title & Badges πŸ†

  • Build Status: Build Status
  • Version: npm version
  • License: License: MIT
  • Stars: GitHub stars
  • Forks: GitHub forks

Description πŸ“

The Readmecode-pdf project is a backend service primarily built with Node.js and Express.js. It is designed to generate PDF documents from HTML content using Puppeteer and to track visitor counts for various users, integrating with Firebase for data persistence. The service offers endpoints for PDF generation, visitor tracking, and badge customization.

Features ✨

  • PDF Generation: Converts HTML content into PDF documents using Puppeteer. Supports caching for generated PDFs to improve performance.
  • Visitor Count Tracking: Tracks visitor counts for specific user IDs, with options to store data in Firebase Firestore or fall back to in-memory storage.
  • Dynamic SVG Badges: Generates customizable SVG badges to display visitor counts, with various styles and color options.
  • Firebase Integration: Leverages Firebase for persistent storage of visitor counts and user configurations.
  • CORS Configuration: Implements Cross-Origin Resource Sharing with a configurable list of allowed origins.
  • Health Check Endpoint: Provides a /health endpoint to check the status of the service and its components.
  • Graceful Shutdown: Handles SIGTERM and SIGINT signals for a clean server shutdown.
  • Environment Variable Support: Uses dotenv to manage environment variables, including specific configurations for production and local development.

Tech Stack πŸ’»

  • Languages: JavaScript
  • Frameworks/Libraries: Node.js, Express.js, React (implied by devDependencies), TypeScript (implied by devDependencies), Puppeteer, pdf-lib, Firebase, axios, body-parser, cheerio, compression, cors, dotenv, jsdom, node-fetch
  • Development Tools: ESLint

Installation πŸ› οΈ

  1. Clone the repository:

    git clone https://github.com/Sonucs12/Readmecode-pdf.git
    cd Readmecode-pdf
  2. Install dependencies:

    npm install

    This command will also run npx puppeteer browsers install chrome as per the postinstall script in package.json to ensure Puppeteer has a compatible Chrome browser.

  3. Set up environment variables: Create a .env.local file in the root of the project and add your Firebase credentials and any other necessary environment variables:

    FIREBASE_API_KEY=YOUR_API_KEY
    FIREBASE_AUTH_DOMAIN=YOUR_AUTH_DOMAIN
    FIREBASE_PROJECT_ID=YOUR_PROJECT_ID
    FIREBASE_STORAGE_BUCKET=YOUR_STORAGE_BUCKET
    FIREBASE_MESSAGING_SENDER_ID=YOUR_MESSAGING_SENDER_ID
    FIREBASE_APP_ID=YOUR_APP_ID
    FIREBASE_MEASUREMENT_ID=YOUR_MEASUREMENT_ID
    PORT=3000
    

Usage πŸ’‘

This project serves as a backend API. Here are the primary use cases:

  1. Generating PDF Reports: You can send a POST request to the /generate-pdf endpoint with HTML content to receive a PDF file.

    Example Request:

    curl -X POST http://localhost:3000/generate-pdf \
      -H "Content-Type: application/json" \
      -d '{
        "html": "<h1>Hello World!</h1><p>This is a test PDF.</p>",
        "brandName": "My App"
      }' \
      -o output.pdf
  2. Tracking Website Visitors: The service allows you to track unique visitors for your projects. A userId is required to identify the visitor.

    • Initialization: First, initialize the user and their preferred badge style via the /init endpoint.
      curl -X POST http://localhost:3000/init \
        -H "Content-Type: application/json" \
        -d '{
          "userId": "user123",
          "style": "style1",
          "timestamp": "2023-10-27T10:00:00Z",
          "bg": "gradient-blue",
          "textColor": "#ffffff"
        }'
    • Increment Count: Send a POST request to /increment with the userId to increment the visitor count.
      curl -X POST http://localhost:3000/increment \
        -H "Content-Type: application/json" \
        -d '{"userId": "user123"}'
    • Get Badge: Retrieve a dynamic SVG badge representing the visitor count.
      curl http://localhost:3000/badge/user123
      You can also customize the badge via query parameters:
      curl http://localhost:3000/badge/user123?style=shield1&bg=gradient-green&textColor=%23000000
  3. Health Check: Check the status of the service and its components.

    curl http://localhost:3000/health

How to use πŸš€

This backend is designed to be integrated into larger applications. The primary use cases include:

  • Generating dynamic reports or documents (e.g., invoices, certificates, summaries) that can be downloaded as PDFs.
  • Adding visitor counters to personal portfolios, blogs, or open-source projects, visualized through customizable SVG badges.
  • Providing an API for a frontend application that requires PDF generation or visitor analytics features.

Example Integration Scenario:

Imagine a project where users can generate personalized resumes from a template. The frontend would send the resume's HTML content to the /generate-pdf endpoint, and the backend would return the PDF. Simultaneously, the frontend could increment a visitor count for that user's profile page by calling the /increment endpoint with the user's ID, and display a badge showing the total visits using the /badge/:userId endpoint.

Project Structure πŸ“

Readmecode-pdf/
β”œβ”€β”€ .env.local          # Environment variables (not in git)
β”œβ”€β”€ CHANGELOG.md        # Project changelog
β”œβ”€β”€ Procfile            # Process definition for deployment
β”œβ”€β”€ README.md           # Project README file
β”œβ”€β”€ eslint.config.mjs   # ESLint configuration
β”œβ”€β”€ firebaseUtils.js    # Firebase Firestore utility functions
β”œβ”€β”€ package.json        # Project metadata and dependencies
β”œβ”€β”€ pdfRoutes.js        # Routes for PDF generation and management
β”œβ”€β”€ puppeteer.config.cjs # Puppeteer configuration
β”œβ”€β”€ server.js           # Main Express server entry point
β”œβ”€β”€ svgTemplates.js     # SVG badge template generation
β”œβ”€β”€ visitorRoutes.js    # Routes for visitor tracking and badge generation
└── pdf_cache/          # Directory for cached PDF files (generated at runtime)

API Reference 🌐

PDF Generation

  • POST /generate-pdf Generates a PDF from provided HTML content.

    • Request Body:
      {
        "html": "string", // HTML content to convert
        "brandName": "string" // Optional brand name for footer
      }
    • Response: PDF file stream.
  • GET /debug-pdf A debug endpoint to generate a sample PDF.

    • Response: PDF file stream.

Visitor Tracking & Badges

  • POST /init Initializes a user with badge preferences.

    • Request Body:
      {
        "userId": "string",
        "style": "string", // e.g., "style1", "shield1"
        "timestamp": "string",
        "bg": "string", // Optional: background color or gradient key
        "textColor": "string" // Optional: text color
      }
    • Response: { success: true, stored: {...} }
  • POST /increment Increments the visitor count for a given userId.

    • Request Body:
      {
        "userId": "string"
      }
    • Response: { success: true, count: number, storage: "firebase" | "memory" }
  • GET /badge/:userId Serves a dynamic SVG badge with the visitor count.

    • Query Parameters:
      • style: Badge style (e.g., style1, shield1).
      • bg: Background color or gradient key (e.g., gradient-blue).
      • textColor: Text color.
    • Response: SVG image.
  • POST /badge/style Sets the preferred badge style for a user in Firestore.

    • Request Body:
      {
        "userId": "string",
        "style": "string"
      }
    • Response: { success: true }
  • GET /badge/styles Lists available badge styles.

    • Response: { styles: [{ key: "string" }, ...] }
  • GET /badge/gradients Lists available gradient options for badges.

    • Response: { gradients: [{ value: "string", label: "string", gradient: "string" }, ...] }

Health Check

  • GET /health Checks the health status of the service.
    • Response:
      {
        "status": "OK",
        "timestamp": "string",
        "browserConnected": boolean,
        "memoryCacheSize": number
      }

Contributing 🀝

Contributions are welcome! Please follow these steps:

  1. Fork the repository.
  2. Create a new branch for your feature (git checkout -b feature/AmazingFeature).
  3. Commit your changes (git commit -m 'Add some AmazingFeature').
  4. Push to the branch (git push origin feature/AmazingFeature).
  5. Open a Pull Request.

Please ensure you add tests for your changes and update the documentation if necessary.

License πŸ“„

This project is licensed under the MIT License - see the LICENSE file for details.

Important Links πŸ”—

Footer πŸ“

Β© 2023 Sonucs12. All rights reserved.

Repository: Readmecode-pdf

Feel free to fork, star ⭐, and report issues on the repository!


Generated by ReadmeCodeGen

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors