Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7187553
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T18:52:18+00:00 2026-05-28T18:52:18+00:00

I’m using django and reportlab tool generate Dynamic PDF reports. All the data in

  • 0

I’m using django and reportlab tool generate Dynamic PDF reports. All the data in report is coming from database.

I’m generating dynamic PDF report using reportlab which consist of the data from database. My problem is whenever I restart Apache server my PDF reports data is changing. The generated report uses Django queries to display the data. But when I restart apache server then the correct data is not appearing in report.

I checked all the queries which I written in my django views. Also I noticed that every restart of Apache server showing different results. So I don’t think so that this is the problem of my django queries. Is there any solution for this problem?

If I restart the apache server data of already generated reports will change, what is the cause for this problem, any solutions?

Or it is due to apache server?

Here is the source code. I think StringIO is wrongly placed.

buffer = StringIO()

def analysis_report(request, sample_no, contact_person):

"""
This function generates the analysis report by using the
client information, transformer details, sample data and
test results of respective analysis.
"""

response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment;filename=ANALYSIS_REPORT.pdf'

doc = SimpleDocTemplate(buffer)

document = []
doc.sample_no = sample_no
doc.contact_person = contact_person

image = Paragraph(stamp_image, STYLES['NORMAL_RIGHT'])

document.append(image)

# BUILTIN FUNCTION TO GENERATE THE DOCUMENT.

doc.build(document, onLaterPages=header_footer)

pdf = buffer.getvalue()

response.write(pdf) 

return response

Thanks in advance

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T18:52:20+00:00Added an answer on May 28, 2026 at 6:52 pm

    Firstly, a huge problem in your case may be that buffer = StringIO() is not in function scope but you use it within your function.

    I’m not sure what exactly you are doing – the code you’ve given us is the tiniest snippet of a whole working PDF – but here are a couple pointers from a guy that just had to do 2 really huge PDF packages for a django project:

    • write a class to create and encapsulate your PDF document object
      • The first PDF doc I wrote kept growing in scope – having all of the logic in the view became too much to manage
      • your class should have a function to build out each of your page templates
      • if your page templates use callbacks onPage= each of those callbacks should also be defined separately in your class
      • each unique section of data should have its own function (in my case: page 1, page 2, and disclosures each got a function because they were logically different chunks of data)

    So here is an example views.py:

    @check_requirments
    def pdf(request) :
        """
        Download a PDF
        """
        response = HttpResponse(mimetype='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=new.pdf'
    
        pdf = MyPdf(response)
        pdf.add_first_page()
        pdf.add_second_page()
        pdf.add_disclosures()
        pdf.build()
    
        return response
    

    And an example of my Pdf Class:

    # Page Setup
    PAGE_WIDTH, PAGE_HEIGHT = landscape(letter)
    
    class MyPdf():
        """
        My PDF
        """
        document            = None
    
        def __init__(self, file_like_handle=None):
            self.document = BaseDocTemplate(file_like_handle, pagesize=landscape(letter))
    
            self.build_templates()
    
        def build_templates(self):
    
            first_page_frames = []
    
            #First Page Title Frame
            frame_title = Frame(.25*inch, PAGE_HEIGHT-(1.75*inch), PAGE_WIDTH-(inch*.5), inch*.5, id="frame_title", showBoundary=0)
            first_page_frames.append(frame_title)
    
            # First Page Body Frames
            frame_body = Frame(.5*inch, PAGE_HEIGHT-(8*inch), PAGE_WIDTH-(inch), inch*6.25, id="frame_body", showBoundary=0)
            first_page_frames.append(frame_body)
    
            # Second Page Body Frame
            frame_body_full = Frame(.5*inch, PAGE_HEIGHT-(8*inch), PAGE_WIDTH-(inch), inch*7, id="frame_body_full", showBoundary=0)
    
            templates = []
            templates.append(PageTemplate(frames=first_page_frames, id="first_page", onPage=self.first_page))
            templates.append(PageTemplate(frames=[frame_body_full], id="child_pages", onPage=self.child_pages))
            templates.append(PageTemplate(frames=[frame_body_full], id="child_pages", onPage=self.last_page))
            self.document.addPageTemplates(templates)
    
    
        def first_page(self, canvas, doc):
            """
            First page has an image header and footer
            """
            canvas.saveState()
            canvas.drawInlineImage(settings.MEDIA_ROOT + "../static/pdf-header-landscape.png", inch*.25, PAGE_HEIGHT-(1.25 * inch), PAGE_WIDTH-(.5*inch), ((11/8)*inch))
            canvas.drawInlineImage(settings.MEDIA_ROOT + "../static/pdf-footer-landscape.png", inch*.25, inch*.25, PAGE_WIDTH-(.5*inch), (.316*inch))
            canvas.restoreState()
    
    
        def child_pages(self, canvas, doc): 
            """
            Second page has a smaller header and the same footer
            """
            canvas.saveState()  
            canvas.setFillColor(HexColor("#f4f3f1"))
            canvas.rect(inch*.25, PAGE_HEIGHT-(.25 * inch), PAGE_WIDTH-(.5*inch), -(.5*inch), fill=1, stroke=0)
            canvas.setFillColor(HexColor("#e5b53b"))
            canvas.setFont('Gotham-Bold', 16)
            canvas.drawString(inch*.5, PAGE_HEIGHT-((.6)*inch), "PAGE")
            canvas.setFillColor(HexColor("#00355f"))
            canvas.drawString(inch*1.75, PAGE_HEIGHT-((.6)*inch), "OVERVIEW")
            canvas.drawInlineImage(settings.MEDIA_ROOT + "../static/pdf-footer-landscape.png", inch*.25, inch*.25, PAGE_WIDTH-(.5*inch), (.316*inch))
            canvas.restoreState()
    
    
        def build(self):
            return self.document.build(self.elements)
    
    
        def add_first_page(self):
    
            sample = getSampleStyleSheet()
            style_title = copy.deepcopy(sample['BodyText'])
            style_title.fontSize = 18
            style_title.textColor = HexColor("#00355f")
    
            style_body  = copy.deepcopy(sample['BodyText'])
            style_body.fontSize = 10
            style_body.alignment = reportlab.lib.enums.TA_LEFT
            style_body.spaceBefore = 25
            style_body.spaceAfter = 15
            style_body.textColor = HexColor("#000000")
            style_body.leading = 14
    
            self.elements.append(Paragraph("""<font color="#e5b53b">PAGE</font>OVERVIEW""", style_title))
            self.elements.append(FrameBreak())
    
            self.elements.append(Paragraph("""Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean elementum malesuada euismod. Praesent ut ante risus. Aenean eleifend massa elit, non adipiscing ipsum. Integer et arcu tortor, a bibendum metus. Maecenas eget nulla id sem placerat dignissim sit amet et ligula. Donec vitae mi mauris. Praesent lacinia, mauris at malesuada bibendum, metus eros molestie ipsum, sed consequat dolor diam interdum ipsum. Phasellus consectetur auctor laoreet. Suspendisse vel nisl lacus, vitae auctor dui.""", style_body))
    
            # ADD A CUSTOM REPORTLAB CANVAS OBJECT
            self.elements.append(SomeGraph())
    
            self.elements.append(Paragraph("""Our strategic allocations for each strategy are determined by our Dynamic Strategic Asset Allocation process - the Science of Dynamic Investing. Our proprietary mathematical model uses updated Price Matters<super>&reg;</super> capital market assumptions (expected return, risk and correlation figures) to determine the optimal allocation to each asset class to achieve the goals of each strategy within the assigned risk tolerance and time horizon. The Art of Dynamic Investing enables us to adapt to changing economic and political realities as we reposition strategies with tactical tilts to the strategic allocations as we see value and momentum of various asset classes being affected during the year. <font color="#e5b53b">The chart below</font> shows the strategic weightings and the tactical allocations to each asset class as of the close of business on the date cited.""", style_body))
    
            self.elements.append(NextPageTemplate("child_pages"))
            self.elements.append(PageBreak())       
    
        def add_second_page(self):
            sample = getSampleStyleSheet()
            style_title = copy.deepcopy(sample['BodyText'])
            style_title.fontSize = 18
            style_title.textColor = HexColor("#00355f")
    
            style_body  = copy.deepcopy(sample['BodyText'])
            style_body.fontSize = 10
            style_body.alignment = reportlab.lib.enums.TA_LEFT
            style_body.spaceBefore = 25
            style_body.spaceAfter = 15
            style_body.textColor = HexColor("#000000")
            style_body.leading = 14
    
            self.elements.append(Paragraph("""Morbi posuere erat non nunc faucibus rhoncus. Donec at ante at tellus vehicula gravida. Praesent vulputate viverra neque, ut consectetur turpis vestibulum at. Integer interdum diam sed leo vehicula in viverra mauris venenatis. Morbi tristique pretium nunc vel ultrices. Fusce vitae augue lorem, et feugiat lorem. Donec sit amet nulla eget elit feugiat euismod rutrum ut magna. Pellentesque condimentum, tellus at rutrum egestas, dui neque dapibus risus, malesuada mollis risus eros id ligula. Fusce id cursus nulla. Etiam porttitor vulputate tellus eu blandit. Donec elementum erat sed tellus dapibus eleifend. Pellentesque sagittis, libero ac sodales laoreet, erat turpis fringilla est, vel accumsan nunc nisi eget orci. Integer condimentum libero in tellus lacinia ultricies quis ac odio. Vivamus justo urna, faucibus vitae bibendum dapibus, condimentum et ligula. Nullam interdum velit at orci blandit nec suscipit lorem lobortis. Pellentesque purus nunc, pulvinar vitae ullamcorper id, rhoncus sit amet diam.""", style_body))
    
        def add_disclosures(self):
    
            sample = getSampleStyleSheet()
            style_d = copy.deepcopy(sample['BodyText'])
            style_d.fontSize        = 8
            style_d.alignment   = reportlab.lib.enums.TA_LEFT
            style_d.textColor   = HexColor("#9D8D85")
    
            self.elements.append(NextPageTemplate("last_page"))
            self.elements.append(PageBreak())
    
            self.elements.append(Paragraph("""Important Disclosures""", style_d))
    
            self.elements.append(Paragraph("""Copyright 2012 Francis Yaconiello All Rights Reserved.""", style_d))
    

    Note: I haven’t tested that class as it is, I basically grabbed a lot of application specific info out of a class that I already had and pared it down for easy digest. It’s meant to give you an idea of how I set up PDFs as a best practice.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm generating some pdf's with Reportlab and Django using a web interface. The pdf's
Using django-social-auth to grab user data from facebook, it is returning a list of
I´m using django to generate a pdf and return the response as an attachment
Using Django 1.1, I am trying to select the maximum value from a varchar
(Using django as an example; the ForeignKey is implicit in the example) >>> from
im using django-registration, all is fine, the confirmation email was sending in plain text,
By using django ORM: How to match the result in database is NOT null?
When using Django sessions , is it good practice to see if session data
I'm using django 1.3 I'm using a base.html template which my pages inherit from.
Using django-contact-form , I have overridden the form class: from contact_form.forms import ContactForm from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.