Ludy.li
Ludy.li

Reputation: 53

IText7> How to add a content of PdfCanvas as PdfName.Figure for PDF/UA Accessibility

I would like to add an element in PdfCanvas, codes as below. Why I can't see the "Figure" in document tag?

PdfCanvas canvas = new PdfCanvas(pdf.addNewPage());
canvas.beginText();
canvas.setFontAndSize(font, 12);
canvas.showText("Test for Accessibility");
canvas.stroke();

PdfDictionary dict = new PdfDictionary();
dict.put(PdfName.Span, new PdfString("Eyes Wide Shut"));      
canvas.beginMarkedContent(PdfName.Figure, dict);
canvas.newlineShowText("EWS");
canvas.endMarkedContent();
canvas.endText();

Upvotes: 1

Views: 711

Answers (1)

Alexey Subach
Alexey Subach

Reputation: 12312

First of all your code is not complete so we don't even know if you call setTagged() on a PdfDocument instance (which is a must for tagging).

But the bigger problem is that beginMarkedContent on its own does not add any connections from the content to the tag tree. The best way to add those connections is use TagTreePointer (if you really want to use low-level PdfCanvas API). You can manipulate tree structure with TagTreePointer and add connections between tree and content with PdfCanvas#openTag.

Also, you seem to be trying to add expansion text (Eyes Wide Shut) with dict.put(PdfName.Span, new PdfString("Eyes Wide Shut"));, but from the PDF syntax point of view this expression does not do anything useful. TagTreePointer's API allows you to set expansion text easily as well.

All in all, the complete code would look like following:

PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFilePath));
pdfDocument.setTagged();

PdfPage firstPage = pdfDocument.addNewPage();

PdfCanvas canvas = new PdfCanvas(firstPage);

TagTreePointer tagPointer = new TagTreePointer(pdfDocument);
tagPointer.setPageForTagging(firstPage);
tagPointer.addTag(StandardRoles.P).addTag(StandardRoles.SPAN);

canvas.beginText()
        .setFontAndSize(PdfFontFactory.createFont(), 12)
        .openTag(tagPointer.getTagReference())
        .showText("Test for Accessibility")
        .closeTag()
        .stroke();

tagPointer.moveToParent().addTag(StandardRoles.SPAN).getProperties().setExpansion("Eyes Wide Shut");
canvas.openTag(tagPointer.getTagReference())
        .newlineShowText("EWS")
        .closeTag()
        .endText();

pdfDocument.close();

The resultant tag structure:

tag structure

Upvotes: 4

Related Questions