如何在Python中将PDF文档从Portrait转为Landscape
解决Django中用pdfkit生成横向PDF的问题
我需要用Python将PDF从纵向(Portrait)转为横向(Landscape),以下是我尝试的Django代码,但没得到预期结果,求解决方案。
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. 问题根源
你的代码未在pdfkit的配置选项中指定页面方向,wkhtmltopdf默认生成纵向PDF,因此无法得到横向效果。
2. 具体修复步骤
(1)添加横向方向配置
在options字典中新增orientation参数,直接指定页面为横向:
options = { 'encoding': 'UTF-8', 'javascript-delay':'10', 'enable-local-file-access': None, 'page-size': 'A4', 'orientation': 'Landscape', # 关键:设置为横向 'custom-header' : [ ('Accept-Encoding', 'gzip') ], }
(2)适配HTML模板布局
在你的PDF模板invoice/pdf-template.html中添加打印专用CSS,确保内容适配A4横向尺寸:
@media print { @page { size: A4 landscape; margin: 1cm; } body { width: 297mm; /* A4横向宽度 */ height: 210mm; /* A4横向高度 */ margin: 0 auto; } }
3. 额外说明
- 无需事后读取PDF判断方向,生成阶段直接指定参数更高效,避免额外的PDF处理开销
- 确保wkhtmltopdf为最新版本,旧版本可能存在参数兼容性问题
- 若使用Bootstrap等框架,可调整栅格布局,利用横向页面的额外宽度优化内容排版
内容的提问来源于stack exchange,提问作者Oluwadamilare Alani
相关产品推荐
相关产品推荐

