# LRS PDF Viewer Integration - Step by Step Guide

## 📍 Your Current URL Flow

```
1. Search: http://10.10.10.3:8080/lrswa/welcome.do#result:Transaction:SourcePropertyIDs=bp703
2. Transaction: http://10.10.10.3:8080/lrswa/welcome.do#detail:Transaction:10000000000121
3. Document: http://10.10.10.3:8080/lrswa/welcome.do#detail:SourceDocument:10000000000188
   └─> Need: "View PDF" button here that opens multi-page PDF in new tab
```

## 🎯 Goal

Add a **"View PDF"** button to the SourceDocument detail page that:
- Opens a multi-page PDF in a new browser tab
- Merges all document images based on `page_count`
- Works with document ID `10000000000188` from the URL

---

## 📝 Step 1: Update Your Python API

### 1.1 Add the new endpoints

Open `multipage_pdf_api.py` and add these new endpoints (from the artifact above):

```python
@app.get("/documents/id/{document_id}/pdf")
async def stream_pdf_by_id(document_id: int, regenerate: bool = False):
    # ... (copy from artifact)
```

This allows you to use:
```
http://localhost:8001/documents/id/10000000000188/pdf
```

### 1.2 Restart the API

```bash
# Stop if running (Ctrl+C)
# Then restart:
python multipage_pdf_api.py
```

### 1.3 Test the new endpoint

Open browser and test:
```
http://localhost:8001/documents/id/10000000000188/pdf
```

You should see a PDF download or open.

---

## 📝 Step 2: Add JavaScript to Your LRS UI

### 2.1 Locate your main JavaScript file

Find one of these files in your LRS deployment:
```
C:\LRSAS\server\default\deploy\lrswa.war\js\
  - main.js
  - forms.js
  - tabs.js
  - utils.js
```

Or create a new file:
```
C:\LRSAS\server\default\deploy\lrswa.war\js\pdf-viewer.js
```

### 2.2 Add the integration code

Copy the entire JavaScript code from the "LRS UI PDF Viewer Integration" artifact above.

### 2.3 Include the script in your HTML

Edit `Details_Document.html` or `welcome.do.jsp` and add:

```html
<SCRIPT src="/lrswa/js/pdf-viewer.js" type="text/javascript"></SCRIPT>
```

Add this **before** the closing `</BODY>` tag.

---

## 📝 Step 3: Simple Manual Integration (Alternative)

If modifying files is difficult, use this **console-based approach** for testing:

### 3.1 Open SourceDocument detail page

Navigate to:
```
http://10.10.10.3:8080/lrswa/welcome.do#detail:SourceDocument:10000000000188
```

### 3.2 Open browser console (F12)

Paste this code:

```javascript
// Quick PDF viewer function
function viewPDF() {
    var hash = window.location.hash;
    var match = hash.match(/detail:SourceDocument:(\d+)/);
    
    if (match && match[1]) {
        var docId = match[1];
        var pdfUrl = 'http://localhost:8001/documents/id/' + docId + '/pdf';
        window.open(pdfUrl, '_blank', 'width=1024,height=768');
    } else {
        alert('Could not find document ID in URL');
    }
}

// Call it
viewPDF();
```

### 3.3 Create a bookmark

Create a browser bookmark with this JavaScript:

```javascript
javascript:(function(){var h=window.location.hash;var m=h.match(/detail:SourceDocument:(\d+)/);if(m&&m[1]){var u='http://localhost:8001/documents/id/'+m[1]+'/pdf';window.open(u,'_blank','width=1024,height=768');}else{alert('Not on a document page');}})();
```

Name it **"View PDF"** and click it when on a document page.

---

## 📝 Step 4: Proper UI Integration (Recommended)

### 4.1 Find the SourceDocument rendering code

Search your codebase for:
```javascript
function getDocumentSearchForm()
// or
case 'SourceDocument':
// or
'detail:SourceDocument'
```

### 4.2 Add button to the detail panel

When the SourceDocument detail loads, add this code:

```javascript
// In your existing detail rendering function
function showSourceDocumentDetail(documentId) {
    // ... existing code ...
    
    // Add PDF button
    var toolbar = detailPanel.getTopToolbar();
    if (toolbar && !toolbar.find('id', 'btn-view-pdf')[0]) {
        toolbar.add({
            id: 'btn-view-pdf',
            text: 'View PDF',
            icon: '/lrswa/images/pdf.png',
            handler: function() {
                var pdfUrl = 'http://localhost:8001/documents/id/' + documentId + '/pdf';
                window.open(pdfUrl, '_blank', 'width=1024,height=768');
            }
        });
        toolbar.doLayout();
    }
    
    // ... rest of existing code ...
}
```

### 4.3 Add to existing buttons

If you have existing buttons (like Print, Close), add PDF button next to them:

```javascript
buttons: [
    {
        text: 'Print',
        handler: printDocument
    },
    {
        text: 'View PDF',  // <-- ADD THIS
        handler: function() {
            var docId = getCurrentDocumentId();
            var pdfUrl = 'http://localhost:8001/documents/id/' + docId + '/pdf';
            window.open(pdfUrl, '_blank');
        }
    },
    {
        text: 'Close',
        handler: closePanel
    }
]
```

---

## 📝 Step 5: Testing

### 5.1 Test with known document

1. Navigate to a document you know exists:
   ```
   http://10.10.10.3:8080/lrswa/welcome.do#detail:SourceDocument:10000000000188
   ```

2. Look for the "View PDF" button

3. Click it - PDF should open in new tab

### 5.2 Check browser console

Press **F12** and check for errors:
- ✅ "Opening PDF for document: 10000000000188"
- ✅ "PDF opened successfully"
- ❌ "Failed to connect to PDF service" - API not running
- ❌ "CORS error" - CORS not configured

### 5.3 Verify PDF content

The PDF should have:
- All pages from the document (matching `page_count`)
- One image per page
- Correct document number as filename

---

## 🔧 Troubleshooting

### Issue: Button doesn't appear

**Check:**
1. Is the JavaScript file loaded?
   - View page source, look for `<script src="/lrswa/js/pdf-viewer.js">`

2. Is Ext.onReady firing?
   - Console: `console.log('Ext ready:', Ext.isReady)`

3. Is the panel found?
   - Console: `Ext.getCmp('tab-details')`

**Solution:**
```javascript
// Force add button manually
setTimeout(function() {
    var panel = Ext.getCmp('tab-details');
    if (panel) addPDFViewerButton(panel);
}, 1000);
```

### Issue: PDF doesn't open

**Check:**
1. Is API running?
   ```bash
   curl http://localhost:8001/health
   ```

2. Does document exist?
   ```bash
   curl http://localhost:8001/documents/id/10000000000188/metadata
   ```

3. Popup blocked?
   - Allow popups for `10.10.10.3:8080`

### Issue: CORS error

**Check browser console:**
```
Access to XMLHttpRequest at 'http://localhost:8001' from origin 'http://10.10.10.3:8080' has been blocked by CORS policy
```

**Solution:**
Update `multipage_pdf_api.py`:
```python
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://10.10.10.3:8080"],
    allow_credentials=True,
    allow_methods=["GET"],
    allow_headers=["*"],
)
```

### Issue: Wrong document ID

**Check URL hash:**
```javascript
console.log(window.location.hash);
// Should show: #detail:SourceDocument:10000000000188
```

**Solution:**
Update regex pattern:
```javascript
var match = hash.match(/detail:SourceDocument:(\d+)/);
console.log('Matched ID:', match ? match[1] : 'none');
```

---

## 🎨 Customization Options

### Option 1: Inline PDF viewer (same tab)

Instead of new tab, embed in current page:

```javascript
function showPDFInline(documentId) {
    var pdfUrl = 'http://localhost:8001/documents/id/' + documentId + '/pdf';
    
    var pdfPanel = new Ext.Panel({
        title: 'Document PDF',
        closable: true,
        html: '<iframe src="' + pdfUrl + '" width="100%" height="100%" frameborder="0"></iframe>'
    });
    
    Ext.getCmp('main-pnl').add(pdfPanel);
    Ext.getCmp('main-pnl').setActiveTab(pdfPanel);
}
```

### Option 2: Preview thumbnail

Show PDF preview in detail panel:

```javascript
{
    xtype: 'panel',
    title: 'Document Preview',
    height: 300,
    html: '<iframe src="' + pdfUrl + '#page=1&zoom=50" width="100%" height="100%"></iframe>'
}
```

### Option 3: Download instead of view

```javascript
handler: function() {
    window.location.href = 'http://localhost:8001/documents/id/' + docId + '/pdf?download=true';
}
```

---

## ✅ Final Checklist

- [ ] Python API running on port 8001
- [ ] Database connection configured
- [ ] Contentstore path correct
- [ ] JavaScript added to LRS UI
- [ ] CORS configured for LRS server
- [ ] Tested with known document ID
- [ ] PDF opens in new tab
- [ ] Multiple pages displayed correctly
- [ ] JBoss cache cleared (if needed)

---

## 🚀 Quick Start Summary

**Minimal setup:**

1. **Start API:**
   ```bash
   python multipage_pdf_api.py
   ```

2. **Test endpoint:**
   ```
   http://localhost:8001/documents/id/10000000000188/pdf
   ```

3. **Add bookmark with JavaScript code above**

4. **Click bookmark when viewing a document**

That's it! PDF opens in new tab with all pages merged.

---

## 📞 Need Help?

If stuck, test each layer:

1. **Database:** Can you query `lr_source_document`?
2. **API:** Does `/health` endpoint work?
3. **Document:** Does `/documents/id/10000000000188/metadata` return data?
4. **PDF:** Does `/documents/id/10000000000188/pdf` generate PDF?
5. **UI:** Does JavaScript execute? Check browser console.

Good luck! 🎉