Getting error Proxy error(InvalidOperationException): The license is not valid for this product
#!/usr/bin/env python3
"""
HTML to PDF Converter Using Official Documentation Pattern
Based on official Aspose.HTML Python documentation imports
"""
import os
import time
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List, Optional
# Use OFFICIAL DOCUMENTATION PATTERN - explicit imports
import aspose.html as ah
import aspose.html.converters as conv
import aspose.html.saving as sav
print("β
Using official documentation import pattern")
class OfficialPatternConverter:
"""HTML to PDF converter using official documentation pattern"""
def __init__(self):
"""Initialize using official documentation pattern"""
self._setup_license_official_pattern()
def _setup_license_official_pattern(self):
"""Setup license using OFFICIAL DOCUMENTATION PATTERN"""
license_filename = "Aspose.TotalforPythonvia.NET.lic"
print(f"π§ Testing OFFICIAL DOCUMENTATION pattern...")
print(f"π License file: {license_filename}")
print(f"π Import pattern: import aspose.html as ah")
try:
# Use OFFICIAL DOCUMENTATION namespace pattern
license = ah.License() # ah.License instead of License()
license.set_license(license_filename)
print("π SUCCESS: Official documentation pattern worked!")
print("β
License loaded using ah.License() namespace")
return True
except Exception as e:
print(f"β Official pattern failed: {str(e)[:80]}")
print("π Running in evaluation mode")
return False
def convert_single_file(self, html_file: str, pdf_file: str) -> bool:
"""Convert single HTML file using official pattern"""
try:
# Use OFFICIAL DOCUMENTATION pattern exactly
document = ah.HTMLDocument(html_file)
options = sav.PdfSaveOptions()
conv.Converter.convert_html(document, options, pdf_file)
# Cleanup
document.dispose()
return True
except Exception as e:
print(f"β Conversion failed: {e}")
return False
def convert_folder(self, input_folder: str, output_folder: str) -> dict:
"""Convert all HTML files using official pattern"""
print(f"\nπ Converting using OFFICIAL DOCUMENTATION pattern...")
print(f"π Input: {input_folder}")
print(f"π Output: {output_folder}")
# Find HTML files
html_files = []
for ext in ['*.html', '*.htm', '*.xhtml']:
html_files.extend(Path(input_folder).glob(ext))
if not html_files:
return {'success': False, 'message': 'No HTML files found'}
print(f"π Found {len(html_files)} HTML files")
# Create output directory
Path(output_folder).mkdir(parents=True, exist_ok=True)
# Convert files
start_time = time.time()
successful = 0
failed = 0
for i, html_file in enumerate(html_files, 1):
pdf_file = Path(output_folder) / f"{html_file.stem}.pdf"
print(f"π [{i}/{len(html_files)}] Converting {html_file.name}...")
if self.convert_single_file(str(html_file), str(pdf_file)):
file_size = pdf_file.stat().st_size / (1024 * 1024) if pdf_file.exists() else 0
print(f" β
Success β {file_size:.1f}MB")
successful += 1
else:
print(f" β Failed")
failed += 1
total_time = time.time() - start_time
print(f"\nπ OFFICIAL PATTERN RESULTS:")
print(f" β
Successful: {successful}")
print(f" β Failed: {failed}")
print(f" β±οΈ Total time: {total_time:.2f}s")
print(f" π Rate: {successful/total_time:.2f} files/second")
return {
'success': True,
'total_files': len(html_files),
'successful': successful,
'failed': failed,
'total_time': total_time
}
def create_test_html():
"""Create test HTML file"""
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Official Pattern Test</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
.header { background: #4CAF50; color: white; padding: 20px; text-align: center; }
.content { padding: 20px; }
.success { background: #d4edda; border: 1px solid #c3e6cb; padding: 15px; margin: 10px 0; }
</style>
</head>
<body>
<div class="header">
<h1>Official Documentation Pattern Test</h1>
<p>Testing explicit imports from Aspose.HTML documentation</p>
</div>
<div class="content">
<div class="success">
<h3>Import Pattern Used:</h3>
<code>
import aspose.html as ah<br>
import aspose.html.converters as conv<br>
import aspose.html.saving as sav
</code>
</div>
<h3>License Test Results:</h3>
<p>If this PDF has <strong>no watermarks</strong>, the official documentation pattern successfully resolved the license issue!</p>
<h3>Technical Details:</h3>
<ul>
<li>License Class: ah.License() (explicit namespace)</li>
<li>HTML Document: ah.HTMLDocument()</li>
<li>PDF Options: sav.PdfSaveOptions()</li>
<li>Converter: conv.Converter.convert_html()</li>
</ul>
<p><strong>Generated:</strong> """ + time.strftime('%Y-%m-%d %H:%M:%S') + """</p>
</div>
</body>
</html>
"""
test_folder = Path("official_test")
test_folder.mkdir(exist_ok=True)
test_file = test_folder / "official_pattern_test.html"
test_file.write_text(html_content, encoding='utf-8')
print(f"β
Created test file: {test_file}")
return test_folder
def main():
"""Test official documentation pattern"""
print("π OFFICIAL DOCUMENTATION PATTERN TESTER")
print("=" * 60)
print("π Import pattern from: https://docs.aspose.com/html/python-net/")
print("π§ Using explicit imports instead of wildcard imports")
# Check license file
license_file = "Aspose.TotalforPythonvia.NET.lic"
if not Path(license_file).exists():
print(f"β οΈ License file not found: {license_file}")
print("π Copy license to current directory")
else:
print(f"β
License file found: {license_file}")
try:
# Create test files
test_folder = create_test_html()
# Initialize converter with official pattern
converter = OfficialPatternConverter()
# Convert using official pattern
result = converter.convert_folder(str(test_folder), "official_output")
if result['success']:
print(f"\nπ OFFICIAL PATTERN TEST COMPLETE!")
print(f"π Check 'official_output' folder for results")
print(f"π Examine PDFs for watermarks - if none, the official pattern worked!")
except Exception as e:
print(f"β Error: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()