Itext 7 Split Paragraph

时间:2017-10-23 17:45:55

标签: java itext itext7

如何将给定的段落拆分为2个段落,因为它只适用于画布。拆分后,我想将第一部分添加到画布中,第二部分添加到新画布中。

public Paragraph addParagraphToPage(PdfDocument pdfDocument, int pageNum, Rectangle rectangle, Paragraph p) 
{
    PdfPage page = pdfDocument.getPage(pageNum);        
    PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), pdfDocument);        
    Canvas canvas = new Canvas(pdfCanvas, pdfDocument, rectangle);

    ParagraphRenderer currentRenderer = (ParagraphRenderer) p.createRendererSubTree();      
    currentRenderer.setParent(canvas.getRenderer());    
    result = currentRenderer.layout(new LayoutContext(new LayoutArea(pageNum, rectangle)));

    ArrayList<Paragraph> paragraphs = new ArrayList<Paragraph>();
    if (result.getStatus() != LayoutResult.FULL)
    {           
        paragraphs = ????? // getNextParagraph(paragraphs, result, pageNum, rectangle, canvas);

        if(paragraphs.size() == 2)
        {
            canvas.add( paragraphs.get(0));
            return paragraphs.get(1);
        }
    }
    return null;
}

1 个答案:

答案 0 :(得分:1)

您的方法一般是正确的,iText7中的布局足够灵活,可以让您轻松地完成所需的操作。我唯一看到的不是很清楚的是Paragraph实际上是一个不能自我分裂的元素,布局框架中没有类促进元素拆分。你可以手动完成,但没有必要。相反,您应该直接使用IRendererParagraphRenderer

IRenderer可以作为layout操作的结果进行拆分,仅与包含完整数据的Paragraph相比,代表必要的数据部分。

您可以向IRenderer添加CanvasRenderer

canvas.getRenderer().addChild(rendererToAdd.setParent(canvas.getRenderer()));

您可以从LayoutResult#getSplitRenderer()LayoutResult#getOverflowRenderer()访问部分渲染器(适合传递区域和溢出部分的部分)。

通常,您的代码可以调整如下:

public ParagraphRenderer addParagraphToPage(PdfDocument pdfDocument, int pageNum, Rectangle rectangle, ParagraphRenderer renderer) {
    PdfPage page = pdfDocument.getPage(pageNum);
    PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), pdfDocument);
    Canvas canvas = new Canvas(pdfCanvas, pdfDocument, rectangle);

    renderer.setParent(canvas.getRenderer());
    LayoutResult result = renderer.layout(new LayoutContext(new LayoutArea(pageNum, rectangle)));

    IRenderer rendererToAdd = result.getStatus() == LayoutResult.FULL ? renderer : result.getSplitRenderer();

    canvas.getRenderer().addChild(rendererToAdd.setParent(canvas.getRenderer()));

    return result.getStatus() != LayoutResult.FULL ? (ParagraphRenderer) result.getOverflowRenderer() : null;
}

然后,为了在顺序页面中添加段落,直到放置所有内容,您基本上只需要两行代码:

ParagraphRenderer renderer = (ParagraphRenderer) p.createRendererSubTree();
while ((renderer = addParagraphToPage(pdfDocument, pageNum++, rectangle, renderer)) != null);