【问题标题】:How can I change the orientation of a .pdf document from Portrait to Landscape in Python如何在 Python 中将 .pdf 文档的方向从纵向更改为横向
【发布时间】:2022-11-17 12:06:08
【问题描述】:

我想使用 Python 将 .pdf 文档的方向从纵向更改为横向。下面是我对此尝试的代码。

解决方案没有给我预期的结果。有人有答案吗?

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

【问题讨论】:

    标签: python


    【解决方案1】:

    使用 pyPDF4,我使用以下方法完成了此操作:

    import PyPDF4
    
    pdfReader = PyPDF4.PdfFileReader(open(source, 'rb'))
    
    for page in range(pdfReader.numPages):
        pageObj = pdfReader.getPage(page)
        pageObj.rotateCounterClockwise(90)
    

    或者可能使用 .rotateClockwise

    这里的诀窍是知道如果你真的有风景或肖像,需要多少。一些 pdf 编写器,除了 mediaBox 之外,还有一个 rotate 属性:

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

    它可以是 90 而不是预期的 0,所以你的 x 和 y 将会出现。祝你好运!

    【讨论】:

      【解决方案2】:

      您可以添加到您的选项以包括

      'orientation': 'Landscape'
      

      这样

      options = {
            'encoding': 'UTF-8',
            'javascript-delay':'10', #Optional
            'enable-local-file-access': None, #To be able to access CSS
            'orientation': 'Landscape'
            'page-size': 'A4',
            'custom-header' : [
                ('Accept-Encoding', 'gzip')
            ],
        }
      

      希望这可以帮助!

      这是我使用的资源:

      https://wkhtmltopdf.org/usage/wkhtmltopdf.txt

      【讨论】:

        猜你喜欢
        • 2020-10-13
        • 1970-01-01
        • 2019-03-30
        • 1970-01-01
        • 2015-01-10
        • 2012-07-21
        • 1970-01-01
        • 1970-01-01
        • 2013-02-27
        相关资源
        最近更新 更多