コード例 #1
0
ファイル: PdfConverter.cs プロジェクト: bimreaf/Common
        /// <summary>
        /// Gets the pdf page bookmark.
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private static Dictionary <int, string> GetPageMark(PdfReader reader)
        {
            var marks   = SimpleBookmark.GetBookmark(reader);
            var results = new Dictionary <int, string>();

            foreach (Hashtable mark in marks)
            {
                var title = string.Empty;
                var page  = 0;

                foreach (DictionaryEntry kv in mark)
                {
                    switch (kv.Key.ToString())
                    {
                    case "Action":
                        continue;

                    case "Title":
                        title = kv.Value.ToString();
                        break;

                    case "Page":
                        page = Convert.ToInt32(kv.Value.ToString().Split(' ')[0]);
                        break;
                    }
                }

                results.Add(page, title);
            }

            return(results);
        }
コード例 #2
0
ファイル: Form1.cs プロジェクト: Nazmul-ca/Bookmark_extractor
        void bgw_DoWork(string reader_name)
        {
            reader = new iTextSharp.text.pdf.PdfReader(reader_name);

            IList <Dictionary <string, object> > book_mark = SimpleBookmark.GetBookmark(reader);

            foreach (Dictionary <string, object> bk in book_mark)
            {
                foreach (KeyValuePair <string, object> kvr in bk)
                {
                    if (kvr.Key == "Kids" || kvr.Key == "kids")
                    {
                        IList <Dictionary <string, object> > child = (IList <Dictionary <string, object> >)kvr.Value;
                        treeView1.Invoke((MethodInvoker)(() => recursive_search(child, tn)));
                    }

                    else if (kvr.Key == "Title" || kvr.Key == "title")
                    {
                        tn    = new System.Windows.Forms.TreeNode(kvr.Value.ToString());
                        title = kvr.Value.ToString();
                    }
                    else if (kvr.Key == "Page" || kvr.Key == "page")
                    {
                        //saves page number
                        tn.ToolTipText = Regex.Match(kvr.Value.ToString(), "[0-9]+").Value;
                        treeView1.Invoke((MethodInvoker)(() => treeView1.Nodes.Add(tn)));
                        ProgressChanged(title, kvr.Value.ToString());
                    }
                }
            }

            label1.Invoke((MethodInvoker)(() => label1.Text = "book_mark Extraction completed"));
            show_book_mark.Invoke((MethodInvoker)(() => show_book_mark.Enabled = true));
            progressBar1.Invoke((MethodInvoker)(() => progressBar1.Visible = false));
        }
コード例 #3
0
        public int SavePageMarker(string namePDF)
        {
            int       res     = 0;
            string    oldFile = namePDF;
            string    newFile = "temporal.pdf";
            PdfReader reader  = new PdfReader(oldFile);
            IList <Dictionary <String, Object> > bmProperties = SimpleBookmark.GetBookmark(reader);
            PdfStamper stamp = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));

            if (bmProperties != null)
            {
                //MessageBox.Show("Cantidad marcadores " + bmProperties.Count());

                Dictionary <String, Object> marcador = new Dictionary <String, Object>();
                marcador.Add("Action", "GoTo");
                marcador.Add("Title", "Esto es otro marcador");
                marcador.Add("Page", "2 XYZ 100 100 0"); // use height of 1st page
                bmProperties.Add(marcador);
                stamp.Outlines = bmProperties;
                stamp.Close();
                //System.Diagnostics.Process.Start(newFile);
                //Console.Read();
                reader.Close();
                File.Replace(newFile, oldFile, @"backup.pdf.bac");

                //File.Replace(@"temporal.pdf", @"ejemploOK.pdf", @"backup.pdf.bac");
                Console.WriteLine("Pdf modificado con exito (tenia marc), se ha guardado un backup de la versión anterior ");
            }
            else
            {
                //stamp.GetUnderContent(1);
                //var h= stamp.GetImportedPage(reader, 1).Height;

                IList <Dictionary <String, Object> > marcadores = new List <Dictionary <String, Object> >();
                Dictionary <String, Object>          marcador   = new Dictionary <String, Object>();
                //marcadores.Add(marcador);
                marcador.Add("Action", "GoTo");
                marcador.Add("Title", "Page1 0 H 0");
                marcador.Add("Page", "1 XYZ 100 100 0"); // use height of 1st page
                // MessageBox.Show("marcador " + marcador.Count);

                //MessageBox.Show("marcador " + marcador.Keys);
                marcadores.Add(marcador);


                stamp.Outlines = marcadores;
                stamp.Close();
                //System.Diagnostics.Process.Start(newFile);
                //Console.Read();
                reader.Close();
                File.Replace(newFile, oldFile, @"backup.pdf.bac");

                //File.Replace(@"temporal.pdf", @"ejemploOK.pdf", @"backup.pdf.bac");
                Console.WriteLine("Pdf modificado con exito (no tenia marc), se ha guardado un backup de la versión anterior ");
            }



            return(res);
        }
コード例 #4
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);
                }
            }
        }
コード例 #5
0
        public int DeleteMarker(string marker, string namePDF)
        {
            string[] delimiters  = new string[] { " Pag." };
            string[] items       = marker.Split(delimiters, StringSplitOptions.None);
            string   markerTitle = items[0];
            string   markerPage  = items[1];

            markerTitle = markerTitle.Trim();
            markerPage  = markerPage.Trim();
            Console.WriteLine("Esto comparo :" + markerTitle + "___" + markerPage);
            string    oldFile = namePDF;
            string    newFile = "temporal.pdf";
            PdfReader reader  = new PdfReader(oldFile);
            IList <Dictionary <String, Object> > bmProperties = SimpleBookmark.GetBookmark(reader);
            PdfStamper stamp = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));
            int        index = -1;
            int        i     = 0;

            foreach (IDictionary <String, Object> bmProperty in bmProperties)
            {
                var getPage   = bmProperty["Page"];
                var getTittle = bmProperty["Title"];

                var aux_pagina = getPage.ToString().Split(' ');
                var pagina     = aux_pagina[0];
                //Console.WriteLine("Esto saco :" + getTittle + "___" + pagina);
                //Console.WriteLine("elemento " + bmProperty);
                if (markerTitle == (string)getTittle && markerPage == (string)pagina)
                {
                    Console.WriteLine("Se elimina este marcador en pos " + i);
                    index = i;
                }
                i += 1;
            }
            if (index == -1)
            {
                stamp.Close();
                reader.Close();
                return(0);
            }
            else
            {
                bmProperties.RemoveAt(index);
                stamp.Outlines = bmProperties;
                stamp.Close();
                //System.Diagnostics.Process.Start(newFile);
                //Console.Read();
                reader.Close();
                File.Replace(newFile, oldFile, @"backup.pdf.bac");
                return(1);
            }


            //MessageBox.Show("Pdf modificado con exito, se ha guardado un backup de la versión anterior ");
            //listBox1.Items.Remove(marcador);
        }
コード例 #6
0
        private static void MergePdfFiles(MemoryStream outputPdf, Stream[] sourcePdfs)
        {
            PdfReader       reader      = null;
            Document        document    = new Document();
            PdfImportedPage page        = null;
            PdfCopy         pdfCpy      = null;
            int             n           = 0;
            int             totalPages  = 0;
            int             page_offset = 0;
            List <Dictionary <string, object> >  bookmarks = new List <Dictionary <string, object> >();
            IList <Dictionary <string, object> > tempBookmarks;

            for (int i = 0; i <= sourcePdfs.GetUpperBound(0); i++)
            {
                reader = new PdfReader(sourcePdfs[i]);
                reader.ConsolidateNamedDestinations();
                n             = reader.NumberOfPages;
                tempBookmarks = SimpleBookmark.GetBookmark(reader);

                if (i == 0)
                {
                    document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
                    pdfCpy   = new PdfCopy(document, outputPdf);
                    document.Open();
                    SimpleBookmark.ShiftPageNumbers(tempBookmarks, page_offset, null);
                    page_offset += n;
                    if (tempBookmarks != null)
                    {
                        bookmarks.AddRange(tempBookmarks);
                    }
                    totalPages = n;
                }
                else
                {
                    SimpleBookmark.ShiftPageNumbers(tempBookmarks, page_offset, null);
                    if (tempBookmarks != null)
                    {
                        bookmarks.AddRange(tempBookmarks);
                    }

                    page_offset += n;
                    totalPages  += n;
                }

                for (int j = 1; j <= n; j++)
                {
                    page = pdfCpy.GetImportedPage(reader, j);
                    pdfCpy.AddPage(page);
                }
                reader.Close();
            }
            pdfCpy.Outlines = bookmarks;
            document.Close();
        }
コード例 #7
0
 private void OpenPDF(string file)
 {
     try
     {
         label2.Text = file;
         pdfReader   = new PdfReader(file);
         bookmarks   = SimpleBookmark.GetBookmark(pdfReader);
     }
     catch (IOException)
     {
     }
 }
コード例 #8
0
        /// <summary>
        /// Compiles ARRL books.
        /// </summary>
        /// <param name="folder">Directory containing all the PDFs in the entire book.</param>
        /// <param name="output">Path and filename of the output (compiled) PDF.</param>
        private static void Merge(string folder, string output)
        {
            int offset = 1;      // Setting to 0 causes all bookmarks to be off by 1

            string[] dirFiles
                = Directory.GetFiles(folder).Where(f => f.EndsWith("pdf")).ToArray();      // PDFs in directory
            IList <Dictionary <string, object> > oldBookmarks
                = SimpleBookmark.GetBookmark(new PdfReader(dirFiles[0]));
            List <Dictionary <string, object> > newBookmarks = new List <Dictionary <string, object> >();

            FileStream     outFile = new FileStream(output, FileMode.Create);
            PdfConcatenate newPdf  = new PdfConcatenate(outFile);

            if (oldBookmarks.Count() == 1)
            {
                oldBookmarks = (IList <Dictionary <string, object> >)(oldBookmarks[0])[KIDS_KEY];
            }

            string[] bFiles
                = oldBookmarks.Select(b => b[FILE_KEY]).Cast <string>().ToArray();     // get files in bookmark order
            IEnumerable <string> missingFiles = bFiles.Except(dirFiles.Select(f => Path.GetFileName(f)));

            if (missingFiles.Any())
            {
                Console.Error.WriteLine("The following files are present in the bookmarks but not in the directory:");
                foreach (string filename in missingFiles)
                {
                    Console.Error.WriteLine(filename);
                }
                Environment.Exit(2);
            }

            for (int i = 0; i < bFiles.Count(); i++)
            {
                Console.Write(string.Format("\r{0}% complete", (int)((i + 1f) / bFiles.Count() * 100)));
                string    filename = bFiles[i];
                PdfReader reader   = new PdfReader(Path.Combine(folder, filename));
                List <Dictionary <string, object> > tempBookmarks =
                    oldBookmarks.Where(b => b.ContainsKey(FILE_KEY) && (string)b[FILE_KEY] == filename).ToList();

                // handles bookmarks
                newBookmarks.AddRange(ModifyBookmarks(      // Exception if LINQ can't find FILE_KEY key in ANY list item
                                          oldBookmarks.Where(b => b.ContainsKey(FILE_KEY) && (string)b[FILE_KEY] == filename).ToList(),
                                          offset));
                offset += reader.NumberOfPages;

                newPdf.AddPages(reader);
                reader.Close();
            }

            newPdf.Writer.Outlines = newBookmarks;
            newPdf.Close();
        }
コード例 #9
0
        private static StringBuilder ExtractAllBookmarks(string pdf)
        {
            StringBuilder sb     = new StringBuilder();
            PdfReader     reader = new PdfReader(pdf);
            IList <Dictionary <string, object> > bookmarksTree = SimpleBookmark.GetBookmark(reader);

            foreach (var node in bookmarksTree)
            {
                sb.AppendLine(PercorreBookmarks(node).ToString());
            }
            return(RemoveAllBlankLines(sb));
        }
コード例 #10
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());
                }
            }
        }
コード例 #11
0
        void ProcessPdf(string path)
        {
            using (var reader = new PdfReader(path))
            {
                // need this call to parse page numbers
                reader.ConsolidateNamedDestinations();

                var bookmarks = ParseBookMarks(SimpleBookmark.GetBookmark(reader));
                for (int i = 0; i < bookmarks.Count; ++i)
                {
                    int page     = bookmarks[i].PageNumberInteger;
                    int nextPage = i + 1 < bookmarks.Count
                                   // if not top of page will be missing content
                        ? bookmarks[i + 1].PageNumberInteger - 1

                                   /* alternative is to potentially add redundant content:
                                    * ? bookmarks[i + 1].PageNumberInteger
                                    */

                        : reader.NumberOfPages;
                    string range = string.Format("{0}-{1}", page, nextPage);

                    // DEMO!
                    if (i < 1000)
                    {
                        var outputPath = Path.Combine(OUTPUT_DIR, bookmarks[i].GetFileName());
                        using (var readerCopy = new PdfReader(reader))
                        {
                            var number = bookmarks[i].Number;
                            readerCopy.SelectPages(range);
                            using (FileStream stream = new FileStream(outputPath, FileMode.Create))
                            {
                                using (var document = new Document())
                                {
                                    using (var copy = new PdfCopy(document, stream))
                                    {
                                        document.Open();
                                        int n = readerCopy.NumberOfPages;
                                        for (int j = 0; j < n;)
                                        {
                                            copy.AddPage(copy.GetImportedPage(readerCopy, ++j));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #12
0
        public List <string> GetPageMarker(string nombrePDF)
        {
            string    oldFile = nombrePDF;
            string    newFile = "temporal.pdf";
            PdfReader reader  = new PdfReader(oldFile);
            IList <Dictionary <String, Object> > bmProperties = SimpleBookmark.GetBookmark(reader);
            PdfStamper stamp = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));
            //List<List<string>> marcadores_final = new List<List<string>>();
            List <string> marcadores_final = new List <string>();

            if (bmProperties != null)
            {
                //listBox1.Items.Clear();
                //MessageBox.Show("Cantidad marcadores " + bmProperties.Count());
                List <string> aux_marcador = new List <string>();

                foreach (IDictionary <String, Object> bmProperty in bmProperties)
                {
                    aux_marcador.Clear();
                    // MessageBox.Show("pagina " + bmProperty["Page"] + " - Titulo " + bmProperty["Title"]);
                    var getPage   = bmProperty["Page"];
                    var getTittle = bmProperty["Title"];

                    var aux_pagina = getPage.ToString().Split(' ');
                    var pagina     = aux_pagina[0];
                    var titulo     = getTittle;
                    aux_marcador.Add(pagina.ToString());
                    aux_marcador.Add(titulo.ToString());
                    //marcadores_final.Add(aux_marcador);
                    marcadores_final.Add(titulo + " Pag." + pagina);
                    //Console.WriteLine("esto tengo en la lista pagina :" + pagina);



                    //listBox1.Items.Add(titulo + "  Pag. " + pagina);

                    //}
                }
                stamp.Close();
                reader.Close();
            }

            foreach (var item in marcadores_final)
            {
                Console.WriteLine("uno " + item);
            }
            return(marcadores_final);
        }
コード例 #13
0
        private void CopyBookmarks(PdfReader reader, PdfCopy writer, Dictionary <int, int> sortKeys)
        {
            var outlines        = SimpleBookmark.GetBookmark(reader);
            var reverseSortKeys = new Dictionary <int, int>();

            foreach (var newPageNumber in sortKeys.Keys)
            {
                var oldPageNumber = sortKeys[newPageNumber];
                reverseSortKeys.Add(oldPageNumber, newPageNumber);
            }

            UpdateTargetPages(outlines, reverseSortKeys);

            SortBookmarks(outlines);

            writer.Outlines = outlines;
        }
コード例 #14
0
        // ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src with the file dest as result
         * @param src the original PDF
         */
        public byte[] ManipulatePdf(List <byte[]> src)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // step 1
                using (Document document = new Document())
                {
                    // step 2
                    using (PdfCopy copy = new PdfCopy(document, ms))
                    {
                        // step 3
                        document.Open();
                        // step 4
                        int page_offset = 0;
                        // Create a list for the bookmarks
                        List <Dictionary <String, Object> > bookmarks =
                            new List <Dictionary <String, Object> >();

                        for (int i = 0; i < src.Count; i++)
                        {
                            PdfReader reader = new PdfReader(src[i]);
                            // merge the bookmarks
                            IList <Dictionary <String, Object> > tmp =
                                SimpleBookmark.GetBookmark(reader);
                            SimpleBookmark.ShiftPageNumbers(tmp, page_offset, null);
                            foreach (var d in tmp)
                            {
                                bookmarks.Add(d);
                            }

                            // add the pages
                            int n = reader.NumberOfPages;
                            page_offset += n;
                            for (int page = 0; page < n;)
                            {
                                copy.AddPage(copy.GetImportedPage(reader, ++page));
                            }
                        }
                        // Add the merged bookmarks
                        copy.Outlines = bookmarks;
                    }
                }
                return(ms.ToArray());
            }
        }
コード例 #15
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);
        }
コード例 #16
0
        /// <summary>
        /// Split PDF file into multiple files.
        /// Each file contains one group in Crystal Reports
        /// </summary>
        /// <param name="sourceFile">Source PDF File</param>
        /// <param name="outDirectory">PDF output directory</param>
        /// <returns></returns>
        public int SplitPDFByBookmark(string sourceFile, string outDirectory)
        {
            if (!File.Exists(sourceFile))
            {
                throw new Exception($"Unable to locate source file {sourceFile}");
            }

            PdfReader pdfReader = new PdfReader(sourceFile);

            try
            {
                IList <Dictionary <string, object> > bookmarks = SimpleBookmark.GetBookmark(pdfReader);
                if (bookmarks == null)
                {
                    return(0);
                }

                if (bookmarks != null && bookmarks.Count > 0)
                {
                    var root     = bookmarks.First();
                    var hasChild = root.ContainsKey(PDF_KIDS);
                    if (hasChild)
                    {
                        var topLevelBookmarks = (IList <Dictionary <string, object> >)root[PDF_KIDS]; //will not scan further level
                        for (var i = 0; i < topLevelBookmarks.Count; i++)
                        {
                            IDictionary <string, object> nextBM = i == topLevelBookmarks.Count - 1 ? null : topLevelBookmarks[i + 1];

                            var title    = topLevelBookmarks[i][PDF_TITLE];
                            var pageFrom = Convert.ToInt32(Regex.Match(topLevelBookmarks[i][PDF_PAGE].ToString(), "[0-9]+").Value);
                            var pageTo   = nextBM != null?Convert.ToInt32(Regex.Match(nextBM[PDF_PAGE].ToString(), "[0-9]+").Value) - 1 : (pdfReader.NumberOfPages);

                            SplitPDFByPageRange(sourceFile, outDirectory, $"{title}.pdf", pageFrom, pageTo);
                        }
                        return(topLevelBookmarks.Count);
                    }
                }
                return(0);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #17
0
        public bool GetBKTreeView(PdfReader pdfreader, ref TreeView trv)
        {
            try
            {
                IList <Dictionary <string, object> > bookmark = SimpleBookmark.GetBookmark(pdfreader);

                foreach (Dictionary <string, object> bk in bookmark)
                {
                    foreach (KeyValuePair <string, object> kvr in bk)
                    {
                        //have child node
                        if (kvr.Key == "Kids" || kvr.Key == "kids")
                        {
                            IList <Dictionary <string, object> > child = (IList <Dictionary <string, object> >)kvr.Value;
                            recursive_func(child, tn);
                        }

                        //add bkmark name to treenode
                        else if (kvr.Key == "Title" || kvr.Key == "title")
                        {
                            tn = new System.Windows.Forms.TreeNode(kvr.Value.ToString());
                        }

                        //add bkmark page number to treenode
                        else if (kvr.Key == "Page" || kvr.Key == "page")
                        {
                            tn.ContextMenuStrip = contextMenuStrip1;
                            tn.Tag = Regex.Match(kvr.Value.ToString(), "[0-9]+").Value;
                            trv.Nodes.Add(tn);
                        }
                        else //do nothing
                        {
                        }
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
コード例 #18
0
        void DumpResults(string path)
        {
            using (var reader = new PdfReader(path))
            {
                // need this call to parse page numbers
                reader.ConsolidateNamedDestinations();

                var bookmarks = ParseBookMarks(SimpleBookmark.GetBookmark(reader));
                var sb        = new StringBuilder();
                foreach (var bookmark in bookmarks)
                {
                    sb.AppendLine(string.Format(
                                      "{0, -4}{1, -100}{2, -25}{3}",
                                      bookmark.Number, bookmark.Title,
                                      bookmark.PageNumberString, bookmark.PageNumberInteger
                                      ));
                }
                File.WriteAllText(outputTextFile, sb.ToString());
            }
        }
コード例 #19
0
        /* ----------------------------------------------------------------- */
        ///
        /// GetBookmarks
        ///
        /// <summary>
        /// Gets the collection of bookmarks embedded in the specified
        /// PDF document.
        /// </summary>
        ///
        /// <param name="src">PdfReader object.</param>
        /// <param name="pagenum">Page number.</param>
        /// <param name="delta">
        /// Difference in page numbers between PDF documents.
        /// </param>
        /// <param name="dest">Container for the result.</param>
        ///
        /// <remarks>
        /// PdfReader オブジェクトから取得されたしおり情報に対して、
        /// ページ番号を delta だけずらした後に処理を実行します。
        /// </remarks>
        ///
        /* ----------------------------------------------------------------- */
        public static void GetBookmarks(this PdfReader src, int pagenum, int delta,
                                        IList <Dictionary <string, object> > dest)
        {
            var cmp       = $"^{pagenum} (XYZ|Fit|FitH|FitBH)";
            var bookmarks = SimpleBookmark.GetBookmark(src);

            if (bookmarks == null)
            {
                return;
            }

            SimpleBookmark.ShiftPageNumbers(bookmarks, delta, null);
            foreach (var b in bookmarks)
            {
                var found = b.TryGetValue("Page", out object obj);
                if (found && Regex.IsMatch(obj.ToString(), cmp))
                {
                    dest.Add(b);
                }
            }
        }
コード例 #20
0
ファイル: Main.cs プロジェクト: lmbrt/PDFBookmark
        public static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: pdfBookmarkReader.exe pdffile.pdf");
                return;
            }

            string file = args[0];

            if (!System.IO.File.Exists(file))
            {
                Console.WriteLine("File {0} is missing", file);
                return;
            }


            PdfReader pr = new PdfReader(file);
            IList <Dictionary <string, object> > bookmarks = SimpleBookmark.GetBookmark(pr);

            Console.WriteLine("<PDF>\n\t<PageCount>{0}</PageCount>\n\t<Bookmarks Total=\"{1}\">\t", pr.NumberOfPages, bookmarks.Count);

            if (bookmarks != null)
            {
                foreach (Dictionary <string, object> bookmark in bookmarks)
                {
                    string title = (string)bookmark["Title"];

                    title = _whitespaceRegex.Replace(title, " ");
                    string[] pageData = ((string)(bookmark["Page"])).Split(' ');
                    string   page     = pageData[0];
                    page = page.Trim();

                    Console.WriteLine("\t\t<Bookmark>\n\t\t\t<Title>{0}</Title>\n\t\t\t<Page>{1}</Page>\n\t\t</Bookmark>", title, page);
                }
            }

            Console.WriteLine("\t</Bookmarks>\n</PDF>");
        }
コード例 #21
0
        virtual public void TestNoBreakSpace()
        {
            MemoryStream ms       = new MemoryStream();
            Document     document = new Document();

            PdfWriter writer = PdfWriter.GetInstance(document, ms);

            document.Open();
            writer.PageEvent = new CustomPdfPageEventHelper();
            document.Add(new Paragraph("Hello World"));
            document.Close();

            // read bookmark back
            PdfReader r = new PdfReader(ms.ToArray());

            IList <Dictionary <String, Object> > bookmarks = SimpleBookmark.GetBookmark(r);

            Assert.AreEqual(1, bookmarks.Count, "bookmark size");
            Dictionary <String, Object> b = bookmarks[0];
            String title = (String)b["Title"];

            Assert.AreEqual(TITLE, title, "bookmark title");
        }
コード例 #22
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);
        }
コード例 #23
0
ファイル: OutputPdf.cs プロジェクト: kuttsun/MakePdf
        void AddBookmark(PdfReader reader, string pdfFilename, List <Dictionary <String, Object> > parentBookmarks)
        {
            // Get bookmark from PDF
            var childBookmark = SimpleBookmark.GetBookmark(reader);

            if (childBookmark != null)
            {
                // It has a bookmark
                SimpleBookmark.ShiftPageNumbers(childBookmark, pageCount, null);
            }
            else
            {
                // Create empty bookmark
                childBookmark = new List <Dictionary <String, Object> >();
            }

            // Replace filename for bookmark
            string bookmarkFileName;

            if (replaceFileName.IsEnabled != false)
            {
                bookmarkFileName = Regex.Replace(pdfFilename, replaceFileName.Before, replaceFileName.After);
            }
            else
            {
                bookmarkFileName = Path.GetFileName(pdfFilename);
            }

            // Create filename bookmark
            var bookmarks = new List <Dictionary <string, object> >();

            if (addFileNameToBookmark.IsEnabled == false)
            {
                if ((addFileNameToBookmark.ExclusionPattern != null) && Regex.IsMatch(pdfFilename, addFileNameToBookmark.ExclusionPattern))
                {
                    bookmarks.Add(CreateBookmark(bookmarkFileName, childBookmark));
                }
                else
                {
                    bookmarks.AddRange(childBookmark);
                }
            }
            else
            {
                if ((addFileNameToBookmark.ExclusionPattern != null) && (Regex.IsMatch(pdfFilename, addFileNameToBookmark.ExclusionPattern)))
                {
                    bookmarks.AddRange(childBookmark);
                }
                else
                {
                    bookmarks.Add(CreateBookmark(bookmarkFileName, childBookmark));
                }
            }

            // Add bookmarks to parent bookmarks
            if (parentBookmarks == null)
            {
                rootBookmarks.AddRange(bookmarks);
            }
            else
            {
                parentBookmarks.AddRange(bookmarks);
            }
        }
コード例 #24
0
ファイル: frmMain.cs プロジェクト: Dolemite1347/PDFSplitIT
        protected void AnalyzeFile()
        {
            analyzeFailed = false;
            this.SetStatusText("Analyzing...");
            SetPictureVisible(ref imgError, false);
            SetPictureVisible(ref imgOK, false);

            if (radRadioButton2.IsChecked && txtPageNumbers.Text.Trim().Length > 0)
            {
                try
                {
                    String[] pages = txtPageNumbers.Text.Trim().Replace(" ", "").Split(',');
                    foreach (string s in pages)
                    {
                        if (s.Contains('-'))
                        {
                            String[] pageRange = s.Split('-');
                            if (Convert.ToInt32(pageRange[0]) >= Convert.ToInt32(pageRange[1]))
                            {
                                MessageBox.Show("Cannot count pages backwards. Please correct your page range.", "Invalid Page Range", MessageBoxButtons.OK);
                                analyzeFailed = true;
                                SetButtonEnabled(ref btnSourcePDF, true);
                                SetButtonEnabled(ref btnDestinationPDF, true);
                                SetPictureVisible(ref imgError, true);
                                SetGroupBoxEnabled(ref radGroupBox1, true);
                                this.SetStatusText("Invalid Page Range");
                                this.SetProgressBar(ref progressStatus, false, 100);
                                this.SetProgressPanelVisible(false);
                                analyzeThread.Abort();
                                return;
                            }
                            else if (pageRange.Length > 2)
                            {
                                MessageBox.Show("Invalid page range entered. Please correct your entry and try again", "Invalid Page Range", MessageBoxButtons.OK);
                                analyzeFailed = true;
                                SetButtonEnabled(ref btnSourcePDF, true);
                                SetButtonEnabled(ref btnDestinationPDF, true);
                                SetGroupBoxEnabled(ref radGroupBox1, true);
                                SetPictureVisible(ref imgError, true);
                                this.SetStatusText("Invalid Page Range");
                                this.SetProgressBar(ref progressStatus, false, 100);
                                this.SetProgressPanelVisible(false);
                                analyzeThread.Abort();
                                return;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    analyzeFailed = true;
                    SetButtonEnabled(ref btnSourcePDF, true);
                    SetButtonEnabled(ref btnDestinationPDF, true);
                    SetPictureVisible(ref imgError, true);
                    SetGroupBoxEnabled(ref radGroupBox1, true);
                    this.SetStatusText("Invalid Page Range");
                    this.SetProgressBar(ref progressStatus, false, 100);
                    this.SetProgressPanelVisible(false);
                    analyzeThread.Abort();
                    return;
                }
            }

            PdfReader         pdfDocument       = new PdfReader(lblSourcePDF.Text);
            PdfDictionary     document          = new PdfDictionary( );
            SortPagesProvider sortPagesProvider = new SortPagesProvider();
            int page_number = 0;

            if (radRadioButton1.IsChecked)
            {
                bookMarkReferences = new List <BookMarkReference>();
                IList <Dictionary <string, object> > bookmarks = SimpleBookmark.GetBookmark(pdfDocument);

                if (bookmarks != null)
                {
                    int i = 0;
                    this.SetProgressBar(ref progressStatus, true, bookmarks.Count);
                    foreach (Dictionary <string, object> bk in bookmarks)
                    {
                        foreach (KeyValuePair <string, object> kvr in bk)
                        {
                            if (kvr.Key == "Page" || kvr.Key == "page")
                            {
                                page_number = Convert.ToInt32(Regex.Match(kvr.Value.ToString(), "[0-9]+").Value);
                            }
                        }

                        bookMarkReferences.Add(new BookMarkReference(bookmarks[i].Values.ToArray().GetValue(0).ToString(), page_number));
                        this.AddTreeNode(radTreeView1, bookmarks[i].Values.ToArray().GetValue(0).ToString() + " (Page: " + page_number.ToString() + ")");
                        this.SetStatusText(string.Format("Analyzing, {0}...", bookmarks[i].Values.ToArray().GetValue(0).ToString()));
                        this.SetProgressBarValue(ref progressStatus, i);
                        Thread.Sleep(500);
                        i++;
                    }

                    bookMarkReferences.Sort(sortPagesProvider);
                    SetButtonEnabled(ref btnSourcePDF, true);
                    SetButtonEnabled(ref btnDestinationPDF, true);
                    SetPictureVisible(ref imgOK, true);
                    SetGroupBoxEnabled(ref radGroupBox1, true);
                    this.SetStatusText("Done.");
                    this.SetProgressBar(ref progressStatus, false, 100);
                    this.SetProgressPanelVisible(false);
                }
                else
                {
                    analyzeFailed = true;
                    SetButtonEnabled(ref btnSourcePDF, true);
                    SetButtonEnabled(ref btnDestinationPDF, true);
                    SetPictureVisible(ref imgError, true);
                    SetGroupBoxEnabled(ref radGroupBox1, true);
                    this.SetStatusText("No Bookmarks Found!");
                    this.SetProgressBar(ref progressStatus, false, 100);
                    this.SetProgressPanelVisible(false);
                }
            }
            else if (radRadioButton2.IsChecked)
            {
                String[] pages = txtPageNumbers.Text.Trim().Replace(" ", "").Split(',');

                Int32 pageCount = pdfDocument.NumberOfPages;

                if (pages.Length > 0)
                {
                    this.SetProgressBar(ref progressStatus, true, pages.Length);
                    try {
                        for (int i = 0; i < pages.Length; i++)
                        {
                            this.SetStatusText(string.Format("Analyzing, {0}...", pages[i]));
                            this.SetProgressBarValue(ref progressStatus, i + 1);

                            if (pages[i].Trim() != "")
                            {
                                if (pages[i].Contains("-"))
                                {
                                    if (pages[i].Split('-')[1].Trim() != "")
                                    {
                                        Int32 lastnum = Convert.ToInt32(pages[i].Split('-')[1]);
                                        if (lastnum > pageCount)
                                        {
                                            analyzeFailed = true;
                                            this.AddTreeNode(radTreeView1, "Page(s): " + pages[i] + " - Invalid");
                                        }
                                        else
                                        {
                                            this.AddTreeNode(radTreeView1, "Page(s): " + pages[i] + " - \u2713");
                                        }
                                    }
                                }
                                else
                                {
                                    if (Convert.ToInt32(pages[i]) > pageCount)
                                    {
                                        analyzeFailed = true;
                                        this.AddTreeNode(radTreeView1, "Page(s): " + pages[i] + " - Invalid");
                                    }
                                    else
                                    {
                                        this.AddTreeNode(radTreeView1, "Page(s): " + pages[i] + " - \u2713");
                                    }
                                }
                            }
                        }

                        this.SetStatusText("Done.");
                        SetButtonEnabled(ref btnSourcePDF, true);
                        SetButtonEnabled(ref btnDestinationPDF, true);
                        SetPictureVisible(ref imgOK, true);
                        SetGroupBoxEnabled(ref radGroupBox1, true);
                        this.SetProgressBar(ref progressStatus, false, 100);
                        this.SetProgressPanelVisible(false);
                    } catch (Exception ex) {
                        MessageBox.Show("There was a problem analyzing your document. Please check your entries and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.SetStatusText("Failed.");
                        SetButtonEnabled(ref btnSourcePDF, true);
                        SetButtonEnabled(ref btnDestinationPDF, true);
                        SetPictureVisible(ref imgError, true);
                        SetGroupBoxEnabled(ref radGroupBox1, true);
                        this.SetProgressBar(ref progressStatus, false, 100);
                        this.SetProgressPanelVisible(false);
                    }
                }
            }
            else
            {
                analyzeFailed = true;
                this.SetStatusText("No pages documented.");
                SetButtonEnabled(ref btnSourcePDF, true);
                SetButtonEnabled(ref btnDestinationPDF, true);
                SetPictureVisible(ref imgError, true);
                SetGroupBoxEnabled(ref radGroupBox1, true);
                this.SetProgressBar(ref progressStatus, false, 100);
                this.SetProgressPanelVisible(false);
            }

            pdfDocument.Close();
            pdfDocument.Dispose();
        }
コード例 #25
0
        private void button2_Click(object sender, EventArgs e)
        {
            string    oldFile = "ejemploOK.pdf";
            string    newFile = "temporal.pdf";
            PdfReader reader  = new PdfReader(oldFile);
            IList <Dictionary <String, Object> > bmProperties = SimpleBookmark.GetBookmark(reader);
            PdfStamper stamp = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));

            if (bmProperties != null)
            {
                MessageBox.Show("Cantidad marcadores " + bmProperties.Count());
                foreach (IDictionary <String, Object> bmProperty in bmProperties)
                {
                    //MessageBox.Show("Key " + bmProperty.Keys + " y values " + bmProperty.Values);
                    foreach (var algo in bmProperty.Keys)
                    {
                        MessageBox.Show("Contiene " + algo);
                    }
                }
                Dictionary <String, Object> marcador = new Dictionary <String, Object>();
                marcador.Add("Action", "GoTo");
                marcador.Add("Title", "Esto es otro marcador");
                marcador.Add("Page", "2 XYZ 100 100 0"); // use height of 1st page
                bmProperties.Add(marcador);
                stamp.Outlines = bmProperties;
                stamp.Close();
                //System.Diagnostics.Process.Start(newFile);
                //Console.Read();
                reader.Close();
                File.Replace(newFile, oldFile, @"backup.pdf.bac");

                //File.Replace(@"temporal.pdf", @"ejemploOK.pdf", @"backup.pdf.bac");
                MessageBox.Show("Pdf modificado con exito, se ha guardado un backup de la versión anterior ");
            }
            else
            {
                //stamp.GetUnderContent(1);
                //var h= stamp.GetImportedPage(reader, 1).Height;
                MessageBox.Show("El PDF no tiene marcadores");
                IList <Dictionary <String, Object> > marcadores = new List <Dictionary <String, Object> >();
                Dictionary <String, Object>          marcador   = new Dictionary <String, Object>();
                //marcadores.Add(marcador);
                marcador.Add("Action", "GoTo");
                marcador.Add("Title", "Page1 0 H 0");
                marcador.Add("Page", "1 XYZ 100 100 0"); // use height of 1st page
                MessageBox.Show("marcador " + marcador.Count);

                //MessageBox.Show("marcador " + marcador.Keys);
                marcadores.Add(marcador);


                stamp.Outlines = marcadores;
                stamp.Close();
                //System.Diagnostics.Process.Start(newFile);
                //Console.Read();
                reader.Close();
                File.Replace(newFile, oldFile, @"backup.pdf.bac");

                //File.Replace(@"temporal.pdf", @"ejemploOK.pdf", @"backup.pdf.bac");
                MessageBox.Show("Pdf modificado con exito, se ha guardado un backup de la versión anterior ");
            }
        }
コード例 #26
0
        private void button1_Click(object sender, EventArgs e)
        {
            string    oldFile = "ejemploOK.pdf";
            string    newFile = "temporal.pdf";
            PdfReader reader  = new PdfReader(oldFile);
            IList <Dictionary <String, Object> > bmProperties = SimpleBookmark.GetBookmark(reader);
            PdfStamper stamp = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));

            if (bmProperties != null)
            {
                listBox1.Items.Clear();
                MessageBox.Show("Cantidad marcadores " + bmProperties.Count());
                foreach (IDictionary <String, Object> bmProperty in bmProperties)
                {
                    //MessageBox.Show("Key " + bmProperty.Keys + " y values " + bmProperty.Values);

                    //bmProperty.TryGetValue("Page", out valor);

                    //foreach (var algo in bmProperty.Values)
                    //{

                    /* if (algo == "Title")
                     * {
                     *   listBox1.Items.Add(algo.);
                     * }
                     * if (algo == "Page")
                     * {
                     *   listBox1.Items.Add(bmProperty.Values);
                     * }*/

                    MessageBox.Show("pagina " + bmProperty["Page"] + " - Titulo " + bmProperty["Title"]);
                    var getPage   = bmProperty["Page"];
                    var getTittle = bmProperty["Title"];

                    var aux_pagina = getPage.ToString().Split(' ');
                    var pagina     = aux_pagina[0];
                    var titulo     = getTittle;
                    listBox1.Items.Add(titulo + "  Pag. " + pagina);

                    //}
                }
                stamp.Close();
                reader.Close();
            }
            else
            {
                MessageBox.Show("El documento No tiene marcadores / Se agregara uno a modo de prueba");
                IList <Dictionary <String, Object> > marcadores = new List <Dictionary <String, Object> >();

                //marcadores.Add(marcador);
                for (int i = 1; i <= 2; i++)
                {
                    Dictionary <String, Object> marcador = new Dictionary <String, Object>();
                    marcador.Add("Action", "GoTo");
                    marcador.Add("Title", "Marcador " + i);
                    marcador.Add("Page", i + " XYZ 100 600 0");
                    MessageBox.Show("marcador " + marcador.Count);
                    marcadores.Add(marcador);
                }



                stamp.Outlines = marcadores;
                stamp.Close();
                //System.Diagnostics.Process.Start(newFile);
                //Console.Read();
                reader.Close();
                File.Replace(newFile, oldFile, @"backup.pdf.bac");
                MessageBox.Show("Pdf modificado con exito, se ha guardado un backup de la versión anterior ");
            }
        }
コード例 #27
0
ファイル: PdfInterface.cs プロジェクト: chuongmep/PDFUnisci
        private static void AddBookmarks(List <string> files, PdfCopy OutFile)
        {
            //{[Title, pagina uno]}
            //{[Page, 1 XYZ 0 0 null]}
            //{[Action, GoTo]}
            //{[Kids, System.Collections.Generic.List`1[System.Collections.Generic.Dictionary`2[System.String,System.Object]]]}

            // Create a list for the bookmarks
            List <Dictionary <String, Object> > bookmarks = new List <Dictionary <String, Object> >();

            int page_offset = 0;

            PdfReader reader = null;

            try
            {
                for (int i = 0; i < files.Count; i++)
                {
                    reader = new PdfReader(files[i]);

                    // merge the bookmarks
                    IList <Dictionary <String, Object> > tmp = SimpleBookmark.GetBookmark(reader);

                    SimpleBookmark.ShiftPageNumbers(tmp, page_offset, null);

                    if (Bookmarks == 1)
                    {
                        tmp = new List <Dictionary <String, Object> >()
                        {
                            new Dictionary <string, object>()
                            {
                                ["Title"]  = $"{Path.GetFileNameWithoutExtension(files[i])}",
                                ["Page"]   = $"{page_offset+1}",
                                ["Action"] = "GoTo",
                                ["Kids"]   = tmp
                            }
                        };
                    }


                    if (tmp != null)
                    {
                        foreach (var d in tmp)
                        {
                            bookmarks.Add(d);
                        }
                    }

                    // add the pages
                    int n = reader.NumberOfPages;

                    page_offset += n;
                }

                // Add the merged bookmarks
                OutFile.Outlines = bookmarks;

                LogHelper.Log("Bookmarks copied successfully", LogType.Successful);
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString(), LogType.Error);
            }
            finally
            {
                reader?.Dispose();
            }
        }
コード例 #28
0
        public static void ConcatenatePdfFiles(List <string> fromFileNames, string toFileName)
        {
            var      pageOffset = 0;
            var      master     = new ArrayList();
            var      f          = 0;
            Document document   = null /* TODO Change to default(_) if this is not a reference type */;
            PdfCopy  writer     = null /* TODO Change to default(_) if this is not a reference type */;

            foreach (var fromFileName in fromFileNames)
            {
                // we create a reader for a certain document
                var reader = new PdfReader(fromFileName);
                reader.ConsolidateNamedDestinations();

                // we retrieve the total number of pages
                var numberOfPages = reader.NumberOfPages;
                var bookmarks     = SimpleBookmark.GetBookmark(reader);
                if (bookmarks != null)
                {
                    if (pageOffset != 0)
                    {
                        SimpleBookmark.ShiftPageNumbers(bookmarks, pageOffset, null);
                    }
                    master.AddRange(bookmarks);
                }
                pageOffset += numberOfPages;

                if (f == 0)
                {
                    // step 1: creation of a document-object
                    document = new Document(reader.GetPageSizeWithRotation(1));

                    // step 2: we create a writer that listens to the document
                    writer = new PdfCopy(document, new FileStream(toFileName, FileMode.Create));

                    // step 3: we open the document
                    document.Open();
                }

                // step 4: we add content
                PdfImportedPage page;
                int             i = 0;
                while (i < numberOfPages)
                {
                    i   += 1;
                    page = writer.GetImportedPage(reader, i);
                    writer.AddPage(page);
                }

                PRAcroForm form = reader.AcroForm;
                if (form != null)
                {
                    writer.CopyAcroForm(reader);
                }

                reader.Close();
                f++;
            }

            // step 5: we close the document
            document.Close();
        }
コード例 #29
0
        private string[] SplitPdf(string url, string splittedFilesDirectoryName, string prefixOfFileName)
        {
            PdfReader reader = LibPDFTools.CreatePdfReader(url, QueryPassword, false);

            try
            {
                reader.ConsolidateNamedDestinations();
                IList <Dictionary <string, object> > bookmarks = SimpleBookmark.GetBookmark(reader);
                int      numberOfPages = reader.NumberOfPages;
                string[] splittedFiles = new string[numberOfPages];
                Directory.CreateDirectory(splittedFilesDirectoryName);

                for (int i = 1; i <= numberOfPages; i++)
                {
                    string splittedFile = Path.Combine(splittedFilesDirectoryName, prefixOfFileName + i.ToString("D10") + ".pdf");
                    splittedFiles[i - 1] = splittedFile;

                    //extract bookmarks on the page
                    IList <Dictionary <string, object> > bookmark = null;
                    if (bookmarks != null)
                    {
                        bookmark = new List <Dictionary <string, object> >(bookmarks);
                        int[] rs;
                        rs    = new int[4];
                        rs[0] = 1;
                        rs[1] = i - 1;
                        rs[2] = i + 1;
                        rs[3] = numberOfPages;
                        SimpleBookmark.EliminatePages(bookmark, rs);
                        rs    = new int[2];
                        rs[0] = rs[1] = i;
                        SimpleBookmark.ShiftPageNumbers(bookmark, 1 - i, rs);
                    }

                    using (var document = new Document(reader.GetPageSizeWithRotation(i)))
                    {
                        using (var outStream = new FileStream(splittedFile, FileMode.Create, FileAccess.Write))
                        {
                            using (var writer = new PdfCopy(document, outStream))
                            {
                                document.Open();
                                PdfImportedPage page = writer.GetImportedPage(reader, i);
                                writer.AddPage(page);
                                if (bookmark != null)
                                {
                                    writer.Outlines = bookmark;
                                }
                                writer.Close();
                            }
                            outStream.Close();
                        }
                        document.Close();
                    }
                }
                return(splittedFiles);
            }
            finally
            {
                reader.Close();
            }
        }
コード例 #30
0
        private void btnPDF_Create_Click(object sender, EventArgs e)
        {


            if (txtInput.Text == "")
            {
                MessageBox.Show("参照元PDFを選択して下さい。");
                btnInput.Focus();
                return;
            }

            if (txtOutput.Text == "")
            {
                MessageBox.Show("保存先を選択して下さい。");
                btnOutput.Focus();
                return;
            }

            DialogResult dr = MessageBox.Show("処理を開始します。よろしいですか?", "確認", MessageBoxButtons.YesNo);

            if (dr == System.Windows.Forms.DialogResult.Yes)
            {
            }
            else if (dr == System.Windows.Forms.DialogResult.No)
            {
                return;
            }
            else
            {
                return;
            }



            //コントロールを初期化する
            ProgressBar1.Minimum = 0;
            ProgressBar1.Value = 0;
            Label1.Text = "";
            //Label1を再描画する
            Label1.Update();


            // 参照元PDFファイルのオープン
            PdfReader rd = new PdfReader(txtInput.Text);

            //出力先pdf用
            PdfCopyFields oPdfcopy = null;
            Document oDocument = null;

            // ページ数を取得
            int iEND = rd.NumberOfPages;


            // しおりの情報を取得
            IList<Dictionary<string, object>> obookmarkList = SimpleBookmark.GetBookmark(rd);


            // PDFを閉じる
            rd.Close();


            int i; // カウント用変数
            string[] sTITLE = new string[obookmarkList.Count]; // しおりの件数をセット(しおり名)
            int[] iSectionStart = new int[obookmarkList.Count]; // しおりの件数をセット(しおりの開始位置)
            int[] iSectionEnd = new int[obookmarkList.Count]; // しおりの件数をセット(しおりの終了位置)
            ProgressBar1.Maximum =   obookmarkList.Count; // プログレスバーの最大値設定
            string[] sMONTH = new string[13] { "","Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; //英字変換用



            try
            {


                for (i = 0; i < obookmarkList.Count; ++i) // iをしおりの件数分、1ずつ増やして繰り返し
                {

                    // しおりの名前
                    string[] sSHIORI = ((obookmarkList[i]["Title"]).ToString()).Split('@');
                    sTITLE[i] = sSHIORI[2].ToString().Replace("CSTCNTR:", "");


                    // 開始ページ数
                    string[] sStartPage = ((obookmarkList[i]["Page"]).ToString()).Split(' ');
                    iSectionStart[i] = Convert.ToInt32(sStartPage[0]);



                    // 終了ページ数
                    int w_sEndPage;


                    int j = i;

                    do
                    {
                        if (j + 1 == obookmarkList.Count)
                        {
                            w_sEndPage = iEND;
                        }
                        else
                        {
                            string[] sEndPage = ((obookmarkList[j + 1]["Page"]).ToString()).Split(' ');  //次のしおりの開始ページを取得
                            w_sEndPage = Convert.ToInt32(sEndPage[0]);
                            j = j + 1;
                        }


                    }
                    while (iSectionStart[i] == w_sEndPage && i < obookmarkList.Count - 1 - 1); //現在のしおりの開始ページと次のしおりの開始ページが同じ時(重複時)、
                                                                                               //その次のしおりの開始ページを読み込む(ループ処理を続ける)
                                                                                               //※しかし、最終の重複時は処理を抜ける。

                    if (i + 1 == obookmarkList.Count) //最終データ

                    { iSectionEnd[i] = iEND; }

                    else if (iSectionStart[i] == w_sEndPage && i == obookmarkList.Count - 1 - 1) //最終の一つ前のデータ(しおり重複時)
                                                                                                 //※しおりカウント(obookmarkList.Count)は1から始まっているので、処理変数iの位置と合わせるために-1、
                                                                                                 //  更に最終の一つ前のデータなので、更に-1

                    { iSectionEnd[i] = iEND; }

                    else  //そのほかのデータ

                    { iSectionEnd[i] = w_sEndPage - 1; }


                }


                oDocument = new Document(rd.GetPageSizeWithRotation(1));
                oDocument.Open();

                string SHIORI_NAME = "";
                int w_SectionEnd = 0;
                int w_COUNT = 1;
                int k = 0;

                ProgressBar1.Visible = true;

                for (i = 0; i < obookmarkList.Count; ++i) // iをしおりの件数分、1ずつ増やして繰り返し
                {

                    ProgressBar1.Value = i;


                    if (sTITLE[i] == SHIORI_NAME)


                    { } //前回処理した時としおり名が一致しているとき、処理を行わない。

                    else
 
                    {
                        oPdfcopy = new PdfCopyFields(new FileStream(txtOutput.Text + "\\" + "MAN " + sMONTH[cmbMONTH.SelectedIndex + 1] + " " + cmbYEAR.SelectedItem + "_" + w_COUNT  + ".pdf", FileMode.Create));


                        k = 0;


                        //同しおり名の最後のページを記憶
                        do
                        {
                            w_SectionEnd = iSectionEnd[i + k];
                            k = k + 1;
                            if (i + k >= obookmarkList.Count - 1) { break;}
                        }
                        while (sTITLE[i] == sTITLE[i + k] );

                        
                        rd = new PdfReader(txtInput.Text);

                        rd.SelectPages(iSectionStart[i].ToString() + "-" + w_SectionEnd.ToString()); //現在のしおりの該当ページ部分を選択

                        oPdfcopy.AddDocument(rd); //PDFアウトプット
                        oPdfcopy.Close(); //pdf保存
                        rd.Close();

                        w_COUNT = w_COUNT + 1;


                        SHIORI_NAME = sTITLE[i]; //処理したしおり名を記憶しておく


                        Label1.Text = "PDF分割完了:" + "MAN " + sMONTH[cmbMONTH.SelectedIndex + 1] + " " + cmbYEAR.SelectedItem + "_" + w_COUNT + ".pdf";
                        Label1.Update();
                    }
                }

                ProgressBar1.Value = 0;
                ProgressBar1.Visible = false;
                Label1.Text = "処理完了:" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");


            }


            catch (Exception ex)
            {
                MessageBox.Show("エラー発生: " + ex.ToString());
            }


            finally
            {
                if (rd        != null) { rd.Close(); }
                if (oPdfcopy  != null) { oPdfcopy.Close(); }
                if (oDocument != null) { oDocument.Close(); }
            }

        
    }