File size: 12,495 Bytes
62a0d03
 
 
e61da5a
62a0d03
 
 
 
 
 
e61da5a
62a0d03
 
e61da5a
 
 
62a0d03
 
 
 
 
 
 
 
 
 
 
e61da5a
 
 
 
 
 
 
 
 
 
 
5ec1f6e
 
e61da5a
5ec1f6e
 
 
 
e61da5a
5ec1f6e
e61da5a
 
 
 
0d059f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e61da5a
0d059f2
 
 
 
 
 
 
e61da5a
 
 
 
62a0d03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e61da5a
 
62a0d03
e61da5a
 
 
09084eb
 
62a0d03
 
 
 
 
 
 
 
 
 
 
e61da5a
62a0d03
 
 
e61da5a
62a0d03
 
e61da5a
62a0d03
 
 
 
 
 
 
 
e61da5a
62a0d03
e61da5a
 
 
62a0d03
 
 
 
 
 
 
e61da5a
 
 
 
 
62a0d03
e61da5a
 
 
 
62a0d03
 
09084eb
 
 
 
62a0d03
 
 
 
09084eb
62a0d03
 
 
 
e61da5a
 
62a0d03
 
 
 
 
e61da5a
62a0d03
 
 
 
e61da5a
62a0d03
 
e61da5a
62a0d03
 
 
 
 
 
e61da5a
62a0d03
e61da5a
 
 
 
 
 
 
 
62a0d03
e61da5a
 
 
 
62a0d03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e61da5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62a0d03
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from fastapi.responses import Response, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from typing import List, Optional
import tempfile
import shutil
import os
import subprocess
import base64
from pathlib import Path
import mimetypes

app = FastAPI(
    title="HTML to PDF API with Image Support",
    description="Convert HTML to PDF using Puppeteer with image upload support",
    version="2.0.0"
)

# Enable CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

def save_uploaded_images(images: List[UploadFile], temp_dir: str):
    """Save uploaded images to temp directory and return mapping"""
    image_mapping = {}
    images_dir = os.path.join(temp_dir, "images")
    os.makedirs(images_dir, exist_ok=True)
    
    for image in images:
        if image.filename:
            # Save image to temp directory
            image_path = os.path.join(images_dir, image.filename)
            with open(image_path, 'wb') as f:
                content = image.file.read()
                f.write(content)
            
            # Reset file pointer for potential reuse
            image.file.seek(0)
            
            # Create mapping with relative path
            image_mapping[image.filename] = f"images/{image.filename}"
            print(f"Saved image: {image.filename} -> {image_path}")
    
    return image_mapping

def process_html_with_images(html_content: str, temp_dir: str, image_mapping: dict):
    """Process HTML to handle image references with absolute file paths"""
    import re
    
    for original_name, relative_path in image_mapping.items():
        # Get absolute path for the image
        absolute_path = os.path.abspath(os.path.join(temp_dir, relative_path))
        file_url = f"file://{absolute_path}"
        
        # Replace various image reference patterns
        # Pattern 1: src="filename"
        html_content = re.sub(
            f'src=["\'](?:\.\/)?{re.escape(original_name)}["\']',
            f'src="{file_url}"',
            html_content,
            flags=re.IGNORECASE
        )
        
        # Pattern 2: src='filename'
        html_content = re.sub(
            f"src=['\"](?:\.\/)?{re.escape(original_name)}['\"]",
            f'src="{file_url}"',
            html_content,
            flags=re.IGNORECASE
        )
        
        # Pattern 3: background-image: url(filename)
        html_content = re.sub(
            f'url\(["\']?(?:\.\/)?{re.escape(original_name)}["\']?\)',
            f'url("{file_url}")',
            html_content,
            flags=re.IGNORECASE
        )
        
        # Pattern 4: href for links
        html_content = re.sub(
            f'href=["\'](?:\.\/)?{re.escape(original_name)}["\']',
            f'href="{file_url}"',
            html_content,
            flags=re.IGNORECASE
        )
    
    return html_content

def convert_html_to_pdf(html_content: str, aspect_ratio: str, temp_dir: str):
    """Convert HTML content to PDF"""
    try:
        # Style injection for better PDF rendering
        style_injection = """
        <style>
            @page { margin: 0; }
            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
                color-adjust: exact !important;
            }
            body {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
        </style>
        """
        
        if '</head>' in html_content:
            html_content = html_content.replace('</head>', style_injection + '</head>')
        elif '<body' in html_content:
            html_content = html_content.replace('<body', style_injection + '<body', 1)
        else:
            html_content = style_injection + html_content
        
        # Save HTML to temp file
        html_file = os.path.join(temp_dir, "input.html")
        with open(html_file, 'w', encoding='utf-8') as f:
            f.write(html_content)
        
        # Get puppeteer script path
        script_dir = os.path.dirname(os.path.abspath(__file__))
        puppeteer_script = os.path.join(script_dir, 'puppeteer_pdf.js')
        
        # Run conversion
        result = subprocess.run(
            ['node', puppeteer_script, html_file, aspect_ratio],
            capture_output=True,
            text=True,
            timeout=60,
            cwd=script_dir
        )
        
        if result.returncode != 0:
            raise Exception(f"PDF conversion failed: {result.stderr}")
        
        pdf_file = html_file.replace('.html', '.pdf')
        
        if not os.path.exists(pdf_file):
            raise Exception("PDF file was not generated")
        
        with open(pdf_file, 'rb') as f:
            pdf_bytes = f.read()
        
        return pdf_bytes
        
    except Exception as e:
        raise e

@app.get("/")
async def root():
    """API root endpoint"""
    return {
        "message": "HTML to PDF Conversion API with Image Support",
        "version": "2.0.0",
        "endpoints": {
            "POST /convert": "Convert HTML to PDF (file upload with optional images)",
            "POST /convert-text": "Convert HTML text to PDF (with optional image files)",
            "POST /convert-with-images": "Convert HTML with multiple images",
            "GET /health": "Health check",
            "GET /docs": "API documentation (Swagger UI)"
        }
    }

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {"status": "healthy", "service": "html-to-pdf-api"}

@app.post("/convert")
async def convert_file(
    file: UploadFile = File(...),
    images: Optional[List[UploadFile]] = File(None),
    aspect_ratio: str = Form(default="9:16")
):
    """
    Convert uploaded HTML file to PDF with optional images
    
    - **file**: HTML file to convert
    - **images**: Optional list of image files (jpg, png, gif, svg, webp)
    - **aspect_ratio**: Page orientation (16:9, 1:1, or 9:16)
    """
    if not file.filename.lower().endswith(('.html', '.htm')):
        raise HTTPException(status_code=400, detail="File must be HTML (.html or .htm)")
    
    if aspect_ratio not in ["16:9", "1:1", "9:16"]:
        raise HTTPException(status_code=400, detail="Invalid aspect ratio. Use: 16:9, 1:1, or 9:16")
    
    temp_dir = None
    try:
        # Create temporary directory
        temp_dir = tempfile.mkdtemp()
        
        # Read HTML content
        content = await file.read()
        try:
            html_content = content.decode('utf-8')
        except UnicodeDecodeError:
            html_content = content.decode('latin-1')
        
        # Process images if provided
        if images:
            image_mapping = save_uploaded_images(images, temp_dir)
            html_content = process_html_with_images(html_content, temp_dir, image_mapping)
        
        # Convert to PDF
        pdf_bytes = convert_html_to_pdf(html_content, aspect_ratio, temp_dir)
        
        # Clean up
        shutil.rmtree(temp_dir, ignore_errors=True)
        
        # Return PDF file
        filename = file.filename.replace('.html', '.pdf').replace('.htm', '.pdf')
        if not filename.endswith('.pdf'):
            filename += '.pdf'
            
        return Response(
            content=pdf_bytes,
            media_type="application/pdf",
            headers={
                "Content-Disposition": f"attachment; filename={filename}"
            }
        )
        
    except Exception as e:
        if temp_dir:
            shutil.rmtree(temp_dir, ignore_errors=True)
        raise HTTPException(status_code=500, detail=f"Conversion failed: {str(e)}")

@app.post("/convert-text")
async def convert_text(
    html: str = Form(...),
    images: Optional[List[UploadFile]] = File(None),
    aspect_ratio: str = Form(default="9:16"),
    return_base64: bool = Form(default=False)
):
    """
    Convert HTML text to PDF with optional images
    
    - **html**: HTML content as string
    - **images**: Optional list of image files
    - **aspect_ratio**: Page orientation (16:9, 1:1, or 9:16)
    - **return_base64**: If true, returns base64 encoded PDF in JSON
    """
    if aspect_ratio not in ["16:9", "1:1", "9:16"]:
        raise HTTPException(status_code=400, detail="Invalid aspect ratio. Use: 16:9, 1:1, or 9:16")
    
    temp_dir = None
    try:
        # Create temporary directory
        temp_dir = tempfile.mkdtemp()
        
        # Process images if provided
        if images:
            image_mapping = save_uploaded_images(images, temp_dir)
            html = process_html_with_images(html, temp_dir, image_mapping)
        
        # Convert to PDF
        pdf_bytes = convert_html_to_pdf(html, aspect_ratio, temp_dir)
        
        # Clean up
        shutil.rmtree(temp_dir, ignore_errors=True)
        
        if return_base64:
            # Return as JSON with base64 encoded PDF
            pdf_base64 = base64.b64encode(pdf_bytes).decode('utf-8')
            return JSONResponse(content={
                "success": True,
                "pdf_base64": pdf_base64,
                "size_bytes": len(pdf_bytes)
            })
        else:
            # Return PDF file directly
            return Response(
                content=pdf_bytes,
                media_type="application/pdf",
                headers={
                    "Content-Disposition": "attachment; filename=converted.pdf"
                }
            )
        
    except Exception as e:
        if temp_dir:
            shutil.rmtree(temp_dir, ignore_errors=True)
        raise HTTPException(status_code=500, detail=f"Conversion failed: {str(e)}")

@app.post("/convert-with-images")
async def convert_with_images(
    html_file: UploadFile = File(...),
    images: List[UploadFile] = File(...),
    aspect_ratio: str = Form(default="9:16")
):
    """
    Convert HTML with multiple images - dedicated endpoint
    
    - **html_file**: HTML file to convert
    - **images**: List of image files (required)
    - **aspect_ratio**: Page orientation (16:9, 1:1, or 9:16)
    """
    if not html_file.filename.lower().endswith(('.html', '.htm')):
        raise HTTPException(status_code=400, detail="HTML file must be .html or .htm")
    
    if aspect_ratio not in ["16:9", "1:1", "9:16"]:
        raise HTTPException(status_code=400, detail="Invalid aspect ratio. Use: 16:9, 1:1, or 9:16")
    
    # Validate image files
    allowed_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.svg', '.webp', '.bmp'}
    for img in images:
        ext = Path(img.filename).suffix.lower()
        if ext not in allowed_extensions:
            raise HTTPException(
                status_code=400, 
                detail=f"Invalid image format: {img.filename}. Allowed: {', '.join(allowed_extensions)}"
            )
    
    temp_dir = None
    try:
        # Create temporary directory
        temp_dir = tempfile.mkdtemp()
        
        # Read HTML content
        content = await html_file.read()
        try:
            html_content = content.decode('utf-8')
        except UnicodeDecodeError:
            html_content = content.decode('latin-1')
        
        # Save and process images
        image_mapping = save_uploaded_images(images, temp_dir)
        html_content = process_html_with_images(html_content, temp_dir, image_mapping)
        
        # Convert to PDF
        pdf_bytes = convert_html_to_pdf(html_content, aspect_ratio, temp_dir)
        
        # Clean up
        shutil.rmtree(temp_dir, ignore_errors=True)
        
        # Return PDF
        filename = html_file.filename.replace('.html', '.pdf').replace('.htm', '.pdf')
        if not filename.endswith('.pdf'):
            filename += '.pdf'
            
        return Response(
            content=pdf_bytes,
            media_type="application/pdf",
            headers={
                "Content-Disposition": f"attachment; filename={filename}",
                "X-Image-Count": str(len(images))
            }
        )
        
    except Exception as e:
        if temp_dir:
            shutil.rmtree(temp_dir, ignore_errors=True)
        raise HTTPException(status_code=500, detail=f"Conversion failed: {str(e)}")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)