Search code examples
c#itext7accessible

Add titles as H1 in accessible pdf using iText 7 and C#


In iText5, we can use chapter and section to add titles and bookmarks.
Then title will displayed as H1 tag in accessible PDF.
How I can do this in iText7?


Solution

  • In iText7, you'd do it like this:

    @Test
    public void run() throws IOException {
    
        File outputFile = getOutputFile();
    
        PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outputFile));
        pdfDocument.setTagged();
    
        Document layoutDocument = new Document(pdfDocument);
    
        Paragraph para = new Paragraph("The Raven")
                            .setFontColor(new DeviceRgb(8, 73, 117))
                            .setFontSize(20f);
                            para.getAccessibilityProperties().setRole(StandardRoles.H1);
        layoutDocument.add(para);
    
        layoutDocument.add(new Paragraph("Once upon a midnight dreary\nWhile I pondered weak and weary\nOver many a quaint and curious volume\nOf forgotten lore"));
    
        pdfDocument.close();
    
        Desktop.getDesktop().open(outputFile);
    }
    

    Checking the tags with Adobe Reader verifies the correct tagging has been applied.

    enter image description here