Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pdf is not rendering properly. #264

Open
HardikChhallani opened this issue Oct 6, 2024 · 0 comments
Open

Pdf is not rendering properly. #264

HardikChhallani opened this issue Oct 6, 2024 · 0 comments

Comments

@HardikChhallani
Copy link

Description:

I'm building a Flask application that generates a loan receipt in PDF format using wkhtmltopdf. The left section of the receipt renders properly, but the text in the right section is not displayed.

Steps to Reproduce:

  1. Clone the project repository from [GitHub repository link].
  2. Install the required dependencies (e.g., Flask, wkhtmltopdf, etc.).
  3. Run the Flask application.
  4. Send a JSON request containing receipt data.
  5. The generated PDF will have missing text in the right section.

Expected Behavior:

The entire loan receipt, including both left and right sections, should be rendered correctly in the PDF.

Actual Behavior:

Only the left section of the receipt is rendered in the PDF. The text in the right section is missing.

image

Code Snippets:

index.html:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Loan Slip Book</title>
    <style>
        @page {
            size: A4 landscape;
            margin: 0;
        }
        body {
            font-family: Arial, sans-serif;
            background-color: white;
            margin: 0;
            padding: 0;
            width: 297mm;
            height: 210mm;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .loan-slip {
            width: 280mm;
            height: 80mm;
            background-color: #ffffc0;
            display: flex;
            border: 1px solid #000;
        }
        .section {
            padding: 5mm;
            font-size: 3mm;
            display: flex;
            flex-direction: column;
        }
        .left-section {
            width: 33%;
            border-right: 1px dashed #000;
        }
        .right-section {
            width: 67%;
        }
        .top-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 3mm;
        }
        .header {
            text-align: center;
            font-weight: bold;
            margin-bottom: 3mm;
            font-size: 3.1mm;
        }
        .sub-header {
            text-align: center;
            font-size: 2.5mm;
            margin-bottom: 5mm;
        }
        .field {
            margin-bottom: 5mm;
            display: flex;
        }
        .label {
            min-width: 25mm;
            flex-shrink: 0;
        }
        .value {
            border-bottom: 1px solid #000;
            flex-grow: 1;
            margin-left: 2mm;
        }
        .signature-section {
            display: flex;
            justify-content: space-between;
            margin-top: auto;
            padding-top: 5mm;
        }
        .signature-line {
            width: 30%;
            border-top: 1px solid #000;
            text-align: center;
            padding-top: 1mm;
            font-size: 2.5mm;
        }
    </style>
</head>
<body>
    <div class="loan-slip">
        <div class="section left-section">
            <div class="top-info">
                <div>Account No: {{ account_no }}</div>
                <div>Date: {{ date }}</div>
            </div>
            <div class="header">The Yavatmal Urban Co-operative Bank Ltd., Yavatmal</div>
            <div class="sub-header">Branch {{ branch }}</div>
            <div class="field">
                <span class="label">Rs. (in words):</span>
                <span class="value">{{ amount_words }}</span>
            </div>
            <div class="field">
                <span class="label">Name:</span>
                <span class="value">{{ name }}</span>
            </div>
            <div class="field">
                <span class="label">Hypothecation Loan/Cash Credit A/c</span>
            </div>
            <div class="field">
                <span class="label">Rs:</span>
                <span style="display: inline-block; height: 4mm; border: 1px solid #000; padding: 1mm; width: auto; min-width: 10mm; white-space: nowrap;">{{ amount }}</span>
            </div>
            <div class="field">
                <span class="label">Cheque No:</span>
                <span class="value">{{ cheque_no }}</span>
            </div>
            <div class="signature-section">
                <div class="signature-line">Cashier</div>
                <div class="signature-line">Manager</div>
            </div>
        </div>
        
        <div class="section right-section">
            <div class="top-info">
                <div>Slip No: Sample Slip No</div>
                <div>Account No: Sample Account No</div>
                <div>Date: Sample Date</div>
            </div>
            <div class="header">The Yavatmal Urban Co-operative Bank Ltd., Yavatmal</div>
            <div class="sub-header">Branch Sample Branch</div>
            <div class="field">
                <span class="label">Rs. (in words):</span>
                <span class="value">Sample Amount Words</span>
            </div>
            <div class="field">
                <span class="label">Name:</span>
                <span class="value">Sample Name</span>
            </div>
            <div class="field">
                <span class="label">Hypothecation Loan/Cash Credit A/c</span>
            </div>
            <div class="field">
                <span class="label">Rs:</span>
                <span>Sample Amount</span>
            </div>
            <div class="signature-section">
                <div class="signature-line">Cashier</div>
                <div class="signature-line">Manager</div>
                <div class="signature-line">Depositor's Signature</div>
            </div>
        </div>
        
    </div>
</body>
</html>

app.py:

import pdfkit
import os

# Path to wkhtmltopdf
path_to_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_to_wkhtmltopdf)

options = {
    'page-size': 'A4',
    'margin-top': '0.25in',
    'margin-right': '0.25in',
    'margin-bottom': '0.25in',
    'margin-left': '0.25in',
    'encoding': "UTF-8",
    'no-outline': None
}

def replace_placeholders(template, data):
    for key, value in data.items():
        placeholder = '{{ ' + key + ' }}'
        if placeholder in template:
            print(f"Replacing {placeholder} with {value}")
            template = template.replace(placeholder, str(value))
        else:
            print(f"No placeholder for {key} in the template.")
    return template

def generate_receipts():
    try:
        data = request.json  # Ensure you are receiving JSON data
        if not data or "SAA_DATA" not in data:
            return {'error': 'No JSON data or SAA_DATA key received'}, 400

        # Get the PDF file name from the JSON data
        pdf_file_name = data.get("pdf_file_name", "receipts.pdf")  # Default to 'receipts.pdf' if not provided

        # Create a list to hold all the formatted HTML content
        combined_html = "<style>@media print {.page-break { page-break-before: always; }}</style>"

        # Iterate over the list of receipts
        for index, item in enumerate(data["SAA_DATA"]):
            # Path to the external HTML file
            html_file = r'templates\shantinath_agro_agencies_loan_receipt.html'

            # Ensure the HTML file exists
            if not os.path.exists(html_file):
                return {'error': 'HTML template file not found'}, 404

            # Read the HTML content from the file
            with open(html_file, 'r', encoding='utf-8') as f:
                html_content = f.read()

            # Replace placeholders in the HTML with data from the JSON request
            html_formatted = replace_placeholders(html_content, item)

            # Append the formatted HTML and a page break
            combined_html +=  html_formatted
            # combined_html += "<br> <br>"
            # combined_html +=  html_formatted
            if index < len(data["SAA_DATA"]) - 1:
                combined_html += '<div class="page-break"></div>'
            
        #temp 
        with open("debug.html", "w", encoding="utf-8") as debug_file:
            debug_file.write(combined_html)

        # Generate PDF from the combined HTML content
        pdf_file_path = pdf_file_name  # Use the name provided in the JSON
        pdfkit.from_string(combined_html, pdf_file_path, configuration=config, options=options)

        # Send the combined PDF file as a response
        return send_file(pdf_file_path, as_attachment=True, download_name=pdf_file_name, mimetype='application/pdf')

    except Exception as e:
        return {'error': str(e)}, 400

Other Relevant Files:

  • Include any additional files (e.g., templates, static files) that are relevant to the PDF generation process.

Additional Information:

  • Mention the version of wkhtmltopdf you're using.
  • Include a screenshot (if possible) of the generated PDF highlighting the missing text.

Here are some additional questions that might help diagnose the issue:

  • HTML Structure: Is there any difference in the HTML structure between the left and right sections that might affect rendering?
  • CSS Classes: Are the CSS classes applied to the elements in the right section correct?
  • Data Sample: Can you provide a sample JSON object with some example data for the receipt fields? This can help verify if the data is being passed correctly to the template.

By including all the necessary code files and additional information, you'll provide developers with a comprehensive understanding of the problem and increase the chances of resolving it quickly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant