Funtion to convert html file into pdf
@api_view(['POST'])
def create_pdf_api(request):
serializer = PDFDataSerializer(data=request.data)
if serializer.is_valid():
data = serializer.validated_data
patient_name = data.get('name', 'patient')
# Render the HTML template
html_string = render_to_string('api/pdf_template.html', data)
# Parse the HTML and replace static file paths
soup = BeautifulSoup(html_string, 'html.parser')
for img in soup.find_all('img'):
if img.attrs.get('src', '').startswith('/static/'):
img['src'] = './static/' + img['src'].split('/static/')[1]
for div in soup.find_all('div'):
style = div.attrs.get('style', '')
if 'background-image' in style:
start_index = style.find('url(') + 4
end_index = style.find(')', start_index)
static_path = style[start_index:end_index].strip("'"")
if static_path.startswith('/static/'):
new_path = './static/' + static_path.split('/static/')[1]
div['style'] = style[:start_index] + new_path + style[end_index:]
# Write to temporary HTML file
html_string = str(soup)
html_file_path = os.path.join(settings.BASE_DIR, 'temp.html')
with open(html_file_path, 'w') as html_file:
html_file.write(html_string)
# Ensure the PDFs directory exists
pdf_dir = os.path.join(settings.BASE_DIR, 'pdfs')
if not os.path.exists(pdf_dir):
os.makedirs(pdf_dir)
# Convert HTML to PDF using pyhtml2pdf
pdf_filename = f"{patient_name.replace(' ', '_')}_report.pdf"
pdf_file_path = os.path.join(pdf_dir, pdf_filename)
converter.convert(f'file:///{html_file_path}', pdf_file_path)
# Upload PDF to Google Drive
credentials_file = os.path.join(settings.BASE_DIR, 'credentials.json')
file_id = upload_to_google_drive(pdf_file_path, credentials_file)
# Grant permission to Gmail account to view the file
gmail_email = '[email protected]' # Replace with your Gmail email
grant_drive_permission(file_id, gmail_email, credentials_file)
# Serve the PDF as a response
with open(pdf_file_path, 'rb') as pdf_file:
response = HttpResponse(pdf_file.read(), content_type='application/pdf')
response['Content-Disposition'] = f'attachment; filename="{pdf_filename}"'
return response
else:
return JsonResponse(serializer.errors, status=400)
Dockerfile
FROM python:3.12-slim
# Install dependencies and Chrome
RUN apt-get update &&
apt-get install -y wget unzip libnss3 libgconf-2-4 libgl1-mesa-glx libfontconfig1 &&
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb &&
apt-get install -y ./google-chrome-stable_current_amd64.deb &&
rm google-chrome-stable_current_amd64.deb
# Install ChromeDriver
RUN CHROME_DRIVER_VERSION=$(wget -qO- https://chromedriver.storage.googleapis.com/LATEST_RELEASE) &&
wget https://chromedriver.storage.googleapis.com/${CHROME_DRIVER_VERSION}/chromedriver_linux64.zip &&
unzip chromedriver_linux64.zip &&
mv chromedriver /usr/local/bin/ &&
chmod +x /usr/local/bin/chromedriver &&
rm chromedriver_linux64.zip
# Set working directory
WORKDIR /app
# Install Python dependencies
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Expose port and start application
EXPOSE 8000
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "myapp.wsgi:application"]
**In this funtion I am trying to convert the html file into pdf and it is working fine on localhost but when I try to hit the api after runing it through docker-compose I am getting error
**
OSError at /api/create_pdf/
[Errno 8] Exec format error: ‘/root/.wdm/drivers/chromedriver/linux64/127.0.6533.72/chromedriver
linux64/THIRD_PARTY_NOTICES.chromedriver’
Harsh Kumar Singh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.