public ImposeSingleTypesetPdf(System.IO.MemoryStream orig_mem_stream, TypeOfBindEnum bind_type, bool hasCover)
 {
     // initialize properties
     BindType = bind_type;
     HasCover = hasCover;
     if (HasCover)
     {
         LengthOfCover = PdfCropAndNUp.StaticUtils.GetCoverLength_FirstPageTypesetPdf(orig_mem_stream);
     }
     // run imposition
     carryOutImposition(orig_mem_stream);
 }
        public ImposeSingleTypesetPdf(CockleFilePdf imposeReadyCocklePdf, TypeOfBindEnum bind_type, bool hasCover)
        {
            // interrupt if file doesn't exist
            if (!System.IO.File.Exists(imposeReadyCocklePdf.FullName))
            {
                return;
            }

            // convert to stream
            System.IO.MemoryStream orig_mem_stream;
            using (var fs = new System.IO.FileStream(imposeReadyCocklePdf.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                orig_mem_stream = new System.IO.MemoryStream();
                fs.CopyTo(orig_mem_stream);
            }
            if (null == orig_mem_stream)
            {
                return;
            }

            // initialize properties
            OrigCockleReadyFile = imposeReadyCocklePdf;
            BindType            = bind_type;
            HasCover            = hasCover;
            if (HasCover)
            {
                if (null != OrigCockleReadyFile.CoverLength)
                {
                    LengthOfCover = OrigCockleReadyFile.CoverLength;
                }
                else
                {
                    LengthOfCover = PdfCropAndNUp.StaticUtils.GetCoverLength_FirstPageTypesetPdf(OrigCockleReadyFile.FullName);
                }
            }
            // run imposition
            carryOutImposition(orig_mem_stream);
        }
示例#3
0
        public ImposeFullConvertedTicket(
            string folder,
            List <CockleFilePdf>
            converted_files,
            int lenOfCover,
            TypeOfBindEnum bind_type)
        {
            // interrupt if no folder, or inconsistent file information
            if (string.IsNullOrEmpty(folder) || converted_files.Count == 0)
            {
                return;
            }

            // set properties
            Attorney = converted_files[0].Attorney;
            Ticket   = converted_files[0].TicketNumber;

            // make sure same Attorney & Ticket for all files
            if (!converted_files.TrueForAll(f => f.Attorney.Equals(Attorney) && f.TicketNumber == Ticket))
            {
                return;
            }

            // initialize properties
            FolderPath          = folder;
            LengthOfCover       = lenOfCover;
            ConvertedFiles      = converted_files;
            ImposedFilesCreated = new List <CockleFilePdf>();

            // get page ranges for app files
            ConvertedFiles.ForEach(f =>
            {
                if (f.FileType == SourceFileTypeEnum.App_File && f.PageRange == null)
                {
                    f.GetPageRangeForFile();
                }
            });

            // get non foldout files
            var nonFoldouts = ConvertedFiles
                              .Where(f =>
                                     f.FileType != SourceFileTypeEnum.App_Foldout ||
                                     f.FileType != SourceFileTypeEnum.App_ZFold ||
                                     f.FileType != SourceFileTypeEnum.Brief_Foldout ||
                                     f.FileType != SourceFileTypeEnum.Brief_ZFold ||
                                     f.FileType != SourceFileTypeEnum.Certificate_of_Service ||
                                     f.FileType != SourceFileTypeEnum.SidewaysPage ||
                                     f.FileType != SourceFileTypeEnum.Unrecognized)
                              .OrderBy(f => f.FileType);

            // get foldout files
            var foldouts = ConvertedFiles.Where(f =>
                                                f.FileType == SourceFileTypeEnum.App_Foldout ||
                                                f.FileType == SourceFileTypeEnum.App_ZFold ||
                                                f.FileType == SourceFileTypeEnum.Brief_Foldout ||
                                                f.FileType == SourceFileTypeEnum.Brief_ZFold);

            // get page numbers for foldout pages
            List <int> foldout_page_nums = new List <int>();

            if (foldouts.Count() > 0)
            {
                foldouts.ToList().ForEach(f =>
                {
                    f.GetPageRangeForFile();
                });
            }

            // get total page count
            int page_count = 0;

            ConvertedFiles.ForEach(f =>
            {
                using (iTextSharp.text.pdf.PdfReader r = new iTextSharp.text.pdf.PdfReader(f.FullName))
                { page_count += r.NumberOfPages; }
            });
            TotalPageCount = page_count;

            // set bind type
            switch (bind_type)
            {
            case TypeOfBindEnum.ProgramDecidesByPageCount:
                if (foldouts.Count() == 0 && page_count <= 65)
                {
                    SaddleStitch = true; BindType = TypeOfBindEnum.SaddleStitch;
                }
                else
                {
                    SaddleStitch = false; BindType = TypeOfBindEnum.PerfectBind;
                }
                break;

            case TypeOfBindEnum.SaddleStitch:
                SaddleStitch = true; BindType = TypeOfBindEnum.SaddleStitch;
                break;

            case TypeOfBindEnum.PerfectBind:
                SaddleStitch = false; BindType = TypeOfBindEnum.PerfectBind;
                break;
            }

            // impose files
            // saddle stitch: enforce that document has a cover: without cover, could get unreliable results
            if (BindType == TypeOfBindEnum.SaddleStitch && (nonFoldouts?.ToList()).Any(x => x.FileType == SourceFileTypeEnum.Cover))
            {
                var impose = new ImposeSaddleStitch(
                    FolderPath, nonFoldouts, LengthOfCover, BindType, Ticket, Attorney);

                // keep track of files created
                foreach (var f in impose.NewFilesCreated)
                {
                    ImposedFilesCreated.Add(f);
                }
            }
            else if (BindType == TypeOfBindEnum.PerfectBind)
            {
                var impose = new ImposePerfectBind(
                    FolderPath,
                    nonFoldouts, foldouts,
                    LengthOfCover, BindType, Ticket, Attorney);

                // keep track of files created
                foreach (var f in impose.NewFilesCreated)
                {
                    ImposedFilesCreated.Add(f);
                }
            }
        }
        /// <summary>
        /// Constructor invoked on auto creation of files.
        /// </summary>
        /// <param name="src"></param>
        /// <param name="list"></param>
        /// <param name="cvLen"></param>
        /// <param name="bind"></param>
        /// <param name="ticket"></param>
        /// <param name="atty"></param>
        public ImposeSaddleStitch(
            string src,
            IOrderedEnumerable <CockleFilePdf> list,
            int cvLen,
            TypeOfBindEnum bind,
            int?ticket,
            string atty)
        {
            SourceFolder    = src;
            ImposedFiles    = new List <CockleFilePdf>(list);
            TypeOfBind      = bind;
            CoverLength     = cvLen;
            PageCountOfBody = 0;
            NewFilesCreated = new List <CockleFilePdf>();

            // get total page count
            ImposedFiles.ForEach(f =>
            {
                using (PdfReader r = new PdfReader(f.FullName))
                {
                    PageCountOfBody += r.NumberOfPages;
                }
            });
            if (PageCountOfBody == 0)
            {
                PageCountOfBody = null;
            }

            // create folder for processed files
            ProcessedFolder = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(SourceFolder, "processed"));

            // create new file names
            NewFileNames = new Dictionary <string, string>
            {
                { "Cover", System.IO.Path.Combine(ProcessedFolder.FullName, "Cover.pdf") },
                { "Brief", System.IO.Path.Combine(ProcessedFolder.FullName, "Brief.pdf") },
                { "Combined", System.IO.Path.Combine(ProcessedFolder.FullName, "Combined.pdf") },
                { "FinalVersion", System.IO.Path.Combine(SourceFolder, string.Format(
                                                             "{0} {1} cv{2}{3}br{4}{5}B4 pr.pdf", ticket, atty,
                                                             ImposedFiles.Any(x => x.FileType == SourceFileTypeEnum.InsideCv) ? " icv " : " ",
                                                             ImposedFiles.Any(x => x.FileType == SourceFileTypeEnum.Motion) ? " brmo " : " ",
                                                             ImposedFiles.Any(x => x.FileType == SourceFileTypeEnum.App_Index) ? " ain " : " ",
                                                             ImposedFiles.Any(x => x.FileType == SourceFileTypeEnum.App_File) ? " app " : " ")
                                                         .Replace("  ", " ")) },
                { "FinalVersionWithOnlyCover", System.IO.Path.Combine(SourceFolder, string.Format("{0} {1} cv B4 pr.pdf", ticket, atty)) }
            };

            bool hasCover = ImposedFiles.Any(f => f.FileType == SourceFileTypeEnum.Cover);

            if (hasCover)
            {
                ImposeCover(ImposedFiles, NewFileNames["Cover"]);
            }

            bool hasOnlyCover = true;

            ImposedFiles.ForEach(f => { if (f.FileType != SourceFileTypeEnum.Cover)
                                        {
                                            hasOnlyCover = false;
                                        }
                                 });
            if (!hasOnlyCover)
            {
                ImposeBrief(ImposedFiles, NewFileNames["Brief"], TypeOfBind);
            }

            // COMBINE COVER WITH BRIEF
            try
            {
                if (hasCover && !hasOnlyCover)
                {
                    if (!combinedImposedCoverAndBrief(NewFileNames["Brief"], NewFileNames["Cover"], NewFileNames["Combined"]))
                    {
                        System.Diagnostics.Debug.WriteLine("Failure here!");
                    }
                }
            }
            catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); }

            // copy file to main folder
            try
            {
                if (System.IO.File.Exists(NewFileNames["FinalVersion"]))
                {
                    System.IO.File.Delete(NewFileNames["FinalVersion"]);
                }
                //File.Copy(NewFileNames["Combined"], NewFileNames["FinalVersion"], true);

                // open, save, close with acrobat
                AcroApp   _myAdobe = new Acrobat.AcroApp();
                AcroAVDoc _acroDoc = new AcroAVDoc();

                CAcroPDDoc _pdDoc = null;
                if (hasOnlyCover)
                {
                    _acroDoc.Open(NewFileNames["Cover"], null);
                    _pdDoc = (Acrobat.AcroPDDoc)(_acroDoc.GetPDDoc());
                    _pdDoc.Save(1, NewFileNames["FinalVersionWithOnlyCover"]);

                    // keep track of files created
                    NewFilesCreated.Add(new CockleFilePdf(
                                            NewFileNames["FinalVersionWithOnlyCover"], atty, ticket, SourceFileTypeEnum.Imposed_Cover, ""));
                }
                else
                {
                    _acroDoc.Open(NewFileNames["Combined"], null);
                    _pdDoc = (Acrobat.AcroPDDoc)(_acroDoc.GetPDDoc());
                    _pdDoc.Save(1, NewFileNames["FinalVersion"]);

                    // keep track of files created
                    NewFilesCreated.Add(new CockleFilePdf(
                                            NewFileNames["FinalVersion"], atty, ticket, SourceFileTypeEnum.Imposed_Cover_and_Brief, ""));
                }
                _pdDoc.Close();
                _acroDoc.Close(0);
                _myAdobe.Exit();
            }
            catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); }

            // attempt to delete processed folder
            try { ProcessedFolder.Delete(true); }
            catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); }
        }
        private bool ImposeBrief(List <CockleFilePdf> imposedFiles, string imposedBody, TypeOfBindEnum bind)
        {
            // remove cover, combine body, and add blank pages where needed
            PdfUtilities.CombineBriefPages_AddingBlanks(imposedFiles, imposedBody, bind);

            if (// reorder saddlestitch pages
                !PdfUtilities.SaddleStitch_ReorderPagesForLayout(imposedBody) ||
                // crop pages
                !PdfUtilities.CropCockleBriefPages(imposedBody) ||
                // layout on B4 pages
                !PdfUtilities.SaddleStitch_LayoutCroppedBrief(imposedBody))
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
示例#6
0
        public static bool CombineBriefPages_AddingBlanks(
            List <CockleFilePdf> srcFiles, string src, TypeOfBindEnum bind)
        {
            // new attempt Dec 28, to account for divider pages (or any page without text)
            // text has to start on odd-numbered page, if followed by divider page

            // first, add 2 pages for each divider page, to account for front and back.
            // then, when everything is together, cycle through doc to add extra dividers...
            // ... so that text always falls on odd-numbered page


            // should work for both Saddle Stitch and Perfect Bind


            // create new list without cover, ordered by rank
            List <CockleFilePdf> files = new List <CockleFilePdf>(
                srcFiles
                .Where(f => f.FileType != SourceFileTypeEnum.Cover)
                .Where(f => f.FileType != SourceFileTypeEnum.InsideCv)
                .Where(f => f.FileType != SourceFileTypeEnum.SidewaysPage)
                .Where(f => f.FileType != SourceFileTypeEnum.Brief_Foldout)
                .Where(f => f.FileType != SourceFileTypeEnum.Brief_ZFold)
                .Where(f => f.FileType != SourceFileTypeEnum.App_Foldout)
                .Where(f => f.FileType != SourceFileTypeEnum.App_ZFold)
                .Where(f => f.FileType != SourceFileTypeEnum.Unrecognized)
                .OrderBy(f => f.Rank));

            if (files.Count < 1)
            {
                return(false);
            }

            // what if files.Count == 1 ??? just return ???

            int  pageCount         = 0;
            bool hasDividers       = false;
            bool firstAppFileFound = false;
            int  firstPageOfApp    = -1;

            try
            {
                using (var stream = new System.IO.FileStream(src, System.IO.FileMode.Create))
                {
                    // initiate iTextSharp processes
                    iTextSharp.text.Document    pdfdoc  = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER);
                    iTextSharp.text.pdf.PdfCopy pdfcopy = new iTextSharp.text.pdf.PdfCopy(pdfdoc, stream);
                    pdfdoc.Open();

                    // merge pdfs in folder
                    CockleFilePdf f;
                    for (int i = 0; i < files.Count; i++)
                    {
                        f = files[i];
                        // read file
                        iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(f.FullName);
                        int filePageCount = reader.NumberOfPages;

                        // set up pdfstamper
                        iTextSharp.text.pdf.PdfStamper stamper = new iTextSharp.text.pdf.PdfStamper(reader, stream);

                        // look for divider pages here, add blank if exists
                        List <int> divider_pages = new List <int>();
                        iTextSharp.text.pdf.parser.PdfReaderContentParser parser = new iTextSharp.text.pdf.parser.PdfReaderContentParser(reader);
                        for (int j = 1; j <= reader.NumberOfPages; j++)
                        {
                            iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy extract = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                            var    extractedText = parser.ProcessContent(j, extract);
                            string textFromPage  = extractedText.GetResultantText();

                            int cnt     = textFromPage.ToCharArray().Count();
                            int mch_cnt = System.Text.RegularExpressions.Regex.Matches(textFromPage, @"A(PPENDIX|ppendix)").Count;

                            if (System.Text.RegularExpressions.Regex.Matches(textFromPage, @"\S").Count == 0)
                            {
                                // collect blank pages
                                divider_pages.Add(j);
                            }
                            else if (cnt < 50 && mch_cnt > 0)
                            {
                                // collect other divider pages
                                divider_pages.Add(j);
                            }
                        }
                        if (divider_pages.Count > 0)
                        {
                            hasDividers = true;

                            int k = 0; // adjust for total page number change
                            foreach (int page in divider_pages)
                            {
                                stamper.InsertPage(page + k, reader.GetPageSizeWithRotation(1));
                                filePageCount = reader.NumberOfPages;
                                k++;
                            }
                        }

                        // add blank page if needed to make even number
                        if (files[i].FileType == SourceFileTypeEnum.Index ||
                            files[i].FileType == SourceFileTypeEnum.Brief ||
                            files[i].FileType == SourceFileTypeEnum.App_Index ||
                            files[i].FileType == SourceFileTypeEnum.Motion ||
                            files[i].FileType == SourceFileTypeEnum.Divider_Page)
                        {
                            f.AssignNeedsBlankPage(files, reader.NumberOfPages);
                            if (f.NeedsBlankPage)
                            {
                                //PdfStamper stamper2 = new PdfStamper(reader, stream);
                                stamper.InsertPage(reader.NumberOfPages + 1, reader.GetPageSizeWithRotation(1));
                                filePageCount = reader.NumberOfPages;
                            }
                        }

                        // with last document in 'files', add extra pages to make divisible by 4
                        if (bind == TypeOfBindEnum.SaddleStitch && i == files.Count - 1)
                        {
                            if (bind == TypeOfBindEnum.SaddleStitch &&
                                (pageCount + reader.NumberOfPages) % 4 != 0)
                            {
                                //PdfStamper stamper3 = new PdfStamper(reader, stream);
                                while ((pageCount + reader.NumberOfPages) % 4 != 0)
                                {
                                    stamper.InsertPage(reader.NumberOfPages + 1, reader.GetPageSizeWithRotation(1));
                                }
                            }
                        }

                        // get first page of first app file
                        if (!firstAppFileFound && files[i].FileType == SourceFileTypeEnum.App_File)
                        {
                            firstAppFileFound = true;
                            firstPageOfApp    = pageCount + 1;
                        }

                        // add document to 'src'
                        pdfcopy.AddDocument(new iTextSharp.text.pdf.PdfReader(reader));
                        pageCount += reader.NumberOfPages;
                    }

                    pdfcopy.Close();
                    pdfdoc.CloseDocument();
                }

                // final cycle, if dividers, to make sure text starts on odd-sided pages
                if (bind == TypeOfBindEnum.PerfectBind && hasDividers)
                {
                    string dest = (System.IO.Path.GetDirectoryName(src) + @"\temp " + DateTime.Now.ToString("ddMMyyyyhhmmssffff"));

                    using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create))
                    {
                        iTextSharp.text.pdf.PdfReader  reader  = new iTextSharp.text.pdf.PdfReader(src);
                        iTextSharp.text.pdf.PdfStamper stamper = new iTextSharp.text.pdf.PdfStamper(reader, stream);

                        // get all blank pages in appendix
                        iTextSharp.text.pdf.parser.PdfReaderContentParser parser = new iTextSharp.text.pdf.parser.PdfReaderContentParser(reader);
                        List <List <int> > groupsOfBlanks = new List <List <int> >();
                        List <int>         group_list     = new List <int>();
                        int x;
                        for (x = firstPageOfApp; x <= reader.NumberOfPages; x++)
                        {
                            iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy extract = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                            var    extractedText = parser.ProcessContent(x, extract);
                            string textFromPage  = extractedText.GetResultantText();
                            // find blank pages and cluster into group_list
                            if (System.Text.RegularExpressions.Regex.Matches(textFromPage, @"\S").Count == 0)
                            {
                                // capture blank page cluster (??? but what if only 1 page ???)
                                if (group_list.Count == 0 || group_list.Contains(x - 1))
                                {
                                    group_list.Add(x);
                                }
                            }
                            else
                            {
                                // find first page after cluster
                                if (group_list.Count > 0)
                                {
                                    if (group_list.Last() % 2 == 1)
                                    {
                                        // add blank page
                                        stamper.InsertPage(group_list.Last() + 1, reader.GetPageSizeWithRotation(1));
                                    }
                                }
                                // clear list
                                group_list.Clear();
                            }
                        }
                        stamper.Close();
                        reader.Close();
                    }
                    System.IO.File.Delete(src);
                    System.IO.File.Move(dest, src);
                }
            }
            catch (Exception excpt)
            {
                System.Diagnostics.Debug.WriteLine(excpt); return(false);
            }
            return(true);
        }
示例#7
0
        public ImposePerfectBind(
            string src, IOrderedEnumerable <CockleFilePdf> list, IEnumerable <CockleFilePdf> listFoldouts,
            int cvLen, TypeOfBindEnum bind, int?ticket, string atty)
        {
            this.SourceFolder    = src;
            this.ImposedFiles    = new List <CockleFilePdf>(list);
            this.TypeOfBind      = bind;
            this.CoverLength     = cvLen;
            this.PageCountOfBody = 0;
            this.NewFilesCreated = new List <CockleFilePdf>();

            // create folder for processed files
            this.ProcessedFolder = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(this.SourceFolder, "processed"));

            // create new file names
            NewFileNames = new Dictionary <string, string>
            {
                { "Cover", System.IO.Path.Combine(ProcessedFolder.FullName, "Cover.pdf") },
                { "Brief", System.IO.Path.Combine(ProcessedFolder.FullName, "Brief.pdf") },
                { "FinalCover", System.IO.Path.Combine(SourceFolder, string.Format("{0} {1} cv B4 PB pr.pdf", ticket, atty)) },
                { "FinalBrief", System.IO.Path.Combine(SourceFolder, string.Format("{0} {1} br app B5 pr.pdf", ticket, atty)) }
            };

            bool hasCover = this.ImposedFiles.Any(f => f.FileType == SourceFileTypeEnum.Cover);

            if (hasCover)
            {
                ImposeCover(this.ImposedFiles, this.NewFileNames["Cover"]);
            }

            bool hasOnlyCover = true;

            this.ImposedFiles.ForEach(f => { if (f.FileType != SourceFileTypeEnum.Cover)
                                             {
                                                 hasOnlyCover = false;
                                             }
                                      });
            if (!hasOnlyCover)
            {
                ImposeBrief(this.ImposedFiles, this.NewFileNames["Brief"], this.TypeOfBind);
            }

            // move files to main folder
            try
            {
                if (hasCover)
                {
                    if (System.IO.File.Exists(this.NewFileNames["FinalCover"]))
                    {
                        System.IO.File.Delete(this.NewFileNames["FinalCover"]);
                    }
                    System.IO.File.Copy(this.NewFileNames["Cover"], this.NewFileNames["FinalCover"], true);
                    this.NewFilesCreated.Add(new CockleFilePdf(
                                                 this.NewFileNames["FinalCover"], atty, ticket, SourceFileTypeEnum.Imposed_Cover, ""));
                }
            }
            catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); }
            try
            {
                if (!hasOnlyCover)
                {
                    if (System.IO.File.Exists(this.NewFileNames["FinalBrief"]))
                    {
                        System.IO.File.Delete(this.NewFileNames["FinalBrief"]);
                    }
                    System.IO.File.Copy(this.NewFileNames["Brief"], this.NewFileNames["FinalBrief"], true);
                    this.NewFilesCreated.Add(new CockleFilePdf(
                                                 this.NewFileNames["FinalBrief"], atty, ticket, SourceFileTypeEnum.Imposed_Brief, ""));
                }
            }
            catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); }

            // attempt to delete processed folder
            try { ProcessedFolder.Delete(true); }
            catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); }
        }
示例#8
0
        private void ImposeBrief(List <CockleFilePdf> imposedFiles, string imposedBody, TypeOfBindEnum bind)
        {
            // remove cover, combine body, and add blank pages where needed
            if (!PdfUtilities.CombineBriefPages_AddingBlanks(imposedFiles, imposedBody, bind))
            {
                // problem if returns false
            }

            // crop pages
            if (!PdfUtilities.CropCockleBriefPages(imposedBody))
            {
                // problem if returns false
            }
            // layout on B5 pages
            if (!PdfUtilities.PerfectBind_LayoutCroppedBrief(imposedBody))
            {
                // problem if returns false
            }
        }