Search code examples
itextitext7

iText 7: How can I insert diagrams into a `Document`?


I am using iText 7.2.1.

According to the documentation, I can only find elements like Image, Div, List, Paragraph, Table can be inserted into Document.

I want to draw some diagrams and insert it into my document. I need them to be part of my content stream. The existing PdfCanvas or Canvas can not do that. They seems to accept only absolute positions.

Is there a way inserting diagrams in iText 7?


Solution

  • In a comment you clarified

    I want to draw diagrams using PdfCanvas instructions. Is it possible that I don't have to specify absolute position, and the diagram automatically follow the previous paragraph, and next paragraphs automatically follow this diagram. Is SVG the only way to do this?

    You can create your diagram in a PdfFormXObject which has its own coordinate system. PdfCanvas instances can also be constructed for form XObjects.

    Then you can wrap that XObject in an iText Image which in turn you can add to an iText Document to be automatically positioned.

    So for a PdfDocument pdfDocument and a Document document:

    PdfFormXObject xobject = new PdfFormXObject(new Rectangle([... area for your diagram ...]));
    PdfCanvas pdfCanvas = new PdfCanvas(xobject, pdfDocument);
    [... draw diagram on pdfCanvas ...]
    Image image = new Image(xobject);
    document.add(image);