bettertend/frontend/PDF_TROUBLESHOOTING.md

8.1 KiB

PDF Report Download Troubleshooting Guide

🔍 Issue: PDFs View Correctly in Browser but Are Corrupted When Downloaded

This guide addresses the common issue where PDF reports generated from the work order options tab display correctly in the browser window but become corrupted or unreadable when downloaded to disk.

🎭 Demo Mode (No Backend Required)

Since you don't have a backend connected, the system now includes a Mock PDF Generation System that creates fully functional PDF reports using sample data.

How Demo Mode Works:

  1. Attempts real API call first (with 5-second timeout)
  2. Automatically falls back to mock generation when backend unavailable
  3. Creates valid PDF files that can be downloaded and opened
  4. Uses sample work order data for demonstration purposes
  5. Shows "Demo Mode" indicator in the UI

🔧 Solutions Implemented

1. Enhanced PDF Download Handler (WorkOrderRepository.js)

The PDF generation and download functionality has been completely rewritten with:

  • Proper binary data handling with responseType: 'blob'
  • Correct MIME type enforcement (application/pdf)
  • Response validation to ensure data integrity
  • Automatic corruption detection and repair
  • Comprehensive error logging and debugging

2. PDF Debugging Utilities (/src/utils/pdfDebugger.js)

A comprehensive debugging toolkit that:

  • Validates PDF blob integrity by checking headers and structure
  • Detects common corruption patterns (HTML responses, JSON errors, etc.)
  • Provides detailed logging for troubleshooting
  • Attempts automatic repair of corrupted PDFs
  • Safely handles downloads with fallback mechanisms

3. Improved ReportGenerator Component

The ReportGenerator now includes:

  • Separate Preview and Download buttons for better user experience
  • Integration with useWorkOrders composable for proper data handling
  • Real-time PDF validation before download
  • Better error handling and user feedback

🚀 Quick Test (Demo Mode)

Test PDF Generation in Browser Console:

// Quick test - generates and downloads a sample PDF immediately
await quickTest()

// Full test with validation and detailed logging  
await testPDFGeneration()

// Test multiple formats (PDF, HTML, JSON)
await testMultipleFormats()

// Simulate the exact form download process
await simulateFormDownload('WO-123')

Test Through UI:

  1. Navigate to any work order
  2. Click the "Options" tab
  3. Look for "🎭 Demo Mode" indicator in Report Generation section
  4. Configure your report settings (template, sections, etc.)
  5. Click "Download PDF" - should generate and download immediately
  6. Click "Preview" - opens PDF in new browser tab

What's in the Demo PDFs:

The mock PDFs contain realistic work order data including:

  • Work Order Details: ID, title, status, priority, assigned user
  • Asset Information: HVAC system details, model, serial number
  • Location Data: Building location and address
  • Task Lists: Maintenance tasks with completion status
  • Parts Information: Required parts with costs and quantities
  • Cost Summary: Labor hours, parts costs, total budget
  • Timestamps: Creation date, generation date
  • Demo Notice: Clear indication that this is demonstration data

🧪 Testing with Real Backend

In Browser Console

After attempting to download a PDF, check the browser console for detailed debugging information:

// Look for these debug groups:
🔍 PDF Debug: Starting PDF generation
🔍 PDF Debug: Response received  
🔍 PDF Debug: PDF validation
🔍 PDF Debug: PDF download completed

Manual Testing

  1. Open browser DevTools (F12)
  2. Navigate to work order options tab
  3. Configure a report and click "Download PDF"
  4. Check the console for any validation errors or warnings
  5. Verify the downloaded file opens correctly in a PDF viewer

Test Function

You can manually test PDF downloads using:

// In browser console
import { testPDFDownload } from '@/utils/pdfDebugger'

// Test a specific work order report
const results = await testPDFDownload('/api/work-orders/123/report')
console.log('Test results:', results)

🚨 Common Issues and Solutions

Issue 1: "Invalid PDF header" Error

Symptoms: Console shows header validation failed Cause: Server returning HTML error page instead of PDF Solution: Check server response and API endpoint configuration

Issue 2: "PDF blob is empty" Error

Symptoms: Zero-byte file download Cause: API endpoint not returning data or wrong HTTP method Solution: Verify API endpoint is working and returns binary data

Issue 3: "Content-Type" Warnings

Symptoms: PDF downloads but MIME type is incorrect Cause: Server not setting proper content-type header Solution: The debugger automatically corrects MIME type locally

Issue 4: Browser Popup Blocked

Symptoms: Preview doesn't open in new window Cause: Browser blocking popups Solution: Allow popups for the site or use download instead of preview

🔧 Advanced Debugging

Enable Detailed Logging

Add this to your component to enable extra debugging:

// In your Vue component
import { logPDFDebug } from '@/utils/pdfDebugger'

// Before any PDF operation
logPDFDebug('Custom debug point', { 
  workOrderId, 
  options,
  userAgent: navigator.userAgent 
})

Check Network Tab

  1. Open DevTools → Network tab
  2. Filter by XHR/Fetch
  3. Look for the report API call
  4. Check Response Headers for:
    • Content-Type: application/pdf
    • Content-Length: [positive number]
    • Content-Disposition: attachment; filename="..."

Verify Blob Content

// In console after PDF generation fails
const response = await fetch('/api/work-orders/123/report')
const blob = await response.blob()

// Check if it's actually HTML/JSON instead of PDF
const text = await blob.text()
console.log('Response content:', text.substring(0, 200))

🛠️ Server-Side Considerations

If the issue persists, check these server-side factors:

1. Response Headers

Content-Type: application/pdf
Content-Disposition: attachment; filename="report.pdf"  
Content-Length: [actual file size]
Access-Control-Allow-Origin: [your domain]

2. Binary Data Handling

  • Ensure server doesn't modify binary data during transmission
  • Check for character encoding issues (UTF-8 vs binary)
  • Verify no compression is corrupting the PDF

3. CORS Configuration

Access-Control-Allow-Headers: Accept, Content-Type
Access-Control-Allow-Methods: GET, POST
Access-Control-Expose-Headers: Content-Disposition, Content-Length

📱 Browser Compatibility

The solution includes fallbacks for:

  • Firefox: DOM manipulation compatibility
  • Safari: Blob URL handling differences
  • Edge: Download attribute support
  • Chrome: Standard implementation

🎯 How to Use the Fixed Implementation

In Work Order Options Tab:

  1. Navigate to any work order
  2. Click the "Options" tab in the work order form
  3. Configure your report settings in the ReportGenerator component
  4. Click "Preview" to view the PDF in a new window (validates but doesn't download)
  5. Click "Download PDF" to download with corruption detection

Expected Behavior:

  • Preview opens PDF in new browser tab
  • Download saves valid PDF file to disk
  • Console shows detailed debugging information
  • Errors are caught and reported clearly
  • Auto-repair attempts if corruption detected

📞 Additional Support

If issues persist after implementing this solution:

  1. Check the browser console for specific error messages
  2. Test with different browsers to isolate compatibility issues
  3. Verify the server-side API is returning valid PDF data
  4. Use the debugging utilities to get detailed information about the failure

The implementation now provides comprehensive error handling and debugging to help identify exactly where PDF corruption occurs in the download process.