Пример #1
0
        private static IList <AttachmentFile> extractDocumentLevelAttachments(PdfReader reader)
        {
            var results = new List <AttachmentFile>();

            var names = PdfReader.GetPdfObject(reader.Catalog.Get(PdfName.Names)) as PdfDictionary;

            if (names == null)
            {
                return(null);
            }

            var files = PdfReader.GetPdfObject(names.Get(PdfName.Embeddedfiles)) as PdfDictionary;

            if (files == null)
            {
                return(null);
            }

            var filesMap = PdfNameTree.ReadTree(files);

            foreach (var item in filesMap.Values)
            {
                var filespec = PdfReader.GetPdfObject((PdfObject)item) as PdfDictionary;
                var file     = extractFile(filespec);
                if (file == null)
                {
                    continue;
                }
                results.Add(file);
            }

            return(results);
        }
Пример #2
0
 public StructIdCellRenderer(Cell c, Document document, PdfString headerId, PdfNameTree idTree) : base(c)
 {
     this.pdfDocument = document.GetPdfDocument();
     this.idTree      = idTree;
     this.tagContext  = pdfDocument.GetTagStructureContext();
     this.headerId    = headerId;
 }
Пример #3
0
        protected int ParseToc()
        {
            _outline = new List <BookItem>();
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(_src_file));

            PdfOutline pdfOutline = pdfDoc.GetOutlines(false);

            PdfNameTree destsTree = pdfDoc.GetCatalog().GetNameTree(PdfName.Dests);

            GetBookmark(pdfOutline, destsTree.GetNames(), pdfDoc);

            pdfDoc.Close();
            return(0);
        }
Пример #4
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            Dictionary <String, PdfString> renamed = new Dictionary <String, PdfString>();

            PdfNameTree nameTree = pdfDoc.GetCatalog().GetNameTree(PdfName.Dests);
            IDictionary <String, PdfObject> names = nameTree.GetNames();
            List <String> keys = new List <string>(names.Keys);

            // Loop over all named destinations and rename its string values with new names
            foreach (String key in keys)
            {
                String newName = "new" + key;

                names.Add(newName, names[key]);
                names.Remove(key);
                renamed.Add(key, new PdfString(newName));
            }

            // Specify that the name tree has been modified
            // This implies that the name tree will be rewritten on close() method.
            nameTree.SetModified();

            PdfDictionary page        = pdfDoc.GetPage(1).GetPdfObject();
            PdfArray      annotations = page.GetAsArray(PdfName.Annots);

            // Loop over all link annotations of the first page and change their destinations.
            for (int i = 0; i < annotations.Size(); i++)
            {
                PdfDictionary annotation = annotations.GetAsDictionary(i);
                PdfDictionary action     = annotation.GetAsDictionary(PdfName.A);
                if (action == null)
                {
                    continue;
                }

                PdfString n = action.GetAsString(PdfName.D);
                if (n != null && renamed.ContainsKey(n.ToString()))
                {
                    action.Put(PdfName.D, renamed[n.ToString()]);
                }
            }

            pdfDoc.Close();
        }
Пример #5
0
        public static List <Bookmark> GetBookmarks(string sourceFile)
        {
            PdfDocument doc = new PdfDocument(new PdfReader(sourceFile));

            PdfNameTree     destsTree = doc.GetCatalog().GetNameTree(PdfName.Dests);
            PdfOutline      outlines  = doc.GetOutlines(false);
            List <Bookmark> bookmarks = new List <Bookmark>();

            if (outlines != null)
            {
                ListBookmarks(outlines, destsTree.GetNames(), doc, bookmarks, 0, Guid.Empty);
            }

            for (int i = 0; i < bookmarks.Count; i++)
            {
                Bookmark mark    = bookmarks[i];
                Bookmark leveled = bookmarks.FirstOrDefault(x
                                                            => x.Level == mark.Level &&
                                                            bookmarks.IndexOf(x) > i &&
                                                            x.ParentId == mark.ParentId);

                if (leveled != null)
                {
                    mark.EndPage = leveled.StartPage - 1;
                }
                else
                {
                    Bookmark levelUp = bookmarks.FirstOrDefault(x => x.Level <mark.Level && bookmarks.IndexOf(x)> i);
                    if (levelUp != null)
                    {
                        mark.EndPage = levelUp.StartPage - 1;
                    }
                    else
                    {
                        mark.EndPage = doc.GetPageNumber(doc.GetLastPage());
                    }
                }
            }

            doc.Close();

            return(bookmarks);
        }
Пример #6
0
 /**
  * Creates the actual annotation and adds different elements to the
  * PdfWriter while doing so.
  * @return  a PdfAnnotation
  */
 virtual public PdfAnnotation CreateAnnotation()
 {
     if (richMediaContent != null)
     {
         if (assetsmap.Count > 0)
         {
             PdfDictionary assets = PdfNameTree.WriteTree(assetsmap, writer);
             richMediaContent.Put(PdfName.ASSETS, writer.AddToBody(assets).IndirectReference);
         }
         if (configurations.Size > 0)
         {
             richMediaContent.Put(PdfName.CONFIGURATION, writer.AddToBody(configurations).IndirectReference);
         }
         if (views.Size > 0)
         {
             richMediaContent.Put(PdfName.VIEWS, writer.AddToBody(views).IndirectReference);
         }
         richMediaContentReference = writer.AddToBody(richMediaContent).IndirectReference;
     }
     writer.AddDeveloperExtension(PdfDeveloperExtension.ADOBE_1_7_EXTENSIONLEVEL3);
     annot.Put(PdfName.RICHMEDIACONTENT, richMediaContentReference);
     annot.Put(PdfName.RICHMEDIASETTINGS, writer.AddToBody(richMediaSettings).IndirectReference);
     return(annot);
 }
Пример #7
0
        /// <summary>Gets the annotation specified by /A and /P entry values.</summary>
        /// <param name="pdfDocument">specifies the corresponding document</param>
        /// <returns>the annotation specified by /A and /P entry value.</returns>
        public virtual PdfFileAttachmentAnnotation GetAnnotation(PdfDocument pdfDocument)
        {
            PdfObject pValue = GetPdfObject().Get(PdfName.P);
            PdfPage   page   = null;

            if (pValue is PdfNumber)
            {
                // zero-based index is used
                page = pdfDocument.GetPage(((PdfNumber)pValue).IntValue() + 1);
            }
            else
            {
                if (pValue is PdfString)
                {
                    PdfNameTree destsTree = pdfDocument.GetCatalog().GetNameTree(PdfName.Dests);
                    IDictionary <String, PdfObject> dests = destsTree.GetNames();
                    PdfArray pdfArray = (PdfArray)dests.Get(((PdfString)pValue).GetValue());
                    if (null != pdfArray)
                    {
                        if (pdfArray.Get(0) is PdfNumber)
                        {
                            page = pdfDocument.GetPage(((PdfNumber)pdfArray.Get(0)).IntValue());
                        }
                        else
                        {
                            page = pdfDocument.GetPage((PdfDictionary)pdfArray.Get(0));
                        }
                    }
                }
            }
            IList <PdfAnnotation> pageAnnotations = null;

            if (null != page)
            {
                pageAnnotations = page.GetAnnotations();
            }
            PdfObject aValue = GetPdfObject().Get(PdfName.A);
            PdfFileAttachmentAnnotation resultAnnotation = null;

            if (null != pageAnnotations)
            {
                if (aValue is PdfNumber)
                {
                    resultAnnotation = (PdfFileAttachmentAnnotation)pageAnnotations[((PdfNumber)aValue).IntValue()];
                }
                else
                {
                    if (aValue is PdfString)
                    {
                        foreach (PdfAnnotation annotation in pageAnnotations)
                        {
                            if (aValue.Equals(annotation.GetName()))
                            {
                                resultAnnotation = (PdfFileAttachmentAnnotation)annotation;
                                break;
                            }
                        }
                    }
                }
            }
            if (null == resultAnnotation)
            {
                ILog logger = LogManager.GetLogger(typeof(iText.Kernel.Pdf.Action.PdfTarget));
                logger.Error(iText.IO.LogMessageConstant.SOME_TARGET_FIELDS_ARE_NOT_SET_OR_INCORRECT);
            }
            return(resultAnnotation);
        }
Пример #8
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(dest));

            pdfDocument.SetTagged();

            Document doc = new Document(pdfDocument);

            Table table = new Table(UnitValue.CreatePercentArray(3)).UseAllAvailableWidth();

            // Initialize ID strings beforehand. Every ID should be unique across the document
            PdfString[] headersId =
            {
                // Since '/ID' is a `byte string` according to specification we are not passing
                // encoding to the constructor of the PdfString
                new PdfString("header_id_0"), new PdfString("header_id_1"), new PdfString("header_id_2")
            };

            PdfName     idTreeName = new PdfName("IDTree");
            PdfNameTree idTree     = new PdfNameTree(pdfDocument.GetCatalog(), idTreeName);

            for (int i = 0; i < 3; ++i)
            {
                Cell c = new Cell().Add(new Paragraph("Header " + (i + 1)));
                c.GetAccessibilityProperties().SetRole(StandardRoles.TH);
                table.AddHeaderCell(c);
                PdfString headerId = headersId[i];

                // Use custom renderer for cell header element in order to add ID to its tag
                CellRenderer renderer = new StructIdCellRenderer(c, doc, headerId, idTree);
                c.SetNextRenderer(renderer);
            }

            List <TaggingHintKey> colSpanHints = new List <TaggingHintKey>();

            for (int i = 0; i < 4; i++)
            {
                Cell c;
                if (i < 3)
                {
                    c = new Cell().Add(new Paragraph((i + 1).ToString()));
                }
                else
                {
                    // Colspan creation
                    c = new Cell(1, 3).Add(new Paragraph((i + 1).ToString()));
                }

                if (i < 3)
                {
                    // Correct table tagging requires marking which headers correspond to the given cell.
                    // The correspondence is defined by header cells tags IDs. For table cells without
                    // col/row spans it's easy to reference a header: just add proper
                    // PdfStructureAttributes to it. Table cells with col spans are processed below.
                    PdfStructureAttributes tableAttributes = new PdfStructureAttributes("Table");
                    PdfArray headers;
                    headers = new PdfArray(headersId[i % headersId.Length]);
                    tableAttributes.GetPdfObject().Put(PdfName.Headers, headers);
                    c.GetAccessibilityProperties().AddAttributes(tableAttributes);
                }
                else
                {
                    // When we add PdfStructureAttributes to the element these attributes override any
                    // attributes generated for it automatically. E.g. cells with colspan require properly
                    // generated attributes which describe the colspan (e.g. which columns this cell spans).
                    // So here we will use a different approach: fetch the tag which will be created for
                    // the cell and modify attributes object directly.
                    TaggingHintKey colSpanCellHint = LayoutTaggingHelper.GetOrCreateHintKey(c);
                    colSpanHints.Add(colSpanCellHint);
                }

                table.AddCell(c);
            }

            doc.Add(table);

            // After table has been drawn on the page, we can modify the colspan cells tags
            foreach (TaggingHintKey colSpanHint in colSpanHints)
            {
                WaitingTagsManager waitingTagsManager = pdfDocument.GetTagStructureContext().GetWaitingTagsManager();
                TagTreePointer     p = new TagTreePointer(pdfDocument);

                // Move tag pointer to the colspan cell using its hint
                if (!waitingTagsManager.TryMovePointerToWaitingTag(p, colSpanHint))
                {
                    // It is not expected to happen ever if immediate-flush is enabled (which is by default),
                    // otherwise this should be done after the flush
                    throw new InvalidOperationException("A work-around does not work. A tag for the cell is " +
                                                        "not created or cannot be found.");
                }

                foreach (PdfStructureAttributes attr in p.GetProperties().GetAttributesList())
                {
                    if ("Table".Equals(attr.GetAttributeAsEnum("O")))
                    {
                        // Specify all the headers for the column spanning (all of 3)
                        PdfArray headers = new PdfArray(headersId);
                        attr.GetPdfObject().Put(PdfName.Headers, headers);
                        break;
                    }
                }
            }

            pdfDocument.GetStructTreeRoot().GetPdfObject().Put(idTreeName, idTree.BuildTree()
                                                               .MakeIndirect(pdfDocument));

            doc.Close();
        }