Exemple #1
0
        /// <summary>Removes an annotation from the page.</summary>
        /// <remarks>
        /// Removes an annotation from the page.
        /// <br /><br />
        /// NOTE: If document is tagged, PdfDocument's PdfTagStructure instance will point at annotation tag parent after method call.
        /// </remarks>
        /// <param name="annotation">an annotation to be removed.</param>
        /// <returns>this PdfPage instance.</returns>
        public virtual iText.Kernel.Pdf.PdfPage RemoveAnnotation(PdfAnnotation annotation)
        {
            PdfArray annots = GetAnnots(false);

            if (annots != null)
            {
                if (annots.Contains(annotation.GetPdfObject()))
                {
                    annots.Remove(annotation.GetPdfObject());
                }
                else
                {
                    annots.Remove(annotation.GetPdfObject().GetIndirectReference());
                }
                if (annots.IsEmpty())
                {
                    GetPdfObject().Remove(PdfName.Annots);
                }
            }
            if (GetDocument().IsTagged())
            {
                TagTreePointer tagPointer = GetDocument().GetTagStructureContext().RemoveAnnotationTag(annotation);
                if (tagPointer != null)
                {
                    bool standardAnnotTagRole = tagPointer.GetRole().Equals(PdfName.Annot) || tagPointer.GetRole().Equals(PdfName
                                                                                                                          .Form);
                    if (tagPointer.GetKidsRoles().Count == 0 && standardAnnotTagRole)
                    {
                        tagPointer.RemoveTag();
                    }
                }
            }
            return(this);
        }
        public virtual void WriteUtf8ActualText()
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationFolder + "writeUtf8ActualText.pdf"));

            pdfDoc.SetTagged();
            PdfPage        page       = pdfDoc.AddNewPage();
            PdfCanvas      canvas     = new PdfCanvas(page);
            TagTreePointer tagPointer = new TagTreePointer(pdfDoc);

            tagPointer.SetPageForTagging(page);
            tagPointer.AddTag(StandardRoles.DIV);
            tagPointer.AddTag(StandardRoles.SPAN);
            tagPointer.GetContext().GetPointerStructElem(tagPointer).SetActualText(new PdfString("actual", PdfEncodings
                                                                                                 .UTF8));
            canvas.BeginText();
            canvas.MoveText(36, 788);
            canvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN), 12);
            canvas.OpenTag(tagPointer.GetTagReference());
            canvas.ShowText("These piece of text has an actual text property. Can be viewed via properties of span in the tag tree."
                            );
            canvas.CloseTag();
            canvas.EndText();
            pdfDoc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + "writeUtf8ActualText.pdf"
                                                                             , sourceFolder + "cmp_writeUtf8ActualText.pdf", destinationFolder, "diffActualText_"));
        }
        public virtual void TagStructureRemovingTest03()
        {
            PdfWriter writer = new PdfWriter(destinationFolder + "tagStructureRemovingTest03.pdf");

            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfDocument document = new PdfDocument(writer);

            document.SetTagged();
            PdfPage        page       = document.AddNewPage();
            TagTreePointer tagPointer = new TagTreePointer(document);

            tagPointer.SetPageForTagging(page);
            PdfCanvas canvas = new PdfCanvas(page);

            tagPointer.AddTag(PdfName.P);
            IAccessibleElement paragraphElement = tagPointer.GetConnectedElement(true);
            PdfFont            standardFont     = PdfFontFactory.CreateFont(FontConstants.COURIER);

            canvas.BeginText().SetFontAndSize(standardFont, 24).SetTextMatrix(1, 0, 0, 1, 32, 512);
            tagPointer.AddTag(PdfName.Span);
            canvas.OpenTag(tagPointer.GetTagReference()).ShowText("Hello ").CloseTag();
            canvas.SetFontAndSize(standardFont, 30).OpenTag(tagPointer.GetTagReference()).ShowText("World").CloseTag()
            .EndText();
            tagPointer.MoveToParent().MoveToParent();
            document.RemovePage(1);
            PdfPage newPage = document.AddNewPage();

            canvas = new PdfCanvas(newPage);
            tagPointer.SetPageForTagging(newPage);
            tagPointer.MoveToTag(paragraphElement).AddTag(PdfName.Span);
            canvas.OpenTag(tagPointer.GetTagReference()).BeginText().SetFontAndSize(standardFont, 24).SetTextMatrix(1,
                                                                                                                    0, 0, 1, 32, 512).ShowText("Hello.").EndText().CloseTag();
            document.Close();
            CompareResult("tagStructureRemovingTest03.pdf", "cmp_tagStructureRemovingTest03.pdf", "diffRemoving03_");
        }
        public virtual void WriteUtf8AltText()
        {
            String      RESOURCE = sourceFolder + "Space Odyssey.jpg";
            PdfDocument pdfDoc   = new PdfDocument(new PdfWriter(destinationFolder + "writeUtf8AltText.pdf"));

            pdfDoc.SetTagged();
            PdfPage        page       = pdfDoc.AddNewPage();
            PdfCanvas      canvas     = new PdfCanvas(page);
            TagTreePointer tagPointer = new TagTreePointer(pdfDoc);

            tagPointer.SetPageForTagging(page);
            tagPointer.AddTag(StandardRoles.DIV);
            tagPointer.AddTag(StandardRoles.SPAN);
            //  2001: A Space Odyssey (Космическая одиссея)
            tagPointer.GetContext().GetPointerStructElem(tagPointer).SetAlt(new PdfString("2001: A Space Odyssey (\u041A\u043E\u0441\u043C\u0438\u0447\u0435\u0441\u043A\u0430\u044F "
                                                                                          + "\u043E\u0434\u0438\u0441\u0441\u0435\u044F)", PdfEncodings.UTF8));
            ImageData img = ImageDataFactory.Create(RESOURCE);

            canvas.OpenTag(tagPointer.GetTagReference());
            canvas.AddImage(img, 36, 700, 100, false, false);
            canvas.CloseTag();
            canvas.EndText();
            pdfDoc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + "writeUtf8AltText.pdf"
                                                                             , sourceFolder + "cmp_writeUtf8AltText.pdf", destinationFolder, "diffAltText_"));
        }
        public virtual void AccessibleAttributesInsertionTest01()
        {
            PdfReader      reader   = new PdfReader(sourceFolder + "taggedDocumentWithAttributes.pdf");
            PdfWriter      writer   = new PdfWriter(destinationFolder + "accessibleAttributesInsertionTest01.pdf");
            PdfDocument    document = new PdfDocument(reader, writer);
            TagTreePointer pointer  = new TagTreePointer(document);
            // 2 attributes
            AccessibilityProperties properties = pointer.MoveToKid(0).GetProperties();
            PdfStructureAttributes  testAttr   = new PdfStructureAttributes("test");

            testAttr.AddIntAttribute("N", 4);
            properties.AddAttributes(testAttr);
            testAttr = new PdfStructureAttributes("test");
            testAttr.AddIntAttribute("N", 0);
            properties.AddAttributes(0, testAttr);
            testAttr = new PdfStructureAttributes("test");
            testAttr.AddIntAttribute("N", 5);
            properties.AddAttributes(4, testAttr);
            testAttr = new PdfStructureAttributes("test");
            testAttr.AddIntAttribute("N", 2);
            properties.AddAttributes(2, testAttr);
            try {
                properties.AddAttributes(10, testAttr);
                NUnit.Framework.Assert.Fail();
            }
            catch (Exception e) {
                NUnit.Framework.Assert.IsTrue(ExceptionUtil.IsOutOfRange(e));
            }
            document.Close();
            CompareResult("accessibleAttributesInsertionTest01.pdf", "cmp_accessibleAttributesInsertionTest01.pdf", "diffAttributes01_"
                          );
        }
        public virtual void TagStructureFlushingTest01()
        {
            PdfReader reader = new PdfReader(sourceFolder + "taggedDocument.pdf");
            PdfWriter writer = new PdfWriter(destinationFolder + "tagStructureFlushingTest01.pdf");

            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfDocument    document   = new PdfDocument(reader, writer);
            TagTreePointer tagPointer = new TagTreePointer(document);

            tagPointer.MoveToKid(StandardRoles.TABLE).MoveToKid(2, StandardRoles.TR).FlushTag();
            tagPointer.MoveToKid(3, StandardRoles.TR).MoveToKid(StandardRoles.TD).FlushTag();
            tagPointer.MoveToParent().FlushTag();
            String exceptionMessage = null;

            try {
                tagPointer.FlushTag();
            }
            catch (PdfException e) {
                exceptionMessage = e.Message;
            }
            document.Close();
            NUnit.Framework.Assert.AreEqual(PdfException.CannotFlushDocumentRootTagBeforeDocumentIsClosed, exceptionMessage
                                            );
            CompareResult("tagStructureFlushingTest01.pdf", "taggedDocument.pdf", "diffFlushing01_");
        }
        public virtual void TagTreePointerTest06()
        {
            PdfReader reader = new PdfReader(sourceFolder + "taggedDocument.pdf");
            PdfWriter writer = new PdfWriter(destinationFolder + "tagTreePointerTest06.pdf");

            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfDocument    document   = new PdfDocument(reader, writer);
            TagTreePointer tagPointer = new TagTreePointer(document);

            tagPointer.SetRole(PdfName.Part);
            NUnit.Framework.Assert.AreEqual(tagPointer.GetRole().GetValue(), "Part");
            tagPointer.MoveToKid(PdfName.Table).GetProperties().SetLanguage("en-US");
            tagPointer.MoveToKid(PdfName.TR).MoveToKid(PdfName.TD).MoveToKid(PdfName.P);
            String actualText1 = "Some looong latin text";

            tagPointer.GetProperties().SetActualText(actualText1);
            NUnit.Framework.Assert.IsNull(tagPointer.GetConnectedElement(false));
            IAccessibleElement connectedElement = tagPointer.GetConnectedElement(true);

            tagPointer.MoveToRoot().MoveToKid(PdfName.Table).MoveToKid(1, PdfName.TR).GetProperties().SetActualText("More latin text"
                                                                                                                    );
            connectedElement.SetRole(PdfName.Div);
            connectedElement.GetAccessibilityProperties().SetLanguage("en-Us");
            NUnit.Framework.Assert.AreEqual(connectedElement.GetAccessibilityProperties().GetActualText(), actualText1
                                            );
            document.Close();
            CompareResult("tagTreePointerTest06.pdf", "cmp_tagTreePointerTest06.pdf", "diff06_");
        }
        public virtual void TagTreePointerTest02()
        {
            FileStream fos    = new FileStream(destinationFolder + "tagTreePointerTest02.pdf", FileMode.Create);
            PdfWriter  writer = new PdfWriter(fos);

            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfDocument document = new PdfDocument(writer);

            document.SetTagged();
            PdfPage        page       = document.AddNewPage();
            TagTreePointer tagPointer = new TagTreePointer(document);

            tagPointer.SetPageForTagging(page);
            PdfCanvas canvas = new PdfCanvas(page);

            canvas.BeginText();
            PdfFont standardFont = PdfFontFactory.CreateFont(StandardFonts.COURIER);

            canvas.SetFontAndSize(standardFont, 24).SetTextMatrix(1, 0, 0, 1, 32, 512);
            PdfStructureAttributes attributes = new PdfStructureAttributes("random attributes");

            attributes.AddTextAttribute("hello", "world");
            tagPointer.AddTag(StandardRoles.P).AddTag(StandardRoles.SPAN).GetProperties().SetActualText("Actual text for span is: Hello World"
                                                                                                        ).SetLanguage("en-GB").AddAttributes(attributes);
            canvas.OpenTag(tagPointer.GetTagReference()).ShowText("Hello ").CloseTag();
            canvas.SetFontAndSize(standardFont, 30).OpenTag(tagPointer.GetTagReference()).ShowText("World").CloseTag();
            canvas.EndText().Release();
            page.Flush();
            document.Close();
            CompareResult("tagTreePointerTest02.pdf", "cmp_tagTreePointerTest02.pdf", "diff02_");
        }
Exemple #9
0
        public virtual iText.Kernel.Pdf.PdfPage AddAnnotation(int index, PdfAnnotation annotation, bool tagAnnotation
                                                              )
        {
            if (GetDocument().IsTagged() && tagAnnotation)
            {
                TagTreePointer           tagPointer = GetDocument().GetTagStructureContext().GetAutoTaggingPointer();
                iText.Kernel.Pdf.PdfPage prevPage   = tagPointer.GetCurrentPage();
                // TODO what about if current tagging stream is set
                tagPointer.SetPageForTagging(this).AddAnnotationTag(annotation);
                if (prevPage != null)
                {
                    tagPointer.SetPageForTagging(prevPage);
                }
            }
            PdfArray annots = GetAnnots(true);

            if (index == -1)
            {
                annots.Add(annotation.SetPage(this).GetPdfObject());
            }
            else
            {
                annots.Add(index, annotation.SetPage(this).GetPdfObject());
            }
            if (annots.GetIndirectReference() == null)
            {
                SetModified();
            }
            return(this);
        }
        public virtual void TagStructureRemovingTest02()
        {
            PdfReader reader = new PdfReader(sourceFolder + "taggedDocument.pdf");
            PdfWriter writer = new PdfWriter(destinationFolder + "tagStructureRemovingTest02.pdf");

            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfDocument document   = new PdfDocument(reader, writer);
            PdfPage     firstPage  = document.GetPage(1);
            PdfPage     secondPage = document.GetPage(2);

            document.RemovePage(firstPage);
            document.RemovePage(secondPage);
            PdfPage        page       = document.AddNewPage();
            TagTreePointer tagPointer = new TagTreePointer(document);

            tagPointer.SetPageForTagging(page);
            PdfCanvas canvas = new PdfCanvas(page);

            tagPointer.AddTag(StandardRoles.P);
            PdfFont standardFont = PdfFontFactory.CreateFont(StandardFonts.COURIER);

            canvas.BeginText().SetFontAndSize(standardFont, 24).SetTextMatrix(1, 0, 0, 1, 32, 512);
            tagPointer.AddTag(StandardRoles.SPAN);
            canvas.OpenTag(tagPointer.GetTagReference()).ShowText("Hello ").CloseTag();
            canvas.SetFontAndSize(standardFont, 30).OpenTag(tagPointer.GetTagReference()).ShowText("World").CloseTag()
            .EndText();
            document.Close();
            CompareResult("tagStructureRemovingTest02.pdf", "cmp_tagStructureRemovingTest02.pdf", "diffRemoving02_");
        }
        private static IRoleMappingResolver ResolveMappingToStandard(TagTreePointer taggingPointer)
        {
            TagStructureContext tagContext = taggingPointer.GetDocument().GetTagStructureContext();
            PdfNamespace        @namespace = taggingPointer.GetProperties().GetNamespace();

            return(tagContext.ResolveMappingToStandardOrDomainSpecificRole(taggingPointer.GetRole(), @namespace));
        }
Exemple #12
0
            public override void Draw(DrawContext drawContext)
            {
                LayoutTaggingHelper taggingHelper = GetProperty <LayoutTaggingHelper>(Property.TAGGING_HELPER);

                // We want to reach the actual tag from logical structure tree, in order to set custom properties, for
                // which iText doesn't provide convenient API at the moment. Specifically we are aiming at setting /ID
                // entry in structure element dictionary corresponding to the table header cell. Here we are creating tag
                // for the current element in logical structure tree right at the beginning of #draw method.
                // If this particular instance of header cell is paging artifact it would be marked so by layouting
                // engine and it would not allow to create a tag (return value of the method would be 'false').
                // If this particular instance of header cell is the header which is to be tagged, a tag will be created.
                // It's safe to create a tag at this moment, it will be picked up and placed at correct position in the
                // logical structure tree later by layout engine.

                TagTreePointer p = new TagTreePointer(pdfDocument);

                if (taggingHelper.CreateTag(this, p))
                {
                    // After the tag is created, we can fetch low level entity PdfStructElem
                    // in order to work with it directly. These changes would be directly reflected
                    // in the PDF file inner structure.
                    PdfStructElem structElem     = tagContext.GetPointerStructElem(p);
                    PdfDictionary structElemDict = structElem.GetPdfObject();
                    structElemDict.Put(PdfName.ID, headerId);
                    idTree.AddEntry(headerId.GetValue(), structElemDict);
                }

                base.Draw(drawContext);
            }
        public virtual void LangAttrEmptyTagTest()
        {
            String      html        = sourceFolder + "langAttrEmptyTagTest.html";
            String      outFile     = destinationFolder + "langAttrEmptyTagTest.pdf";
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFile));

            pdfDocument.SetTagged();
            HtmlConverter.ConvertToPdf(new FileStream(html, FileMode.Open, FileAccess.Read), pdfDocument, null);
            PrintOutputPdfNameAndDir(outFile);
            PdfDocument    document   = new PdfDocument(new PdfReader(outFile));
            TagTreePointer tagPointer = new TagTreePointer(document);

            tagPointer.MoveToKid(0);
            NUnit.Framework.Assert.AreEqual("", tagPointer.GetProperties().GetLanguage());
            tagPointer.MoveToRoot().MoveToKid(1).MoveToKid(0).MoveToKid(StandardRoles.P);
            NUnit.Framework.Assert.AreEqual("", tagPointer.GetProperties().GetLanguage());
            tagPointer.MoveToRoot().MoveToKid(1).MoveToKid(2).MoveToKid(StandardRoles.P);
            NUnit.Framework.Assert.AreEqual("", tagPointer.GetProperties().GetLanguage());
            tagPointer.MoveToRoot().MoveToKid(2).MoveToKid(0).MoveToKid(StandardRoles.TD);
            NUnit.Framework.Assert.AreEqual("", tagPointer.GetProperties().GetLanguage());
            tagPointer.MoveToRoot().MoveToKid(2).MoveToKid(1).MoveToKid(StandardRoles.TD);
            NUnit.Framework.Assert.AreEqual("", tagPointer.GetProperties().GetLanguage());
            NUnit.Framework.Assert.IsNull(document.GetCatalog().GetLang());
            document.Close();
        }
        public virtual void TagTreePointerTest06()
        {
            PdfReader reader = new PdfReader(sourceFolder + "taggedDocument.pdf");
            PdfWriter writer = new PdfWriter(destinationFolder + "tagTreePointerTest06.pdf");

            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfDocument    document   = new PdfDocument(reader, writer);
            TagTreePointer tagPointer = new TagTreePointer(document);

            tagPointer.SetRole(StandardRoles.PART);
            NUnit.Framework.Assert.AreEqual(tagPointer.GetRole(), "Part");
            tagPointer.MoveToKid(StandardRoles.TABLE).GetProperties().SetLanguage("en-US");
            tagPointer.MoveToKid(StandardRoles.P);
            String actualText1 = "Some looong latin text";

            tagPointer.GetProperties().SetActualText(actualText1);
            WaitingTagsManager waitingTagsManager = document.GetTagStructureContext().GetWaitingTagsManager();
            //        assertNull(waitingTagsManager.getAssociatedObject(tagPointer));
            Object associatedObj = new Object();

            waitingTagsManager.AssignWaitingState(tagPointer, associatedObj);
            tagPointer.MoveToRoot().MoveToKid(StandardRoles.TABLE).MoveToKid(1, StandardRoles.TR).GetProperties().SetActualText
                ("More latin text");
            waitingTagsManager.TryMovePointerToWaitingTag(tagPointer, associatedObj);
            tagPointer.SetRole(StandardRoles.DIV);
            tagPointer.GetProperties().SetLanguage("en-Us");
            NUnit.Framework.Assert.AreEqual(tagPointer.GetProperties().GetActualText(), actualText1);
            document.Close();
            CompareResult("tagTreePointerTest06.pdf", "cmp_tagTreePointerTest06.pdf", "diff06_");
        }
 private static void AddAttributes(String attributeValue, PdfFormField pdfFormField, PdfDocument pdfDocument)
 {
     foreach (PdfWidgetAnnotation widget in pdfFormField.GetWidgets())
     {
         PdfDictionary pdfObject = widget.GetPage().GetPdfObject();
         int           i         = widget.GetPdfObject().GetAsNumber(PdfName.StructParent).IntValue();
         PdfObjRef     objRef    = pdfDocument.GetStructTreeRoot().FindObjRefByStructParentIndex(pdfObject, i);
         if (objRef != null)
         {
             TagTreePointer p = pdfDocument.GetTagStructureContext().CreatePointerForStructElem((PdfStructElem)objRef.GetParent());
             IList <PdfStructureAttributes> attributes = p.GetProperties().GetAttributesList();
             bool printFieldAttrFound = false;
             foreach (PdfStructureAttributes attribute in attributes)
             {
                 if (attribute.GetAttributeAsEnum("O").Equals("PrintField"))
                 {
                     printFieldAttrFound = true;
                     break;
                 }
             }
             if (!printFieldAttrFound)
             {
                 p.GetProperties().AddAttributes(new PdfStructureAttributes("PrintField").AddEnumAttribute("Role", attributeValue));
             }
         }
         else
         {
             Console.Out.WriteLine("The object reference couldn't be found.");
             return;
         }
     }
 }
Exemple #16
0
        public virtual TagTreePointer UseAutoTaggingPointerAndRememberItsPosition(IRenderer renderer)
        {
            TagTreePointer autoTaggingPointer = context.GetAutoTaggingPointer();
            TagTreePointer position           = new TagTreePointer(autoTaggingPointer);

            autoTaggingPointerSavedPosition.Put(renderer, position);
            return(autoTaggingPointer);
        }
        public virtual void TagStructureFlushingTest05()
        {
            PdfWriter writer = new PdfWriter(destinationFolder + "tagStructureFlushingTest05.pdf");

            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfDocument document = new PdfDocument(writer);

            document.SetTagged();
            PdfPage        page1      = document.AddNewPage();
            TagTreePointer tagPointer = new TagTreePointer(document);

            tagPointer.SetPageForTagging(page1);
            PdfCanvas canvas = new PdfCanvas(page1);

            tagPointer.AddTag(StandardRoles.DIV);
            tagPointer.AddTag(StandardRoles.P);
            WaitingTagsManager waitingTagsManager = tagPointer.GetContext().GetWaitingTagsManager();
            Object             pWaitingTagObj     = new Object();

            waitingTagsManager.AssignWaitingState(tagPointer, pWaitingTagObj);
            canvas.BeginText();
            PdfFont standardFont = PdfFontFactory.CreateFont(StandardFonts.COURIER);

            canvas.SetFontAndSize(standardFont, 24).SetTextMatrix(1, 0, 0, 1, 32, 512);
            tagPointer.AddTag(StandardRoles.SPAN);
            canvas.OpenTag(tagPointer.GetTagReference()).ShowText("Hello ").CloseTag();
            canvas.SetFontAndSize(standardFont, 30).OpenTag(tagPointer.GetTagReference()).ShowText("World").CloseTag();
            tagPointer.MoveToParent().MoveToParent();
            // Flushing /Div tag and it's children. /P tag shall not be flushed, as it is has connected paragraphElement
            // object. On removing connection between paragraphElement and /P tag, /P tag shall be flushed.
            // When tag is flushed, tagPointer begins to point to tag's parent. If parent is also flushed - to the root.
            tagPointer.FlushTag();
            waitingTagsManager.TryMovePointerToWaitingTag(tagPointer, pWaitingTagObj);
            tagPointer.AddTag(StandardRoles.SPAN);
            canvas.OpenTag(tagPointer.GetTagReference()).ShowText("Hello ").CloseTag();
            canvas.SetFontAndSize(standardFont, 30).OpenTag(tagPointer.GetTagReference()).ShowText("again").CloseTag();
            waitingTagsManager.RemoveWaitingState(pWaitingTagObj);
            tagPointer.MoveToRoot();
            canvas.EndText().Release();
            PdfPage page2 = document.AddNewPage();

            tagPointer.SetPageForTagging(page2);
            canvas = new PdfCanvas(page2);
            tagPointer.AddTag(StandardRoles.P);
            canvas.BeginText().SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA), 24).SetTextMatrix(1,
                                                                                                                    0, 0, 1, 32, 512);
            tagPointer.AddTag(StandardRoles.SPAN);
            canvas.OpenTag(tagPointer.GetTagReference()).ShowText("Hello ").CloseTag();
            tagPointer.MoveToParent().AddTag(StandardRoles.SPAN);
            canvas.OpenTag(tagPointer.GetTagReference()).ShowText("World").CloseTag();
            canvas.EndText().Release();
            page1.Flush();
            page2.Flush();
            document.Close();
            CompareResult("tagStructureFlushingTest05.pdf", "cmp_tagStructureFlushingTest05.pdf", "diffFlushing05_");
        }
Exemple #18
0
        public virtual void RestoreAutoTaggingPointerPosition(IRenderer renderer)
        {
            TagTreePointer autoTaggingPointer = context.GetAutoTaggingPointer();
            TagTreePointer position           = autoTaggingPointerSavedPosition.JRemove(renderer);

            if (position != null)
            {
                autoTaggingPointer.MoveToPointer(position);
            }
        }
        /// <summary>Draws margin boxes.</summary>
        /// <param name="pageNumber">the page</param>
        /// <param name="pdfDocument">
        /// the
        /// <see cref="iText.Kernel.Pdf.PdfDocument"/>
        /// to which content is written
        /// </param>
        /// <param name="documentRenderer">the document renderer</param>
        private void DrawMarginBoxes(int pageNumber, PdfDocument pdfDocument, DocumentRenderer documentRenderer)
        {
            if (properties.GetResolvedPageMarginBoxes().IsEmpty())
            {
                return;
            }
            PdfPage page = pdfDocument.GetPage(pageNumber);

            foreach (PageMarginBoxContextNode marginBoxContentNode in properties.GetResolvedPageMarginBoxes())
            {
                IElement  curBoxElement = ProcessMarginBoxContent(marginBoxContentNode, pageNumber, context);
                IRenderer renderer      = curBoxElement.CreateRendererSubTree();
                RemoveAreaBreaks(renderer);
                renderer.SetParent(documentRenderer);
                bool isTagged = pdfDocument.IsTagged();
                if (isTagged)
                {
                    LayoutTaggingHelper taggingHelper = renderer.GetProperty <LayoutTaggingHelper>(Property.TAGGING_HELPER);
                    LayoutTaggingHelper.AddTreeHints(taggingHelper, renderer);
                }
                LayoutResult result = renderer.Layout(new LayoutContext(new LayoutArea(pageNumber, marginBoxContentNode.GetPageMarginBoxRectangle
                                                                                           ())));
                IRenderer rendererToDraw = result.GetStatus() == LayoutResult.FULL ? renderer : result.GetSplitRenderer();
                if (rendererToDraw != null)
                {
                    TagTreePointer tagPointer    = null;
                    TagTreePointer backupPointer = null;
                    PdfPage        backupPage    = null;
                    if (isTagged)
                    {
                        tagPointer    = pdfDocument.GetTagStructureContext().GetAutoTaggingPointer();
                        backupPage    = tagPointer.GetCurrentPage();
                        backupPointer = new TagTreePointer(tagPointer);
                        tagPointer.MoveToRoot();
                        tagPointer.SetPageForTagging(page);
                    }
                    rendererToDraw.SetParent(documentRenderer).Draw(new DrawContext(page.GetDocument(), new PdfCanvas(page), isTagged
                                                                                    ));
                    if (isTagged)
                    {
                        tagPointer.SetPageForTagging(backupPage);
                        tagPointer.MoveToPointer(backupPointer);
                    }
                }
                else
                {
                    // marginBoxElements have overflow property set to HIDDEN, therefore it is not expected to neither get
                    // LayoutResult other than FULL nor get no split renderer (result NOTHING) even if result is not FULL
                    ILog logger = LogManager.GetLogger(typeof(iText.Html2pdf.Attach.Impl.Layout.PageContextProcessor));
                    logger.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.PAGE_MARGIN_BOX_CONTENT_CANNOT_BE_DRAWN
                                                          , marginBoxContentNode.GetMarginBoxName()));
                }
            }
        }
        private void ReleaseHint(TaggingHintKey hint, ICollection <TaggingHintKey> hintsToBeHeld, bool checkContextIsFinished
                                 )
        {
            TaggingHintKey         parentHint = parentHints.Get(hint);
            IList <TaggingHintKey> kidsHint   = kidsHints.Get(hint);

            if (checkContextIsFinished && parentHint != null)
            {
                if (IsSomeParentNotFinished(parentHint))
                {
                    return;
                }
            }
            if (checkContextIsFinished && kidsHint != null)
            {
                if (IsSomeKidNotFinished(hint))
                {
                    return;
                }
            }
            if (checkContextIsFinished && hintsToBeHeld != null)
            {
                if (hintsToBeHeld.Contains(hint))
                {
                    return;
                }
            }
            if (parentHint != null)
            {
                RemoveParentHint(hint, parentHint);
            }
            if (kidsHint != null)
            {
                foreach (TaggingHintKey kidHint in kidsHint)
                {
                    parentHints.JRemove(kidHint);
                }
                kidsHints.JRemove(hint);
            }
            TagTreePointer tagPointer = new TagTreePointer(document);

            if (context.GetWaitingTagsManager().TryMovePointerToWaitingTag(tagPointer, hint))
            {
                context.GetWaitingTagsManager().RemoveWaitingState(hint);
                if (immediateFlush)
                {
                    tagPointer.FlushParentsIfAllKidsFlushed();
                }
            }
            else
            {
                context.GetWaitingTagsManager().RemoveWaitingState(hint);
            }
        }
        protected void ManipulatePdf(String src, String dest)
        {
            PdfReader   reader      = new PdfReader(src);
            PdfWriter   writer      = new PdfWriter(dest);
            PdfDocument pdfDocument = new PdfDocument(reader, writer);

            PdfPage   firstPage = pdfDocument.GetFirstPage();
            PdfCanvas canvas    = new PdfCanvas(firstPage);

            // The blue star would be something like logo of our document.
            // So for example we don't want it to be read out loud on every page. To achieve it, we mark it as an Artifact.
            canvas.OpenTag(new CanvasArtifact());
            DrawStar(canvas, 30, 745, ColorConstants.BLUE);
            canvas.CloseTag();

            // The green star we want to be a part of actual content and logical structure of the document.
            // To modify tag structure manually we create TagTreePointer. After creation it points at the root tag.
            TagTreePointer tagPointer = new TagTreePointer(pdfDocument);

            tagPointer.AddTag(StandardRoles.FIGURE);
            tagPointer.GetProperties().SetAlternateDescription("The green star.");

            // It is important to set the page at which new content will be tagged
            tagPointer.SetPageForTagging(firstPage);

            canvas.OpenTag(tagPointer.GetTagReference());
            DrawStar(canvas, 450, 745, ColorConstants.GREEN);
            canvas.CloseTag();

            // We can change the position of the existing tags in the tag structure.
            tagPointer.MoveToParent();
            TagTreePointer newPositionOfStar = new TagTreePointer(pdfDocument);

            newPositionOfStar.MoveToKid(StandardRoles.SECT);
            int indexOfTheGreenStarTag = 2;

            // tagPointer points at the parent of the green star tag
            tagPointer.RelocateKid(indexOfTheGreenStarTag, newPositionOfStar);

            // Using the relocateKid method, we can even change the order of the same parent's kids.
            // This could be used to change for example reading order.

            // Make both tagPointer and newPositionOfStar to point at the same tag
            tagPointer.MoveToRoot().MoveToKid(StandardRoles.SECT);


            // Next added tag to this tag pointer will be added at the 0 position
            newPositionOfStar.SetNextNewKidIndex(0);
            indexOfTheGreenStarTag = 2;
            tagPointer.RelocateKid(indexOfTheGreenStarTag, newPositionOfStar);

            pdfDocument.Close();
        }
Exemple #22
0
        public virtual void AddKidsHint <_T0>(TagTreePointer parentPointer, IEnumerable <_T0> newKids)
            where _T0 : IPropertyContainer
        {
            PdfDictionary       pointerStructElem = context.GetPointerStructElem(parentPointer).GetPdfObject();
            TaggingDummyElement dummy             = existingTagsDummies.Get(pointerStructElem);

            if (dummy == null)
            {
                dummy = new TaggingDummyElement(parentPointer.GetRole());
                existingTagsDummies.Put(pointerStructElem, dummy);
            }
            context.GetWaitingTagsManager().AssignWaitingState(parentPointer, GetOrCreateHintKey(dummy));
            AddKidsHint(dummy, newKids);
        }
        public virtual void ReadUtf8AltText()
        {
            String      filename = sourceFolder + "utf-8-alt-text.pdf";
            PdfDocument pdfDoc   = new PdfDocument(new PdfReader(filename), new PdfWriter(destinationFolder + "whatever"
                                                                                          ));
            TagTreePointer tagTreePointer       = new TagTreePointer(pdfDoc);
            String         alternateDescription = tagTreePointer.MoveToKid(0).MoveToKid(0).MoveToKid(0).GetProperties().GetAlternateDescription
                                                      ();

            pdfDoc.Close();
            //  2001: A Space Odyssey (Космическая одиссея)
            NUnit.Framework.Assert.AreEqual("2001: A Space Odyssey (\u041A\u043E\u0441\u043C\u0438\u0447\u0435\u0441\u043A\u0430\u044F "
                                            + "\u043E\u0434\u0438\u0441\u0441\u0435\u044F)", alternateDescription);
        }
Exemple #24
0
 protected internal virtual void WriteAcroFormFieldLangAttribute(PdfDocument pdfDoc)
 {
     if (pdfDoc.IsTagged())
     {
         TagTreePointer formParentPointer = pdfDoc.GetTagStructureContext().GetAutoTaggingPointer();
         IList <String> kidsRoles         = formParentPointer.GetKidsRoles();
         int            lastFormIndex     = kidsRoles.LastIndexOf(StandardRoles.FORM);
         TagTreePointer formPointer       = formParentPointer.MoveToKid(lastFormIndex);
         if (GetLang() != null)
         {
             formPointer.GetProperties().SetLanguage(GetLang());
         }
         formParentPointer.MoveToParent();
     }
 }
        public virtual void TagTreePointerTest08()
        {
            PdfWriter writer = new PdfWriter(destinationFolder + "tagTreePointerTest08.pdf").SetCompressionLevel(CompressionConstants
                                                                                                                 .NO_COMPRESSION);
            PdfDocument             document   = new PdfDocument(new PdfReader(sourceFolder + "taggedDocument2.pdf"), writer);
            TagTreePointer          pointer    = new TagTreePointer(document);
            AccessibilityProperties properties = pointer.MoveToKid(StandardRoles.DIV).GetProperties();
            String language = properties.GetLanguage();

            NUnit.Framework.Assert.AreEqual("en-Us", language);
            properties.SetLanguage("EN-GB");
            pointer.MoveToRoot().MoveToKid(2, StandardRoles.P).GetProperties().SetRole(StandardRoles.H6);
            document.Close();
            CompareResult("tagTreePointerTest08.pdf", "cmp_tagTreePointerTest08.pdf", "diff08_");
        }
        public virtual void TagTreePointerTest04()
        {
            PdfReader reader = new PdfReader(sourceFolder + "taggedDocument.pdf");
            PdfWriter writer = new PdfWriter(destinationFolder + "tagTreePointerTest04.pdf").SetCompressionLevel(CompressionConstants
                                                                                                                 .NO_COMPRESSION);
            PdfDocument    document   = new PdfDocument(reader, writer);
            TagTreePointer tagPointer = new TagTreePointer(document);

            tagPointer.MoveToKid(PdfName.Table).MoveToKid(2, PdfName.TR);
            tagPointer.RemoveTag();
            tagPointer.MoveToKid(PdfName.TR).MoveToKid(PdfName.TD).MoveToKid(PdfName.P).MoveToKid(PdfName.Span);
            tagPointer.RemoveTag().RemoveTag();
            document.Close();
            CompareResult("tagTreePointerTest04.pdf", "cmp_tagTreePointerTest04.pdf", "diff04_");
        }
Exemple #27
0
        private bool CreateSingleTag(TaggingHintKey hintKey, TagTreePointer tagPointer)
        {
            if (hintKey.IsFinished())
            {
                ILog logger = LogManager.GetLogger(typeof(iText.Layout.Tagging.LayoutTaggingHelper));
                logger.Error(iText.IO.LogMessageConstant.ATTEMPT_TO_CREATE_A_TAG_FOR_FINISHED_HINT);
                return(false);
            }
            if (IsNonAccessibleHint(hintKey))
            {
                // try move pointer to the nearest accessible parent in case any direct content will be
                // tagged with this tagPointer
                TaggingHintKey parentTagHint = GetAccessibleParentHint(hintKey);
                context.GetWaitingTagsManager().TryMovePointerToWaitingTag(tagPointer, parentTagHint);
                return(false);
            }
            WaitingTagsManager waitingTagsManager = context.GetWaitingTagsManager();

            if (!waitingTagsManager.TryMovePointerToWaitingTag(tagPointer, hintKey))
            {
                IAccessibleElement modelElement = hintKey.GetAccessibleElement();
                TaggingHintKey     parentHint   = GetAccessibleParentHint(hintKey);
                int ind = -1;
                if (parentHint != null)
                {
                    // if parent tag hasn't been created yet - it's ok, kid tags will be moved on it's creation
                    if (waitingTagsManager.TryMovePointerToWaitingTag(tagPointer, parentHint))
                    {
                        IList <TaggingHintKey> siblingsHint = GetAccessibleKidsHint(parentHint);
                        int i = siblingsHint.IndexOf(hintKey);
                        ind = GetNearestNextSiblingTagIndex(waitingTagsManager, tagPointer, siblingsHint, i);
                    }
                }
                tagPointer.AddTag(ind, modelElement.GetAccessibilityProperties());
                if (hintKey.GetOverriddenRole() != null)
                {
                    tagPointer.SetRole(hintKey.GetOverriddenRole());
                }
                waitingTagsManager.AssignWaitingState(tagPointer, hintKey);
                IList <TaggingHintKey> kidsHint = GetAccessibleKidsHint(hintKey);
                foreach (TaggingHintKey kidKey in kidsHint)
                {
                    MoveKidTagIfCreated(hintKey, kidKey);
                }
                return(true);
            }
            return(false);
        }
        public virtual void AccessibleAttributesInsertionTest05()
        {
            PdfReader      reader       = new PdfReader(sourceFolder + "taggedDocumentWithAttributes.pdf");
            PdfWriter      writer       = new PdfWriter(destinationFolder + "accessibleAttributesInsertionTest05.pdf");
            PdfDocument    document     = new PdfDocument(reader, writer);
            TagTreePointer pointer      = new TagTreePointer(document);
            PdfDictionary  testAttrDict = new PdfDictionary();

            try {
                // 1 attribute array
                pointer.MoveToKid(1).GetProperties().AddAttributes(5, new PdfStructureAttributes(testAttrDict));
                NUnit.Framework.Assert.Fail();
            }
            catch (Exception e) {
                NUnit.Framework.Assert.IsTrue(ExceptionUtil.IsOutOfRange(e));
            }
            pointer.MoveToRoot();
            try {
                // 3 attributes
                pointer.MoveToKid(2).GetProperties().AddAttributes(5, new PdfStructureAttributes(testAttrDict));
                NUnit.Framework.Assert.Fail();
            }
            catch (Exception e) {
                NUnit.Framework.Assert.IsTrue(ExceptionUtil.IsOutOfRange(e));
            }
            pointer.MoveToRoot();
            try {
                // 1 attribute dictionary
                pointer.MoveToKid(0).MoveToKid(StandardRoles.LI).MoveToKid(StandardRoles.LBODY).GetProperties().AddAttributes
                    (5, new PdfStructureAttributes(testAttrDict));
                NUnit.Framework.Assert.Fail();
            }
            catch (Exception e) {
                NUnit.Framework.Assert.IsTrue(ExceptionUtil.IsOutOfRange(e));
            }
            try {
                // no attributes
                pointer.MoveToKid(StandardRoles.P).MoveToKid(StandardRoles.SPAN).GetProperties().AddAttributes(5, new PdfStructureAttributes
                                                                                                                   (testAttrDict));
                NUnit.Framework.Assert.Fail();
            }
            catch (Exception e) {
                NUnit.Framework.Assert.IsTrue(ExceptionUtil.IsOutOfRange(e));
            }
            document.Close();
            CompareResult("accessibleAttributesInsertionTest05.pdf", "cmp_accessibleAttributesInsertionTest05.pdf", "diffAttributes05_"
                          );
        }
Exemple #29
0
 public override void Draw(DrawContext drawContext)
 {
     base.Draw(drawContext);
     if (!IsFlatten())
     {
         String    value    = GetDefaultValue();
         String    name     = GetModelId();
         UnitValue fontSize = (UnitValue)this.GetPropertyAsUnitValue(Property.FONT_SIZE);
         if (!fontSize.IsPointValue())
         {
             fontSize = UnitValue.CreatePointValue(DEFAULT_FONT_SIZE);
         }
         PdfDocument doc  = drawContext.GetDocument();
         Rectangle   area = GetOccupiedArea().GetBBox().Clone();
         ApplyMargins(area, false);
         PdfPage            page   = doc.GetPage(occupiedArea.GetPageNumber());
         PdfButtonFormField button = PdfFormField.CreatePushButton(doc, area, name, value, doc.GetDefaultFont(), fontSize
                                                                   .GetValue());
         button.GetWidgets()[0].SetHighlightMode(PdfAnnotation.HIGHLIGHT_NONE);
         button.SetBorderWidth(0);
         button.SetBackgroundColor(null);
         TransparentColor color = GetPropertyAsTransparentColor(Property.FONT_COLOR);
         if (color != null)
         {
             button.SetColor(color.GetColor());
         }
         PdfAcroForm forms = PdfAcroForm.GetAcroForm(doc, true);
         //Add fields only if it isn't already added. This can happen on split.
         if (forms.GetField(name) == null)
         {
             forms.AddField(button, page);
         }
         if (doc.IsTagged())
         {
             TagTreePointer formParentPointer = doc.GetTagStructureContext().GetAutoTaggingPointer();
             IList <String> kidsRoles         = formParentPointer.GetKidsRoles();
             int            lastFormIndex     = kidsRoles.LastIndexOf(StandardRoles.FORM);
             TagTreePointer formPointer       = formParentPointer.MoveToKid(lastFormIndex);
             String         lang = this.GetProperty <String>(Html2PdfProperty.FORM_ACCESSIBILITY_LANGUAGE);
             if (lang != null)
             {
                 formPointer.GetProperties().SetLanguage(lang);
             }
             formParentPointer.MoveToParent();
         }
     }
 }
        public virtual void TagTreePointerTest03()
        {
            PdfReader reader = new PdfReader(sourceFolder + "taggedDocument.pdf");
            PdfWriter writer = new PdfWriter(destinationFolder + "tagTreePointerTest03.pdf");

            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfDocument    document   = new PdfDocument(reader, writer);
            TagTreePointer tagPointer = new TagTreePointer(document);

            tagPointer.MoveToKid(StandardRoles.TABLE).MoveToKid(2, StandardRoles.TR);
            TagTreePointer tagPointerCopy = new TagTreePointer(tagPointer);

            tagPointer.RemoveTag();
            // tagPointerCopy now points at removed tag
            String exceptionMessage = null;

            try {
                tagPointerCopy.AddTag(StandardRoles.SPAN);
            }
            catch (PdfException e) {
                exceptionMessage = e.Message;
            }
            NUnit.Framework.Assert.AreEqual(PdfException.TagTreePointerIsInInvalidStateItPointsAtRemovedElementUseMoveToRoot
                                            , exceptionMessage);
            tagPointerCopy.MoveToRoot().MoveToKid(StandardRoles.TABLE);
            tagPointerCopy.MoveToKid(StandardRoles.TR);
            TagTreePointer tagPointerCopyCopy = new TagTreePointer(tagPointerCopy);

            tagPointerCopy.FlushTag();
            // tagPointerCopyCopy now points at flushed tag
            try {
                tagPointerCopyCopy.AddTag(StandardRoles.SPAN);
            }
            catch (PdfException e) {
                exceptionMessage = e.Message;
            }
            NUnit.Framework.Assert.AreEqual(PdfException.TagTreePointerIsInInvalidStateItPointsAtFlushedElementUseMoveToRoot
                                            , exceptionMessage);
            try {
                tagPointerCopy.MoveToKid(0);
            }
            catch (PdfException e) {
                exceptionMessage = e.Message;
            }
            NUnit.Framework.Assert.AreEqual(PdfException.CannotMoveToFlushedKid, exceptionMessage);
            document.Close();
        }