Search code examples
javapdfpdf-generationitextjruby

How to add columnText as an annotation in itext pdf


I'm using columnText to draw html into a pdf through XMLWorkerHelper and it's working great.

The only problem is, the code base I'm working with requires everything to be drawn through stamper.addAnnotation()

I'm not sure how to convert a columnText into something which can be added as an annotation?

Some context: this is used as a way to convert content-editable div in the frontend to pdf elements but must be done through stamper.addAnnotation somehow.

If impossible is there anyway to draw html into PDFAnnotations?

Code that currently uses column text(JRuby):

elementsList = XMLWorkerHelper::parseToElementList(html, css)
@stamper = PdfStamper.new(@reader, output_stream)
canvas = @stamper.getOverContent(page_no)

ct = ColumnText.new(canvas)
ct.setSimpleColumn(rect)
elementsList.each{|element| ct.addElement(element)}
ct.go()

Example code of how annotations are normally appended:

annotation = PdfAnnotation.createFreeText(@stamper.getWiter(), rect, "blah blah", defaultAppearance)
@stamper = PdfStamper.new(@reader, output_stream)
@stamper.addAnnotation(annotation, page_no)

defaultAppearance is of type PdfContentByte so maybe theres a way I can convert the columnText into that? I haven't figured out how to do that exactly.

Any ideas?


Solution

  • Your code is JRuby but as you also have tagged your question , I assume a Java sample will also help you.

    You can add content to an appearance from HTML via a ColumnText object like this:

    String html ="<html><h1>Header</h1><p>A paragraph</p><p>Another Paragraph</p></html>";
    String css = "h1 {color: red;}";
    ElementList elementsList = XMLWorkerHelper.parseToElementList(html, css);
    
    PdfReader reader = new PdfReader(resource);
    PdfStamper stamper = new PdfStamper(reader, result);
    
    Rectangle cropBox = reader.getCropBox(1);
    
    PdfAnnotation annotation = stamper.getWriter().createAnnotation(cropBox, PdfName.FREETEXT);
    PdfAppearance appearance = PdfAppearance.createAppearance(stamper.getWriter(), cropBox.getWidth(), cropBox.getHeight());
    
    ColumnText ct = new ColumnText(appearance);
    ct.setSimpleColumn(new Rectangle(cropBox.getWidth(), cropBox.getHeight()));
    elementsList.forEach(element -> ct.addElement(element));
    ct.go();
    
    annotation.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, appearance);
    stamper.addAnnotation(annotation, 1);
    
    stamper.close();
    reader.close();
    

    (AddAnnotation.java test method testAddAnnotationLikeJasonY)

    For this source document

    source

    the result looks like this

    result

    As you see, you already had nearly all the required buildings bricks...