How can I change the orientation of a .pdf document from Portrait to Landscape in Python

Viewed 54

I want to change the orientation of a .pdf document from Portrait to Landscape using Python. Below is the code for my attempt on this.

The solution is not giving me the expected result. Anyone with an answer?

def viewDocumentInvoice(request, slug):
    #fetch that invoice
    try:
        invoice = Invoice.objects.get(slug=slug)
        pass
    except:
        messages.error(request, 'Something went wrong')
        return redirect('invoices')

    #fetch all the products - related to this invoice
    products = Product.objects.filter(invoice=invoice)

    #Get Client Settings
    p_settings = Settings.objects.get(clientName='Kamrate Nigeria Limited')

    #Calculate the Invoice Total
    invoiceTotal = 0.0
    if len(products) > 0:
        for x in products:
            y = float(x.quantity) * float(x.price)
            invoiceTotal += y

    context = {}
    context['invoice'] = invoice
    context['products'] = products
    context['p_settings'] = p_settings
    context['invoiceTotal'] = "{:.2f}".format(invoiceTotal)
    # context['y'] = "{:.2f}".format(y)

    #The name of your PDF file
    filename = '{}.pdf'.format(invoice.uniqueId)  

    #HTML FIle to be converted to PDF - inside your Django directory
    template = get_template('invoice/pdf-template.html')

    #Render the HTML
    html = template.render(context)

    #Options - Very Important [Don't forget this]
    options = {
          'encoding': 'UTF-8',
          'javascript-delay':'10', #Optional
          'enable-local-file-access': None, #To be able to access CSS
          'page-size': 'A4',
          'custom-header' : [
              ('Accept-Encoding', 'gzip')
          ],
      }
      #Javascript delay is optional

    #Remember that location to wkhtmltopdf
    #config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf')
    config = pdfkit.configuration(wkhtmltopdf='C:\Program Files\wkhtmltopdf/bin\wkhtmltopdf.exe')

    #IF you have CSS to add to template
    css1 = os.path.join(settings.CSS_LOCATION, 'assets', 'css', 'bootstrap.min.css')
    css2 = os.path.join(settings.CSS_LOCATION, 'assets', 'css', 'dashboard.css')

    #Create the file
    file_content = pdfkit.from_string(html, False, configuration=config, options=options)

    # pdf = PdfFileReader(file_content)
    # page = pdf.getPage(0).mediaBox
    # if page.getUpperRight_x() - page.getUpperLeft_x() > page.getUpperRight_y() - page.getLowerRight_y():
    #     print('Landscape')
    # else:
    #     print('Portrait')

    #Create the HTTP Response
    response = HttpResponse(file_content, content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename = {}'.format(filename)

    #Return
    return response
1 Answers

Using pyPDF4, I have done this using:

import PyPDF4

pdfReader = PyPDF4.PdfFileReader(open(source, 'rb'))

for page in range(pdfReader.numPages):
    pageObj = pdfReader.getPage(page)
    pageObj.rotateCounterClockwise(90)

or possibly use .rotateClockwise

The trick here is to know how much to if you really have landscape or portrait. Some pdf writers, in addition to the mediaBox, have a rotate property:

pdfReader.getPage(page).get('/Rotate')

which can be 90 instead of the expected 0 so your x and y will be out. Good luck!

Related