Пример #1
1
        //srcで指定されたPDFファイルをページ毎に分割し、destで指定されたパスに保存する。
        //保存ファイル名は「ファイル名-ページ番号.pdf」とする。
        //分割したページ数を返す。
        public List<string> Run(string src, string dest)
        {
            // srcで渡されたファイルが存在するか?
            if (!File.Exists(src))
            {
                throw new FileNotFoundException();
            }

            // destで渡されたフォルダが存在するか?
            if (!Directory.Exists(dest))
            {
                throw new DirectoryNotFoundException();
            }

            var reader = new iTextSharp.text.pdf.PdfReader(src);
            string file_name = Path.GetFileNameWithoutExtension(src);
            int digit = reader.NumberOfPages.ToString().Length;
            var app_name = new MainForm();

            // 一時フォルダにpdfを作成してdestにコピー。
            // その際上書き確認を行う。
            System.IO.DirectoryInfo del = new System.IO.DirectoryInfo(Path.GetTempPath() + "\\" + app_name.Text);
            if (del.Exists) del.Delete(true);
            System.IO.DirectoryInfo tmp = new System.IO.DirectoryInfo(Path.GetTempPath() + "\\" + app_name.Text);
            tmp.Create();
            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                var doc = new iTextSharp.text.Document();
                var dest_tmp = String.Format(@"{{0}}\{{1}}-{{2:D{0}}}.pdf", digit);
                var dest_name = String.Format(dest_tmp, tmp, file_name, i);
                var copy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(dest_name, FileMode.Create));

                doc.Open();
                copy.AddPage(copy.GetImportedPage(reader, i));
                doc.Close();
            }

            // コピーしたファイルを監視する
            Ret.list.Clear();
            var watcher = new System.IO.FileSystemWatcher();
            watcher.Path = dest;
            watcher.Filter = "*.pdf";
            watcher.Changed += new FileSystemEventHandler(changed);
            watcher.Created += new FileSystemEventHandler(changed);

            watcher.EnableRaisingEvents = true;
            FileSystem.CopyDirectory(tmp.ToString(), dest, UIOption.AllDialogs);
            watcher.EnableRaisingEvents = false;
            watcher.Dispose();
            watcher = null;

            tmp.Delete(true);
            reader.Close();

            return Ret.list;
        }
        private System.IO.MemoryStream joinTwoStreamsIntoOnePdf(System.IO.MemoryStream stream_1, System.IO.MemoryStream stream_2)
        {
            System.IO.MemoryStream dest_stream = null;
            try
            {
                dest_stream = new System.IO.MemoryStream();

                var doc    = new iTextSharp.text.Document();
                var writer = new iTextSharp.text.pdf.PdfCopy(doc, dest_stream);
                doc.Open();

                var reader_1 = new iTextSharp.text.pdf.PdfReader(stream_1.ToArray());
                for (var i = 1; i <= reader_1.NumberOfPages; i++)
                {
                    var page = writer.GetImportedPage(reader_1, i);
                    writer.AddPage(page);
                }
                reader_1.Close();

                var reader_2 = new iTextSharp.text.pdf.PdfReader(stream_2.ToArray());
                for (var i = 1; i <= reader_2.NumberOfPages; i++)
                {
                    var page = writer.GetImportedPage(reader_2, i);
                    writer.AddPage(page);
                }
                reader_2.Close();
                doc.Close();
            }
            catch (Exception excpt)
            {
                System.Diagnostics.Debug.WriteLine(excpt);
            }
            return(dest_stream);
        }
        private System.IO.MemoryStream extractPagesFromPerfectBindStream(System.IO.MemoryStream orig_stream,
                                                                         int start_page = 1, int end_page = 1)
        {
            System.IO.MemoryStream dest_stream = null;
            try
            {
                dest_stream = new System.IO.MemoryStream();

                var doc    = new iTextSharp.text.Document();
                var writer = new iTextSharp.text.pdf.PdfCopy(doc, dest_stream);
                doc.Open();

                var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray());
                for (var i = start_page; i <= end_page; i++)
                {
                    var page = writer.GetImportedPage(reader, i);
                    writer.AddPage(page);
                }

                reader.Close();
                doc.Close();
            }
            catch (Exception excpt)
            {
                System.Diagnostics.Debug.WriteLine(excpt);
            }
            return(dest_stream);
        }
        private System.IO.MemoryStream reorderSaddleStitchBrief(System.IO.MemoryStream orig_stream)
        {
            System.IO.MemoryStream dest_stream = null;
            try
            {
                dest_stream = new System.IO.MemoryStream();



                var reader = new iTextSharp.text.pdf.PdfReader(orig_stream.ToArray());
                var order  = new SaddleStitchPageOrder(reader.NumberOfPages);
                reader.SelectPages(order.PageOrder);
                var pdfdoc           = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
                var pdfcopy_provider = new iTextSharp.text.pdf.PdfCopy(pdfdoc, dest_stream);
                pdfdoc.Open();
                iTextSharp.text.pdf.PdfImportedPage importedPage;
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    importedPage = pdfcopy_provider.GetImportedPage(reader, i);
                    pdfcopy_provider.AddPage(importedPage);
                }
                pdfdoc.Close();
                reader.Close();
            }
            catch (Exception excpt)
            {
                System.Diagnostics.Debug.WriteLine(excpt);
            }
            return(dest_stream);
        }
Пример #5
0
        public static bool SaddleStitch_ReorderPagesForLayout(string src)
        {
            string dest = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(src), "ss brief reordered.pdf");

            try
            {
                using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create))
                {
                    iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(src);
                    SaddleStitchPageOrder         order  = new SaddleStitchPageOrder(reader.NumberOfPages);
                    reader.SelectPages(order.PageOrder);
                    iTextSharp.text.Document    pdfdoc           = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
                    iTextSharp.text.pdf.PdfCopy pdfcopy_provider = new iTextSharp.text.pdf.PdfCopy(pdfdoc, stream);
                    pdfdoc.Open();
                    iTextSharp.text.pdf.PdfImportedPage importedPage;
                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        importedPage = pdfcopy_provider.GetImportedPage(reader, i);
                        pdfcopy_provider.AddPage(importedPage);
                    }
                    pdfdoc.Close();
                    reader.Close();
                }
                System.IO.File.Delete(src);
                System.IO.File.Move(dest, src);
                return(true);
            }
            catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); return(false); }
        }
Пример #6
0
        private void createCombinedPdf_iTextSharp(List <string> InFiles, string OutFile)
        {
            try
            {
                using (var stream = new System.IO.FileStream(OutFile, System.IO.FileMode.Create))
                    using (var doc = new iTextSharp.text.Document())
                        using (var pdf = new iTextSharp.text.pdf.PdfCopy(doc, stream))
                        {
                            doc.Open();

                            iTextSharp.text.pdf.PdfReader       reader = null;
                            iTextSharp.text.pdf.PdfImportedPage page   = null;

                            //fixed typo
                            InFiles.ForEach(file =>
                            {
                                reader = new iTextSharp.text.pdf.PdfReader(file);

                                for (int i = 0; i < reader.NumberOfPages; i++)
                                {
                                    page = pdf.GetImportedPage(reader, i + 1);
                                    pdf.AddPage(page);
                                }

                                pdf.FreeReader(reader);
                                reader.Close();
                                System.IO.File.Delete(file);
                            });
                        }
            }
            catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); }
        }
Пример #7
0
        public void ExtractPage(string sourcePdfPath, string outputPdfPath, int pageNumber, int pageend)
        {
            iTextSharp.text.pdf.PdfReader       reader          = null;
            iTextSharp.text.Document            document        = null;
            iTextSharp.text.pdf.PdfCopy         pdfCopyProvider = null;
            iTextSharp.text.pdf.PdfImportedPage importedPage    = null;

            try
            {
                // Intialize a new PdfReader instance with the contents of the source Pdf file:
                reader = new iTextSharp.text.pdf.PdfReader(sourcePdfPath);

                // Capture the correct size and orientation for the page:
                document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(pageNumber));

                // Initialize an instance of the PdfCopyClass with the source
                // document and an output file stream:
                pdfCopyProvider = new iTextSharp.text.pdf.PdfCopy(document,
                                                                  new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));

                document.Open();

                // Extract the desired page number:
                if (pageNumber == pageend)
                {
                    importedPage = pdfCopyProvider.GetImportedPage(reader, pageNumber + 1);
                    pdfCopyProvider.AddPage(importedPage);
                }
                else
                {
                    for (int i = pageNumber; i <= pageend; i++)
                    {
                        importedPage = pdfCopyProvider.GetImportedPage(reader, i + 1);
                        pdfCopyProvider.AddPage(importedPage);
                    }
                }

                document.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                _arCommonService.CreateErrorLog(ex.Message, ex.StackTrace);
            }
        }
Пример #8
0
        private void SaveFile(int desde)
        {
            if (CDPSession.Current.File == null)
            {
                return;
            }

            var pageCount   = GetPageCount();
            var currentPage = 1;

            CDPSession.Current.File.InputStream.Position = 0;

            using (var ms = new MemoryStream())
            {
                CDPSession.Current.File.InputStream.CopyTo(ms);
                var reader = new iTextSharp.text.pdf.PdfReader(ms.ToArray());

                for (var i = 1; i <= pageCount; i++)
                {
                    var newFile = string.Format("{0}{1}.pdf", _folder, desde);
                    var doc     = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage));
                    var pdfCpy  = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(newFile, System.IO.FileMode.Create));

                    doc.Open();
                    for (var j = 1; j <= 4; j++)
                    {
                        iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader, currentPage);
                        //pdfCpy.SetFullCompression();
                        pdfCpy.AddPage(page);
                        currentPage += 1;
                    }

                    desde++;
                    doc.Close();
                    pdfCpy.Close();
                }

                reader.Close();
            }
        }
Пример #9
0
        public void splitPdfByPages(String sourcePdf, int numOfPages, string baseNameOutPdf)
        {
            int    pageCount  = 0;
            string path       = Path.GetFullPath(sourcePdf);
            string separtator = "_";
            string extension  = ".pdf";

            try
            {
                raf       = new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);
                reader    = new iTextSharp.text.pdf.PdfReader(raf, null);
                pageCount = reader.NumberOfPages;
                if (pageCount < numOfPages)
                {
                    MessageBox.Show("Nie ma co dzielić");
                }
                else
                {
                    string counter;
                    string ext         = System.IO.Path.GetExtension(baseNameOutPdf);
                    string outfile     = string.Empty;
                    double m           = pageCount / numOfPages;
                    int    n           = (int)Math.Ceiling(m);
                    int    currentPage = 1;
                    string thename     = Path.GetFileNameWithoutExtension(sourcePdf);
                    string name        = Path.GetFileName(sourcePdf);
                    for (int i = 1; i <= pageCount; i++)
                    {
                        if (i < 10)
                        {
                            counter = "00";
                        }
                        else
                        {
                            counter = "0";
                        }
                        outfile = path.Replace(name, "") + thename + separtator + counter + i + extension;
                        doc     = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage));
                        pdfCpy  = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.Create));
                        doc.Open();
                        if (i < n)
                        {
                            for (int j = 1; j <= numOfPages; j++)
                            {
                                page = pdfCpy.GetImportedPage(reader, currentPage);
                                pdfCpy.AddPage(page);
                                currentPage += 1;
                            }
                        }
                        else
                        {
                            for (int j = currentPage; j <= pageCount; j++)
                            {
                                page = pdfCpy.GetImportedPage(reader, j);
                                pdfCpy.AddPage(page);
                            }
                        }
                        doc.Close();
                        Console.Beep();
                    }
                }
                reader.Close();
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        public string ReorderBookmarks()
        {
            string result = "";

            iTextSharp.text.pdf.PdfReader reader;
            string tempSavePath;

            System.IO.FileStream                 fs;
            iTextSharp.text.Document             document;
            iTextSharp.text.pdf.PdfCopy          copier;
            IList <Dictionary <string, object> > bookmarkList;
            Bookmark firstBookmark;
            SortedList <long, Bookmark> byStartPages;
            SortedList <long, Bookmark> byIndexNumbers;
            Bookmark thisBookmark;
            Bookmark previousBookmark;
            long     totalPages;
            long     currentPages;
            IList <Dictionary <string, object> > newBookmarkList;

            // check to see if file is open by another process
            string quickCheck = System.IO.Path.GetDirectoryName(path) + "\\~" + System.IO.Path.GetFileNameWithoutExtension(path) + System.IO.Path.GetExtension(path);
            long   safeNumber = 1;

            while (System.IO.File.Exists(quickCheck))
            {
                quickCheck  = System.IO.Path.GetDirectoryName(path) + "\\~" + System.IO.Path.GetFileNameWithoutExtension(path) + "(" + safeNumber + ")" + System.IO.Path.GetExtension(path);
                safeNumber += 1;
            }
            bool isSafe = false;

            while (!isSafe)
            {
                try
                {
                    System.IO.File.Move(path, quickCheck);
                    System.IO.File.Move(quickCheck, path);
                    isSafe = true;
                }
                catch
                {
                    System.Windows.Forms.MessageBoxButtons buttons    = System.Windows.Forms.MessageBoxButtons.OKCancel;
                    System.Windows.Forms.DialogResult      diagResult = System.Windows.Forms.MessageBox.Show(path + " is being used by another process. Please close that process and click Ok.", "File in Use", buttons);
                    if (diagResult == System.Windows.Forms.DialogResult.Cancel)
                    {
                        result = "File in use.";
                        return(result);
                    }
                }
            }

            // initalizing reader
            reader       = new iTextSharp.text.pdf.PdfReader(path);
            bookmarkList = iTextSharp.text.pdf.SimpleBookmark.GetBookmark(reader);
            totalPages   = reader.NumberOfPages;

            // empty bookmark list
            if (bookmarkList == null)
            {
                reader.Close();
                System.Windows.Forms.MessageBox.Show("No bookmarks detected.");
                result = "Error";
                return(result);
            }

            // get all bookmarks and add them to a list sorted by start pages and another list sorted by index numbers
            byStartPages   = new SortedList <long, Bookmark>();
            byIndexNumbers = new SortedList <long, Bookmark>();
            long index = 0;

            AddBookmarkToSortedLists(bookmarkList, byStartPages, byIndexNumbers, index);

            // get end pages
            previousBookmark = null;
            foreach (KeyValuePair <long, Bookmark> element in byStartPages)
            {
                if (previousBookmark == null)
                {
                    previousBookmark = element.Value;
                }
                else
                {
                    previousBookmark.SetEndPage(element.Key - 1);
                    previousBookmark = element.Value;
                }
                element.Value.SetPriority(GetPriorityFromList(priorityList, element.Value.GetName()));
            }
            previousBookmark.SetEndPage(totalPages);

            // sort bookmarks by priority or sort by index
            if (prioritizeBookmarks)
            {
                firstBookmark = ReorderNodesByPriority(byIndexNumbers);
            }
            else
            {
                firstBookmark = ReorderNodesByIndex(byIndexNumbers);
            }

            // create a new pdf document
            newBookmarkList = new List <Dictionary <string, object> >();
            tempSavePath    = System.IO.Path.GetDirectoryName(path) + "\\" + System.IO.Path.GetFileNameWithoutExtension(path) + " - Sorted.pdf";
            long saveCount = 0;

            while (System.IO.File.Exists(tempSavePath))
            {
                saveCount++;
                tempSavePath = System.IO.Path.GetDirectoryName(path) + "\\" + System.IO.Path.GetFileNameWithoutExtension(path) + " - Sorted(" + saveCount + ").pdf";
            }
            fs       = new System.IO.FileStream(tempSavePath, System.IO.FileMode.Create);
            document = new iTextSharp.text.Document();
            copier   = new iTextSharp.text.pdf.PdfCopy(document, fs);
            document.Open();
            thisBookmark = firstBookmark;
            currentPages = 0;
            long firstBookmarkedPage = byStartPages.ElementAt(0).Key;

            if (firstBookmarkedPage > 1)
            {
                for (int i = 1; i < firstBookmarkedPage; i++)
                {
                    copier.AddPage(copier.GetImportedPage(reader, i));
                    currentPages++;
                }
            }
            while (thisBookmark != null)
            {
                int startPage = (int)thisBookmark.GetStartPage();
                int endPage   = (int)thisBookmark.GetEndPage();
                for (int i = startPage; i <= endPage; i++)
                {
                    copier.AddPage(copier.GetImportedPage(reader, i));
                }
                if (startPage != currentPages + 1)
                {
                    thisBookmark.ChangePage(currentPages + 1);
                }
                currentPages += (endPage - startPage) + 1;
                newBookmarkList.Add(thisBookmark.GetDictionary());
                thisBookmark = thisBookmark.GetNextNode();
            }
            copier.Outlines = newBookmarkList;
            copier.Close();
            document.Close();
            fs.Close();
            reader.Close();

            reader = new iTextSharp.text.pdf.PdfReader(path);
            IList <Dictionary <string, object> > currentBookmarkList = iTextSharp.text.pdf.SimpleBookmark.GetBookmark(reader);

            reader.Close();

            // delete original and rename sorted file to original name
            if (totalPages != currentPages)
            {
                result = "The number of pages in the new document(s) does not match the number of pages in the old document. Aborting overwrite.";
                return(result);
            }
            if (bookmarkList.Count != currentBookmarkList.Count)
            {
                result = "Bookmark count of original file does not match bookmark count of file being replaced. Aborting overwrite.";
                return(result);
            }
            try
            {
                System.IO.File.Delete(path);
                System.IO.File.Move(tempSavePath, path);
            }
            catch
            {
                result = "Could not overwrite. Sorted bookmarks saved as " + tempSavePath;
            }

            return(result);
        }