コード例 #1
0
        public static bool CombineCoverAndInsideCover(List <CockleFilePdf> files, string src)
        {
            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;
                        pdfcopy.AddDocument(new iTextSharp.text.pdf.PdfReader(reader));
                    }
                    pdfcopy.Close();
                    pdfdoc.CloseDocument();
                }
                return(true);
            }
            catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); return(false); }
        }
コード例 #2
0
        public static bool AddPagesToPDF(string filename, List <Tiff.PageInfo> images, int page, int from, int to)
        {
            PdfReader pdfReader = null;

            try
            {
                string password = String.Empty;
                try
                {
                    pdfReader = new PdfReader(filename);
                    if (!pdfReader.IsOpenedWithFullPermissions)
                    {
                        throw new BadPasswordException("");
                    }
                }
                catch (BadPasswordException)
                {
                    while (!pdfReader.IsOpenedWithFullPermissions)
                    {
                        pdfReader.Close();

                        if (
                            InputBox.Show(Environment.StringResources.GetString("DocControl_PDF_Encrypted"),
                                          Environment.StringResources.GetString("DocControl_PDF_EnterPass"),
                                          ref password) == DialogResult.Cancel)
                        {
                            return(false);
                        }
                        try
                        {
                            pdfReader = new PdfReader(filename, Encoding.ASCII.GetBytes(password));
                        }
                        catch (BadPasswordException)
                        {
                        }
                        catch (Exception ex) { Data.Env.WriteToLog(ex); }
                    }
                }
                catch (Exception ex) { Data.Env.WriteToLog(ex); }

                if (pdfReader.NumberOfPages == 0)
                {
                    throw new Exception("В документе отсутствуют страницы. Операция сохранения невозможна!");
                }

                string tmpFileName = Path.GetTempFileName();
                int    imagesCount = images.Count;
                using (var mem_stream = new MemoryStream())
                {
                    using (var document = new iTextSharp.text.Document())
                        using (PdfWriter pdfWriter = PdfWriter.GetInstance(document, mem_stream))
                        {
                            document.OpenDocument();
                            for (int j = 0; j < imagesCount; j++)
                            {
                                Tiff.PageInfo info       = images[j];
                                bool          needRotate = info.Image.Width > info.Image.Height;
                                if (needRotate)
                                {
                                    info.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
                                }

                                Image gif = Image.GetInstance(info.Image, ImageFormat.Png);
                                gif.SetAbsolutePosition(0, 0);
                                gif.ScaleAbsolute((float)(info.Image.Width * (72.0 / info.Image.HorizontalResolution)),
                                                  (float)(info.Image.Height * (72.0 / info.Image.VerticalResolution)));
                                gif.SetAbsolutePosition(1, 1);

                                document.SetPageSize(new Rectangle(gif.ScaledWidth, gif.ScaledHeight));
                                document.NewPage();

                                pdfWriter.DirectContent.AddImage(gif);

                                if (needRotate)
                                {
                                    pdfWriter.AddPageDictEntry(PdfName.ROTATE, new PdfNumber(270));
                                }
                            }
                            images.Clear();
                            pdfWriter.CloseStream = false;
                            document.CloseDocument();
                        }
                    mem_stream.Position = 0;
                    var addPageReader = new PdfReader(mem_stream);

                    using (var file_stream = new FileStream(tmpFileName, FileMode.Create, FileAccess.Write, FileShare.None))
                        using (var document = new iTextSharp.text.Document(pdfReader.GetPageSize(1)))
                            using (var pdfCopy = new PdfCopy(document, file_stream))
                            {
                                document.Open();
                                if (-1 == page)
                                {
                                    for (int j = 1; j <= imagesCount; j++)
                                    {
                                        PdfImportedPage pp = pdfCopy.GetImportedPage(addPageReader, j);
                                        pdfCopy.AddPage(pp);
                                    }
                                }
                                if (-2 == page)
                                {
                                    page = pdfReader.NumberOfPages - 1;
                                }
                                for (int i = 1; i <= pdfReader.NumberOfPages; i++)
                                {
                                    PdfImportedPage pp = pdfCopy.GetImportedPage(pdfReader, i);
                                    pdfCopy.AddPage(pp);
                                    if (i == page + 1)
                                    {
                                        for (int j = 1; j <= imagesCount; j++)
                                        {
                                            pp = pdfCopy.GetImportedPage(addPageReader, j);
                                            pdfCopy.AddPage(pp);
                                        }
                                    }
                                }
                                document.Close();
                                if (pdfReader != null)
                                {
                                    pdfReader.Close();
                                    pdfReader = null;
                                }
                                addPageReader.Close();
                                File.Copy(tmpFileName, filename, true);
                                File.Delete(tmpFileName);
                                return(true);
                            }
                }
            }
            catch (Exception ex) { Data.Env.WriteToLog(ex); }
            finally
            {
                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }
            return(false);
        }
コード例 #3
0
        public void SaveImage(HttpContext context)
        {
            var aa = context.Request.Form["svg"];

            if (context.Request.Form["svg"] != null)
            {
                string tType     = "image/png";
                string tSvg      = context.Request.Form["svg"].ToString();
                string tFileName = "";

                Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                tFileName = rand.Next().ToString();

                MemoryStream tData = new MemoryStream(Encoding.UTF8.GetBytes(tSvg));

                MemoryStream tStream = new MemoryStream();
                string       tTmp    = new Random().Next().ToString();

                string tExt        = "";
                string tTypeString = "";

                switch (tType)
                {
                case "image/png":
                    tTypeString = "-m image/png";
                    tExt        = "png";
                    break;

                case "image/jpeg":
                    tTypeString = "-m image/jpeg";
                    tExt        = "jpg";
                    break;

                case "application/pdf":
                    tTypeString = "-m application/pdf";
                    tExt        = "pdf";
                    break;

                case "image/svg+xml":
                    tTypeString = "-m image/svg+xml";
                    tExt        = "svg";
                    break;
                }

                if (tTypeString != "")
                {
                    //string tWidth = context.Request.Form["width"].ToString();
                    //string tWidth = "0";
                    Svg.SvgDocument tSvgObj = SvgDocument.Open(tData);
                    switch (tExt)
                    {
                    case "jpg":
                        tSvgObj.Draw().Save(tStream, ImageFormat.Jpeg);
                        break;

                    case "png":

                        tSvgObj.Draw().Save(tStream, ImageFormat.Png);
                        break;

                    case "pdf":
                        PdfWriter tWriter = null;
                        iTextSharp.text.Document tDocumentPdf = null;
                        try
                        {
                            tSvgObj.Draw().Save(tStream, ImageFormat.Png);
                            tDocumentPdf = new iTextSharp.text.Document(new iTextSharp.text.Rectangle((float)tSvgObj.Width, (float)tSvgObj.Height));
                            tDocumentPdf.SetMargins(0.0f, 0.0f, 0.0f, 0.0f);
                            iTextSharp.text.Image tGraph = iTextSharp.text.Image.GetInstance(tStream.ToArray());
                            tGraph.ScaleToFit((float)tSvgObj.Width, (float)tSvgObj.Height);

                            tStream = new MemoryStream();
                            tWriter = PdfWriter.GetInstance(tDocumentPdf, tStream);
                            tDocumentPdf.Open();
                            tDocumentPdf.NewPage();
                            tDocumentPdf.Add(tGraph);
                            tDocumentPdf.CloseDocument();
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                        finally
                        {
                            tDocumentPdf.Close();
                            tDocumentPdf.Dispose();
                            tWriter.Close();
                            tWriter.Dispose();
                            tData.Dispose();
                            tData.Close();
                        }
                        break;

                    case "svg":
                        tStream = tData;
                        break;
                    }
                    System.IO.MemoryStream ms    = new System.IO.MemoryStream(tStream.ToArray());
                    System.Drawing.Image   image = System.Drawing.Image.FromStream(ms);
                    string savePath = context.Server.MapPath("image/");

                    if (!Directory.Exists(savePath))
                    {
                        Directory.CreateDirectory(savePath);
                    }
                    savePath += tFileName + "." + tExt;
                    string SavePathImage = tFileName + "." + tExt;
                    context.Session["FirstImage"] = savePath;
                    image.Save(savePath, System.Drawing.Imaging.ImageFormat.Png);
                    image.Dispose();
                    context.Response.Write(tFileName + "." + tExt);
                }
            }
        }
コード例 #4
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);
        }