示例#1
0
        public void Split(string inputfile)
        {
            using (PdfReader reader = new PdfReader(inputfile))
            {
                int pagecount = reader.NumberOfPages;

                if (pagecount == 1)
                {
                    Console.WriteLine("File has only one page, splitting abandoned!");
                    return;
                }

                var outputpath = FileUtilities.GetOutputPath(inputfile, Libraries.CommonUtilities.Models.ActionType.SPLIT, outputNameFormat: "{0}_Page {1}", hasMultipleOutput: true);

                for (int i = 1; i <= pagecount; i++)
                {
                    string outFile = string.Format(outputpath, Path.GetFileNameWithoutExtension(inputfile), i);

                    FileStream stream = new FileStream(outFile, FileMode.Create);

                    Document doc = new Document();
                    PdfCopy  pdf = new PdfCopy(doc, stream);

                    doc.Open();
                    PdfImportedPage page = pdf.GetImportedPage(reader, i);
                    pdf.AddPage(page);

                    pdf.Dispose();
                    doc.Dispose();

                    Console.WriteLine("Generated {0}", Path.GetFileName(outFile));
                }
            }
        }
        public void ReorderPdf(string inputFile, string outputFile, Dictionary <int, int> sortKeys)
        {
            Document  document = null;
            PdfCopy   writer   = null;
            PdfReader reader   = null;

            try
            {
                document = new Document();
                writer   = new PdfCopy(document, new FileStream(outputFile, FileMode.Create));
                if (writer == null)
                {
                    return;
                }

                document.Open();
                reader = new PdfReader(inputFile);

                CopyPages(reader, writer, sortKeys);
                CopyBookmarks(reader, writer, sortKeys);
            }
            finally
            {
                reader?.Dispose();
                writer?.Dispose();
                document?.Dispose();
            }
        }
示例#3
0
        public static void MergePDF(List <string> files, string OutFile)
        {
            LogHelper.Log("Join all files into a single PDF", LogType.Successful);

            FileStream stream = null;
            Document   doc    = null;
            PdfCopy    pdf    = null;

            try
            {
                stream = new FileStream(OutFile, FileMode.Create);
                doc    = new Document();
                pdf    = new PdfCopy(doc, stream);

                doc.Open();

                foreach (string file in files)
                {
                    LogHelper.Log($"Add the file: {file}");
                    pdf.AddDocument(new iTextSharp.text.pdf.PdfReader(file));
                }

                AddBookmarks(files, pdf);
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString(), LogType.Error);
            }
            finally
            {
                pdf?.Dispose();
                doc?.Dispose();
                stream?.Dispose();
            }
        }
示例#4
0
        public static void combinePDF(string outputFile, List <listboxPdfObjects> files)
        {
            if (files.Count > 0)
            {
                using (var fileStream = new FileStream(outputFile, FileMode.OpenOrCreate))
                {
                    Document doc     = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
                    var      pdfCopy = new PdfCopy(doc, fileStream);

                    doc.Open();

                    foreach (var pdf in files)
                    {
                        try
                        {
                            var pdfReader = new PdfReader(pdf.fullname);
                            pdfCopy.AddDocument(pdfReader);
                            pdfReader.Dispose();
                        }
                        catch (Exception e)
                        {
                        }
                    }
                    pdfCopy.Dispose();
                    doc.Dispose();
                }
            }
        }
示例#5
0
        public static void ReplaceCoverPDF(string InFile, string InCover, string OutFile)
        {
            if (CoverFunction == 0)
            {
                List <string> Files = new List <string>
                {
                    InFile,
                    InCover
                };
                Files.Sort();
                MergePDF(Files, OutFile);
                return;
            }

            LogHelper.Log("Replace the cover to the original file", LogType.Successful);

            FileStream stream = null;
            Document   doc    = null;
            PdfCopy    pdf    = null;

            try
            {
                stream = new FileStream(OutFile, FileMode.Create);
                doc    = new Document();
                pdf    = new PdfCopy(doc, stream);

                doc.Open();

                //Aggiungo la cover
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(InCover);
                int coverPage = reader.NumberOfPages;

                LogHelper.Log($"Add the cover: {InCover} of {coverPage} pages");
                pdf.AddDocument(reader);
                reader.Close();

                //Aggiungo il resto del documento
                reader = new iTextSharp.text.pdf.PdfReader(InFile);
                int count = reader.NumberOfPages;
                coverPage++;
                List <int> pages = Enumerable.Range(coverPage, count - coverPage + 1).ToList();

                LogHelper.Log($"Add the file: {InFile} from Page: {coverPage}");
                pdf.AddDocument(reader, pages);

                reader.Close();

                AddBookmarks(InFile, pdf);
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString(), LogType.Error);
            }
            finally
            {
                pdf?.Dispose();
                doc?.Dispose();
                stream?.Dispose();
            }
        }
 /// <summary>
 /// Release our resources
 /// </summary>
 public void Dispose()
 {
     if (_pdfWriter != null)
     {
         _pdfWriter.Close();
         _pdfWriter.Dispose();
         _binaryWriter.Dispose();
     }
 }
示例#7
0
        public static void SplitPDF(string InFiles, string OutDir, int PageN = 0)
        {
            string outFiles = OutDir + Path.AltDirectorySeparatorChar + Path.GetFileNameWithoutExtension(InFiles);

            LogHelper.Log($"I create the directory: {OutDir}");
            Directory.CreateDirectory(OutDir);

            LogHelper.Log("I split the file into individual PDF", LogType.Successful);

            PdfReader reader = null;

            try
            {
                reader = new PdfReader(InFiles);

                int NumPages = reader.NumberOfPages;

                int digitN = NumPages.ToString().Length;
                if (digitN < DefaultDigit)
                {
                    digitN = (int)DefaultDigit;
                }

                for (int i = 1; i <= NumPages; i++)
                {
                    if (PageN == 0 || PageN == i)
                    {
                        string     outFile = string.Format("{0}_Page {1:D" + digitN + "}.pdf", outFiles, i);
                        FileStream stream  = new FileStream(outFile, FileMode.Create);

                        LogHelper.Log($"Page: {Path.GetFileNameWithoutExtension(outFile)}");
                        Document doc = new Document();
                        PdfCopy  pdf = new PdfCopy(doc, stream);

                        doc.Open();
                        PdfImportedPage page = pdf.GetImportedPage(reader, i);
                        pdf.AddPage(page);

                        pdf.Dispose();
                        doc.Dispose();
                        stream.Dispose();
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString(), LogType.Error);
            }
            finally
            {
                reader?.Dispose();
            }
        }
示例#8
0
 public void Dispose()
 {
     if (document != null)
     {
         document.Close();
     }
     if (copy != null)
     {
         copy.CloseStream = false;
         copy.Close();
         copy.Dispose();
     }
 }
示例#9
0
        private void SetPdfPathList()
        {
            PdfReader reader   = new PdfReader(txtInputPdfFilePath.Text);
            Document  document = new Document();
            PdfCopy   copy     = null;

            PdfFilePathList = new List <string>();

            OriginalDirectoryPath = Path.GetDirectoryName(txtInputPdfFilePath.Text);

            TempDirectoryPath = Path.Combine(OriginalDirectoryPath, "PDF_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"));
            _directoryPathList.Add(TempDirectoryPath);

            OriginalFileNmae = Path.GetFileNameWithoutExtension(txtInputPdfFilePath.Text);

            Directory.CreateDirectory(TempDirectoryPath);

            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                PdfFilePathList.Add(Path.Combine(TempDirectoryPath, OriginalFileNmae) + "_" + i.ToString() + ".pdf");
                using (var fs = new FileStream(PdfFilePathList.Last(), FileMode.Create, FileAccess.Write))
                {
                    try
                    {
                        document = new Document(reader.GetPageSizeWithRotation(1));
                        copy     = new PdfCopy(document, fs);
                        document.Open();
                        copy.AddPage(copy.GetImportedPage(reader, i));
                    }
                    finally
                    {
                        document.Close();
                        copy.Close();
                    }
                }
            }

            reader.Close();

            SetNumberOfPages();
            txtPageMain.Text = "1";
            DisplayPdf();

            document.Dispose();
            copy.Dispose();
            reader.Dispose();
        }
示例#10
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                // Free any other managed objects here.
            }

            // Free any unmanaged objects here.
            try
            {
                copy.Dispose();
            }
            catch (Exception e)
            {
                logger?.LogError(e.Message);
            }

            try
            {
                stream.Dispose();
            }
            catch (Exception e)
            {
                logger?.LogError(e.Message);
            }

            try
            {
                doc.Dispose();
            }
            catch (Exception e)
            {
                logger?.LogError(e.Message);
            }

            disposed = true;
        }
示例#11
0
        /// <summary>
        /// 返回页数
        /// </summary>
        /// <param name="FileList"></param>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public int MergePDF(string[] FileList, string FileName)
        {
            if (System.IO.File.Exists(FileName))
            {
                System.IO.File.Delete(FileName);
            }
            int iPageCount = 0;

            if (FileList.Length == 1)
            {
                System.IO.File.Copy(FileList[0], FileName, true);

                /*
                 * 修改人:侯波
                 * 修改时间:2017-04-12
                 * 描述:拖入一页电子文件计算页数
                 */
                if (File.Exists(FileName))
                {
                    try
                    {
                        PdfReader reader1;
                        reader1 = new PdfReader(FileName);
                        if (reader1 != null)
                        {
                            iPageCount = reader1.NumberOfPages;
                            reader1.Close();
                            reader1.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        MyCommon.WriteLog("Cell2 MergeMultiPdf合并PDF异常:" + ex.Message);
                    }
                }
            }
            else
            {
                try
                {
                    #region 金格合并
                    //List<Stream> FSList = new List<Stream>();
                    //foreach (string file_pdf in FileList)
                    //{
                    //    FSList.Add(new FileStream(file_pdf, FileMode.Open));
                    //}
                    //using (FileStream os = new FileStream(FileName, FileMode.Create, FileAccess.ReadWrite))
                    //{
                    //    com.kinggrid.pdf.KGPdfHummerUtils.MergeMultiPdf(FSList, os);
                    //    if (System.IO.File.Exists(FileName))
                    //    {
                    //        iPageCount = MergePDFFilesPages(FileName);
                    //    }
                    //    else
                    //    {
                    //        MyCommon.WriteLog("合并PDF错误");
                    //    }
                    //}
                    #endregion

                    PdfReader reader;
                    using (iTextSharp.text.Document document = new iTextSharp.text.Document())
                    {
                        PdfImportedPage newPage;
                        PdfCopy         copy = new PdfCopy(document, (new FileStream(FileName, FileMode.Create)));
                        document.Open();
                        for (int i = 0; i < FileList.Length; i++)
                        {
                            reader = new PdfReader(FileList[i], null, true);
                            int iPageNum = reader.NumberOfPages;
                            for (int j = 1; j <= iPageNum; j++)
                            {
                                document.NewPage();
                                newPage = copy.GetImportedPage(reader, j);
                                copy.AddPage(newPage);
                            }
                            reader.Close();
                            reader.Dispose();
                        }
                        document.Close();
                        document.Dispose();
                        if (File.Exists(FileName))
                        {
                            reader = new PdfReader(FileName);
                            if (reader != null)
                            {
                                iPageCount = reader.NumberOfPages;
                                reader.Close();
                                reader.Dispose();
                            }
                        }
                        copy.Close();
                        copy.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    MyCommon.WriteLog("Cell2 MergeMultiPdf合并PDF异常:" + ex.Message);
                }
            }
            return(iPageCount);
        }
示例#12
0
        private void SplitWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            object[]        args = (object[])e.Argument;
            PdfFile         pdfFile = (PdfFile)args[0];
            PageRangeParser pageRangeParser = (PageRangeParser)args[1];
            string          destinationPath = (string)args[2];
            bool            overwriteFile = (bool)args[3];
            FileStream      outFileStream = null;
            Document        destinationDoc = null;
            PdfCopy         pdfCopy = null;
            int             skippedFiles = 0;
            string          exportFileName = string.Empty;
            string          errorMsg = string.Empty;
            int             exportFileCnt = 0, totalNumberOPages = 0, pageCnt = 0;

            EasySplitAndMergePdf.Helper.PageRange[] pageRanges = null;

            if (pageRangeParser.TryParse(out pageRanges) != Define.Success)
            {
                errorMsg = "An error occurred while parsing PDF page ranges" + pageRangeParser.ErrorMsg;
            }
            else if ((totalNumberOPages = pageRanges.Sum(range => range.PageCount)) < 1)
            {
                errorMsg = "The number of PDF pages to extract from source file is zero.";
            }
            else
            {
                pdfFile.Reader.RemoveUnusedObjects();

                while (exportFileCnt < pageRanges.Length && !splitBackgroundWorker.CancellationPending)
                {
                    exportFileName = destinationPath + (exportFileCnt + 1).ToString("D4") + ".pdf";
                    if (FileHelpers.FileIsAvailable(exportFileName, overwriteFile, out outFileStream, out errorMsg) == Define.Success)
                    {
                        destinationDoc = new Document();
                        pdfCopy        = new PdfCopy(destinationDoc, outFileStream);
                        destinationDoc.Open();

                        splitBackgroundWorker.ReportProgress(pageCnt * 100 / totalNumberOPages,
                                                             string.Format("Creating and processing PDF file: {0}", exportFileName));

                        if (pageRanges[exportFileCnt].Pages != null)
                        {
                            int pageArrayIndex = 0;
                            while (pageArrayIndex < pageRanges[exportFileCnt].Pages.Length &&
                                   !splitBackgroundWorker.CancellationPending)
                            {
                                destinationDoc.SetPageSize(pdfFile.Reader.GetPageSizeWithRotation(pageRanges[exportFileCnt].Pages[pageArrayIndex]));
                                destinationDoc.NewPage();
                                pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfFile.Reader, pageRanges[exportFileCnt].Pages[pageArrayIndex]));
                                splitBackgroundWorker.ReportProgress(++pageCnt * 100 / totalNumberOPages);
                                pageArrayIndex++;
                            }
                        }
                        else if (pageRanges[exportFileCnt].PageFrom <= pageRanges[exportFileCnt].PageTo)
                        {
                            int pageNumber = pageRanges[exportFileCnt].PageFrom;
                            while (pageNumber <= pageRanges[exportFileCnt].PageTo &&
                                   !splitBackgroundWorker.CancellationPending)
                            {
                                destinationDoc.SetPageSize(pdfFile.Reader.GetPageSizeWithRotation(pageNumber));
                                destinationDoc.NewPage();
                                pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfFile.Reader, pageNumber));
                                splitBackgroundWorker.ReportProgress(++pageCnt * 100 / totalNumberOPages);
                                pageNumber++;
                            }
                        }
                        else if (pageRanges[exportFileCnt].PageFrom > pageRanges[exportFileCnt].PageTo)
                        {
                            int pageNumber = pageRanges[exportFileCnt].PageFrom;
                            while (pageNumber >= pageRanges[exportFileCnt].PageTo &&
                                   !splitBackgroundWorker.CancellationPending)
                            {
                                destinationDoc.SetPageSize(pdfFile.Reader.GetPageSizeWithRotation(pageNumber));
                                destinationDoc.NewPage();
                                pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfFile.Reader, pageNumber));
                                splitBackgroundWorker.ReportProgress(++pageCnt * 100 / totalNumberOPages);
                                pageNumber--;
                            }
                        }

                        //Exception on document.Close() when doc is empty
                        //if (pages.Count == 0) { throw new IOException("The document has no pages.") };
                        //When canceling pages.Count could be zero therefore skip cleanup.
                        if (destinationDoc != null &&
                            !splitBackgroundWorker.CancellationPending)
                        {
                            destinationDoc.Close();
                            destinationDoc.Dispose();
                            destinationDoc = null;
                        }

                        if (pdfCopy != null &&
                            !splitBackgroundWorker.CancellationPending)
                        {
                            pdfCopy.Close();
                            pdfCopy.Dispose();
                            pdfCopy = null;
                        }

                        if (outFileStream != null)
                        {
                            outFileStream.Close();
                            outFileStream.Dispose();
                            outFileStream = null;
                        }
                    }
                    else
                    {
                        skippedFiles++;
                        Debug.WriteLine(string.Format("File: {0}, error: {1}", exportFileName, errorMsg));
                    }
                    exportFileCnt++;
                }
            }

            if (string.IsNullOrEmpty(errorMsg) &&
                exportFileCnt == pageRanges.Length &&
                skippedFiles == 0)
            {
                errorMsg = string.Format("Successfully created {0} PDF export files.", pageRanges.Length);
            }
            else if (skippedFiles > 0)
            {
                errorMsg = string.Format("Created {0} PDF export files, skipped {1} PDF files.",
                                         pageRanges.Length - skippedFiles, skippedFiles);
            }

            if (splitBackgroundWorker.CancellationPending)
            {
                e.Cancel = true;
            }

            e.Result = errorMsg;
        }