2016-09-21 28 views
1

我有一个Table 2细胞,每一个里面有一个Paragraph溢出隐藏在一个段落在ReportLab的

from reportlab.platypus import Paragraph, Table, TableStyle 
from reportlab.lib.styles import ParagraphStyle 
from reportlab.lib.units import cm 

table_style_footer = TableStyle(
      [ 
       ('LEFTPADDING', (0, 0), (-1, -1), 0), 
       ('RIGHTPADDING', (0, 0), (-1, -1), 0), 
       ('TOPPADDING', (0, 0), (-1, -1), 0), 
       ('BOTTOMPADDING', (0, 0), (-1, -1), 0), 
       ('BOX', (0, 0), (-1, -1), 1, (0, 0, 0)), 
       ('VALIGN', (0, 0), (-1, -1), 'TOP'), 
      ] 
     ) 

style_p_footer = ParagraphStyle('Normal') 
style_p_footer.fontName = 'Arial' 
style_p_footer.fontSize = 8 
style_p_footer.leading = 10 

Table([ 
     [ 
     Paragraph('Send To:', style_p_footer), 
     Paragraph('Here should be a variable with long content', style_p_footer) 
     ] 
     ], 
     [1.7 * cm, 4.8 * cm], 
     style=table_style_footer 
    ) 

我需要隐藏段落的溢出内容,但段落,而不是隐藏溢出内容做一个断线。

回答

2

Reportlab似乎没有隐藏溢出的本机支持,但我们可以通过使用ParagraphbreakLines函数来实现它。 breakLines函数返回一个对象,该对象包含给定一定宽度的段落的所有行,因此我们也可以使用它来查找第一行并放弃其他所有行。

基本上,我们需要做到以下几点:

  1. 创建一个虚拟的段落
  2. 获取的虚拟
  3. 行创建一个基于虚拟
第一线的实际段落

在代码中做到这一点如下所示:

# Create a dummy paragraph to see how it would split 
long_string = 'Here should be a variable with long content'*10 
long_paragraph = Paragraph(long_string, style_p_footer) 

# Needed because of a bug in breakLines (value doesn't matter) 
long_paragraph.width = 4.8 * cm 

# Fetch the lines of the paragraph for the given width 
para_fragment = long_paragraph.breakLines(width=4.8 * cm) 

# There are 2 kinds of returns so 2 ways to grab the first line 
if para_fragment.kind == 0: 
    shorted_text = " ".join(para_fragment.lines[0][1]) 
else: 
    shorted_text = " ".join([w.text for w in para_fragment.lines[0].words]) 

# To make it pretty add ... when we break of the sentence 
if len(para_fragment.lines) > 1: 
    shorted_text += "..." 

# Create the actual paragraph 
shorted_paragraph = Paragraph(shorted_text, style_p_footer) 
+0

完美的作品。我有一个问题,我怎么能'para_fragment.kind'与'0'不同? @ B8vrede –

+0

添加内联分页符将导致它变得友善1 :) – B8vrede

+0

“添加内联分页符”像\ n? :d –