Ejemplo n.º 1
0
        public static IEnumerable <BookMarkItem> GetBookMarks(byte[] pdfData)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                SimpleBookmark.ExportToXML(SimpleBookmark.GetBookmark(new PdfReader(new RandomAccessFileOrArray(pdfData), null)), ms, "UTF-8", false);
                ms.Position = 0;
                var sl = new List <BookMarkItem>();



                using (XmlReader xr = XmlReader.Create(ms))
                {
                    xr.MoveToContent();
                    string page   = null;
                    string action = null;
                    string text   = null;
                    var    re     = new Regex(@"(^\d+).(\D*\d*\D*\d*.\d*\W\d*)");

                    while (xr.Read())
                    {
                        //Filter by the nodes with depth 1 to remove the report name from toc
                        if (xr.NodeType == XmlNodeType.Element && xr.Name == "Title" && xr.IsStartElement() && xr.Depth != 1)
                        {
                            // extract page number from 'Page' attribute
                            if (xr.GetAttribute("Page") != null)
                            {
                                var parts = re.Match(xr.GetAttribute("Page"));
                                page   = parts.Groups[1].Value;
                                action = parts.Groups[2].Value;
                            }


                            xr.Read();

                            if (xr.NodeType == XmlNodeType.Text)
                            {
                                text = xr.Value.Trim();

                                if (text != null && page != null)
                                {
                                    sl.Add(new BookMarkItem
                                    {
                                        Page   = Convert.ToInt32(page),
                                        Title  = text,
                                        Level  = xr.Depth - 3,
                                        Action = action
                                    });
                                }
                            }
                        }
                    }

                    return(sl);
                }
            }
        }
Ejemplo n.º 2
0
// ---------------------------------------------------------------------------

        /**
         * Creates an XML file with the bookmarks of a PDF file
         * @param pdfIn the byte array with the document
         */
        public string CreateXml(byte[] pdfIn)
        {
            PdfReader reader = new PdfReader(pdfIn);
            var       list   = SimpleBookmark.GetBookmark(reader);

            using (MemoryStream ms = new MemoryStream()) {
                SimpleBookmark.ExportToXML(list, ms, "ISO8859-1", true);
                ms.Position = 0;
                using (StreamReader sr = new StreamReader(ms)) {
                    return(sr.ReadToEnd());
                }
            }
        }
Ejemplo n.º 3
0
        private static IEnumerable <Bookmark> GetPdfBookmark(FileInfo docFile, bool diagrama = false, string tituloDiagrama = null)
        {
            var listBookmarks = new List <Bookmark>();

            if (diagrama)
            {
                listBookmarks.Add(new Bookmark //default primeiro bookmark é o nome do próprio documento
                {
                    Title       = tituloDiagrama.ToLower().IndexOf("diagrama") > -1 ? tituloDiagrama : $"Diagrama {tituloDiagrama}",
                    PathAndPage = $"{docFile.FullName}"
                });
                return(listBookmarks);
            }
            else
            {
                listBookmarks.Add(new Bookmark //default primeiro bookmark é o nome do próprio documento
                {
                    Title       = docFile.Name,
                    PathAndPage = $"{docFile.FullName}"
                });
            }

            PdfReader reader = new PdfReader(docFile.FullName);
            IList <Dictionary <string, object> > bookmarks = SimpleBookmark.GetBookmark(reader);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                SimpleBookmark.ExportToXML(bookmarks, memoryStream, "ISO8859-1", true);
                XDocument xml = XDocument.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
                foreach (var node in xml.Descendants("Title"))
                {
                    string Title = node.HasElements == true?node.FirstNode.ToString() : (string)node;

                    string Page = (string)node.Attribute("Page");
                    listBookmarks.Add(new Bookmark
                    {
                        Title       = Title.TrimEnd('\r', '\n', ' '),
                        PathAndPage = $"{docFile.FullName}#page={Page.Split(' ')[0]}"
                    });
                }
                //File.WriteAllBytes(docFile.FullName.Replace(".pdf", ".xml"), memoryStream.ToArray());
            }
            return(listBookmarks);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Generate PDF To Content
        /// </summary>
        /// <param name="content"></param>
        /// <param name="html"></param>
        /// <returns></returns>
        public byte[] GeneratePDFTOCContent(byte[] content, string html)
        {
            var reader = new PdfReader(content);
            var sb     = new StringBuilder();

            // Title of PDF
            sb.Append("<h2><strong style='text-align:center'>Demo for Load More Button in Kendo UI Grid</strong></h2><br>");

            // Begin to create TOC
            sb.Append("<table>");
            sb.Append(string.Format("<tr><td width='80%'><strong>{0}</strong></td><td align='right' width='10%'><strong>{1}</strong></td></tr>", "Section", "Page"));
            using (var ms = new MemoryStream())
            {
                // XML document generated by iText
                SimpleBookmark.ExportToXML(SimpleBookmark.GetBookmark(reader), ms, "UTF-8", false);

                // rewind to create xmlreader
                ms.Position = 0;
                using (var xr = XmlReader.Create(ms))
                {
                    xr.MoveToContent();

                    const string format = @"<tr><td width='80%'>{0}</td><td align='right' width='10%'>{1}</td></tr>";

                    // extract page number from 'Page' attribute
                    var re = new Regex(@"^\d+");
                    while (xr.Read())
                    {
                        if (xr.NodeType != XmlNodeType.Element || xr.Name != "Title" || !xr.IsStartElement())
                        {
                            continue;
                        }

                        var page = re.Match(xr.GetAttribute("Page")).Captures[0].Value;
                        xr.Read();

                        if (xr.NodeType != XmlNodeType.Text)
                        {
                            continue;
                        }

                        var text        = xr.Value.Trim();
                        var pageSection = int.Parse(page) + 1;
                        sb.Append(string.Format(format, text, pageSection));
                    }
                }
            }
            sb.Append("</table>");

            var workStream = new MemoryStream();
            var document   = new Document(reader.GetPageSizeWithRotation(1));
            var writer     = PdfWriter.GetInstance(document, workStream);

            writer.CloseStream = false;

            document.Open();
            document.NewPage();

            // Add TOC
            var styles = new StyleSheet();

            styles.LoadTagStyle("h2", HtmlTags.HORIZONTALALIGN, "center");
            styles.LoadTagStyle("h2", HtmlTags.COLOR, "#F90");

            foreach (IElement element in HTMLWorker.ParseToList(new StringReader(sb.ToString()), styles))
            {
                document.Add(element);
            }

            // Append your chapter content again
            var chapter = CreateChapterContent(html);

            document.Add(chapter);

            document.Close();
            writer.Close();

            var byteInfo = workStream.ToArray();

            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return(byteInfo);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Generate PDF To Content
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public byte[] GeneratePDFTOCContent(byte[] content, string html)
        {
            var           reader = new PdfReader(content);
            StringBuilder sb     = new StringBuilder();

            // Title of PDF
            sb.Append("<h2><strong style='text-align:center'> Demo for Load More Button in Kendo UI Grid </ strong ></ h2 >< br > ");

            // Begin to create TOC
            // Begin to create TOC
            sb.Append("<table>");
            sb.Append(("<tr><td width='80%'><strong>{ 0}</strong ></td><td align = 'right' width = '10%'><strong >{1}</strong ></td></tr> "));
            using (MemoryStream ms = new MemoryStream())
            {
                // XML document generated by iText
                SimpleBookmark.ExportToXML(SimpleBookmark.GetBookmark(reader), ms, "UTF-8", false);

                // rewind to create xmlreader
                ms.Position = 0;
                using (XmlReader xr = XmlReader.Create(ms))
                {
                    xr.MoveToContent();
                    string page = null;
                    string text = null;

                    string format = @"<tr><td width='80%'>{0}</td>
            <td align='right' width='10%'>{1}</td></tr>";

                    // extract page number from 'Page' attribute
                    Regex re = new Regex(@"^\d+");
                    while (xr.Read())
                    {
                        if (xr.NodeType == XmlNodeType.Element &&
                            xr.Name == "Title" && xr.IsStartElement())
                        {
                            page = re.Match(xr.GetAttribute("Page")).Captures[0].Value;
                            xr.Read();

                            if (xr.NodeType == XmlNodeType.Text)
                            {
                                text = xr.Value.Trim();
                                int pageSection = int.Parse(page) + 1;
                                sb.Append(String.Format(format, text, pageSection.ToString()));
                            }
                        }
                    }
                }
            }

            sb.Append("</table>");

            MemoryStream workStream = new MemoryStream();
            var          document   = new Document(reader.GetPageSizeWithRotation(1));
            var          writer     = PdfWriter.GetInstance(document, workStream);

            writer.CloseStream = false;

            document.Open();
            document.NewPage();

            // Add TOC
            //StyleSheet styles = new StyleSheet();
            //styles.LoadTagStyle("h2", HtmlTags.ALIGN_MIDDLE, "center");
            //styles.LoadTagStyle("h2", HtmlTags.COLOR, "#F90");


            StyleSheet style = new StyleSheet();

            style.LoadTagStyle(HtmlTags.DIV, HtmlTags.WIDTH, "220px");
            style.LoadTagStyle(HtmlTags.DIV, HtmlTags.HEIGHT, "80px");
            style.LoadTagStyle(HtmlTags.DIV, HtmlTags.BGCOLOR, "@eeeeee");
            style.LoadStyle("address", "style", "font-size: 8px; text-align: justify; font-family: Arial, Helvetica, sans-serif;");
            style.LoadStyle("largeName", "style", "font-size: 10px; text-align: justify; font-family: Arial, Helvetica, sans-serif;");
            style.LoadStyle("description", "style", "font-size: 8px; text-align: justify; font-family: Arial, Helvetica, sans-serif;");


            foreach (IElement element in HTMLWorker.ParseToList(new StringReader(sb.ToString()), style))
            {
                document.Add(element);
            }

            // Append your chapter content again
            Chapter chapter = CreateChapterContent(html);

            document.Add(chapter);

            document.Close();
            writer.Close();

            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return(byteInfo);
        }