Ejemplo n.º 1
0
        public static void MergeFiles(List <string> sourceFiles, string rutaPdfJoin, bool addCopy)
        {
            Document document = new Document();

            using (MemoryStream ms = new MemoryStream())
            {
                FileStream fl   = new FileStream(rutaPdfJoin, FileMode.Create, FileAccess.Write, FileShare.None);
                PdfCopy    copy = new PdfCopy(document, fl);
                document.Open();

                // Iterar pdfs
                for (int fileCounter = 0; fileCounter < sourceFiles.Count; fileCounter++)
                {
                    PdfReader reader        = new PdfReader(sourceFiles[fileCounter]);
                    int       numberOfPages = reader.NumberOfPages;

                    // Iterar paginas
                    for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                    {
                        PdfImportedPage   importedPage = copy.GetImportedPage(reader, currentPageIndex);
                        PdfCopy.PageStamp pageStamp    = copy.CreatePageStamp(importedPage);

                        pageStamp.AlterContents();
                        copy.AddPage(importedPage);
                        if (addCopy)
                        {
                            copy.AddPage(importedPage);
                        }
                    }
                    copy.FreeReader(reader);
                    reader.Close();
                }
                document.Close();
            }
        }
Ejemplo n.º 2
0
        public static byte[] merge_files(List <FileInfo> docs)
        {
            Document document = new Document();

            using (MemoryStream ms = new MemoryStream()) {
                PdfCopy copy = new PdfCopy(document, ms);
                document.Open();
                int document_page_counter = 0;

                foreach (FileInfo fi in docs)
                {
                    PdfReader reader = new PdfReader(fi.FullName);

                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        document_page_counter++;
                        PdfImportedPage ip = copy.GetImportedPage(reader, i);
#if PAGE_NUMBERS
                        PdfCopy.PageStamp ps = copy.CreatePageStamp(ip);

                        ColumnText.ShowTextAligned(ps.GetOverContent(), Element.ALIGN_CENTER,
                                                   new Phrase(string.Format("{0}", document_page_counter)), (ip.Width / 2), 5, ip.Width < ip.Height ? 0 : 1);
                        ps.AlterContents();
#endif
                        copy.AddPage(ip);
                    }

                    copy.FreeReader(reader);
                    reader.Close();
                }
                document.Close();
                return(ms.GetBuffer());
            }
        }
Ejemplo n.º 3
0
        public string ProductQuoteToSmallPdf(ProductQuote productQuote, string productQuoteSmallPdfTemplate)
        {
            string fileTemplate   = Path.Combine(CommonHelper.MapPath("~/Documents/Templates"), productQuoteSmallPdfTemplate);
            string fileNameExport = string.Format("{0}_{1}_{2}.pdf", productQuote.ProductQuoteCode, "Rev08", Guid.NewGuid().ToString().Substring(0, 8));
            string fileExport     = Path.Combine(CommonHelper.MapPath("~/Documents/Export"), fileNameExport);


            PdfReader  reader = new PdfReader(fileTemplate);
            FileStream fs     = new FileStream(fileExport, FileMode.Create, FileAccess.Write);

            iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
            Document document = new Document(size);

            PdfCopy copy = new PdfCopy(document, fs);

            document.Open();

            PdfImportedPage page = null;

            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                page = copy.GetImportedPage(reader, i);

                //En la primer pagina ponemos los datos
                if (i == 1)
                {
                    PdfCopy.PageStamp pageStamp = copy.CreatePageStamp(page);
                    StampDataIntoSmallPdf(pageStamp, productQuote);
                    pageStamp.AlterContents();
                }

                PdfCopy.PageStamp pageStampFooter = copy.CreatePageStamp(page);
                StampFooterDataIntoPdf(pageStampFooter, productQuote.ProductQuoteSmallPDFFooter);
                pageStampFooter.AlterContents();

                copy.AddPage(page);
            }

            copy.FreeReader(reader);
            document.Close();
            reader.Close();

            return(fileNameExport);
        }
Ejemplo n.º 4
0
    public static byte[] merge_files(List <FileInfo> docs)
    {
        using (Document document = new Document()) {
            using (MemoryStream ms = new MemoryStream()) {
                PdfCopy copy = new PdfCopy(document, ms);
                document.Open();
                int document_page_counter = 0;
                int total_pages           = count_pages(docs);
                int font_size             = ProtoDrawingCollector.csproj.Properties.Settings.Default.PageStampSize;
                foreach (FileInfo fi in docs)
                {
                    using (PdfReader reader = new PdfReader(fi.FullName)) {
                        for (int i = 1; i <= reader.NumberOfPages; i++)
                        {
                            document_page_counter++;
                            PdfImportedPage ip = copy.GetImportedPage(reader, i);
#if PAGE_NUMBERS
                            PdfCopy.PageStamp        ps       = copy.CreatePageStamp(ip);
                            PdfContentByte           cb       = ps.GetOverContent();
                            System.Drawing.Rectangle sdr      = ProtoDrawingCollector.csproj.Properties.Settings.Default.PageStampWhiteoutRectangle;
                            System.Drawing.Point     location = ProtoDrawingCollector.csproj.Properties.Settings.Default.PageStampLoc;
                            //System.Drawing.Rectangle sdr = new System.Drawing.Rectangle(1154, 20, 47, 16);
                            Rectangle size = reader.GetPageSize(i);
                            if ((size.Height * size.Width) < (1224 * 792))
                            {
                                sdr = ProtoDrawingCollector.csproj.Properties.Settings.Default.PageStampWhiteoutRectangleA4;
                                //sdr = new System.Drawing.Rectangle(720, 20, 47, 16);
                                location = ProtoDrawingCollector.csproj.Properties.Settings.Default.PageStampLocA4;
                            }
                            Rectangle r = new Rectangle(sdr.Left, sdr.Bottom, sdr.Right, sdr.Top);
                            //OnAppend(new AppendEventArgs(string.Format(@"{0} x {1}", size.Width, size.Height)));
                            r.BackgroundColor = BaseColor.WHITE;
                            cb.Rectangle(r);
                            Font  f = FontFactory.GetFont("Century Gothic", font_size);
                            Chunk c = new Chunk(string.Format("{0} OF {1}", document_page_counter, total_pages), f);
                            c.SetBackground(BaseColor.WHITE);
                            ColumnText.ShowTextAligned(ps.GetOverContent(),
                                                       Element.ALIGN_CENTER,
                                                       new Phrase(c),
                                                       location.X, location.Y,
                                                       ip.Width < ip.Height ? 0 : 1);
                            ps.AlterContents();
#endif
                            copy.AddPage(ip);
                        }

                        //copy.FreeReader(reader);
                        //reader.Close();
                    }
                }
                document.Close();
                return(ms.GetBuffer());
            }
        }
    }
        private byte[] _RedactUsefulDataFromDocument()
        {
            using (Document document = new Document()) {
                using (MemoryStream memoryStream = new MemoryStream()) {
                    try {
                        PdfCopy copy = new PdfCopy(document, memoryStream);
                        document.Open();
                        using (PdfReader pdfReader = new PdfReader(source)) {
                            for (int i = 1; i < pdfReader.NumberOfPages + 1; i++)
                            {
                                PdfImportedPage   importedPage = copy.GetImportedPage(pdfReader, i);
                                PdfCopy.PageStamp pageStamp    = copy.CreatePageStamp(importedPage);
                                PdfContentByte    contentByte  = pageStamp.GetOverContent();

                                if (i == 1)
                                {
                                    float y_offset = 137F;
                                    for (int j = 0; j < 5; j++, y_offset -= 13.5F)
                                    {
                                        Rectangle sourceRevRectangle = new Rectangle(21, y_offset, 44, y_offset + 10);
                                        sourceRevRectangle.BackgroundColor = BaseColor.WHITE;
                                        Rectangle sourceECRRectangle = new Rectangle(46, y_offset, 71, y_offset + 10);
                                        sourceECRRectangle.BackgroundColor = BaseColor.WHITE;
                                        Rectangle sourceDescrRectangle = new Rectangle(73, y_offset, 988, y_offset + 10);
                                        sourceDescrRectangle.BackgroundColor = BaseColor.WHITE;
                                        Rectangle sourceDrwnBy = new Rectangle(991, y_offset, 1061, y_offset + 10);
                                        sourceDrwnBy.BackgroundColor = BaseColor.WHITE;
                                        Rectangle sourceAppBy = new Rectangle(1063, y_offset, 1133, y_offset + 10);
                                        sourceAppBy.BackgroundColor = BaseColor.WHITE;
                                        Rectangle sourceDate = new Rectangle(1135, y_offset, 1205, y_offset + 10);
                                        sourceDate.BackgroundColor = BaseColor.WHITE;

                                        contentByte.Rectangle(sourceRevRectangle);
                                        contentByte.Rectangle(sourceECRRectangle);
                                        contentByte.Rectangle(sourceDescrRectangle);
                                        contentByte.Rectangle(sourceDrwnBy);
                                        contentByte.Rectangle(sourceAppBy);
                                        contentByte.Rectangle(sourceDate);

                                        pageStamp.AlterContents();
                                    }
                                }
                                copy.AddPage(importedPage);
                            }
                        }
                    } catch (System.Exception e) {
                        throw e;
                    } finally {
                        document.Close();
                    }
                    return(memoryStream.GetBuffer());
                }
            }
        }
Ejemplo n.º 6
0
        //public void ConvertDocumentToPDF(byte[] bytes, string pathFileOut,string pathFileOutTemp,List<Archive> ImageRoutes)
        //{

        //    try {

        //        var inputAsString = Convert.ToBase64String(bytes.ToArray(), 0, bytes.ToArray().Length);
        //        File.WriteAllBytes(pathFileOutTemp, Convert.FromBase64String(inputAsString));

        //        //Incrustando Imagenes
        //        IncrustingImage(pathFileOutTemp, ImageRoutes,pathFileOut);
        //        //if (ImageRoutes != null && ImageRoutes.Count > 0)

        //        string textDelete = "Unlicensed version. Please register @ templater.info";

        //        DocumentCore document = DocumentCore.Load(pathFileOutTemp, new DocxLoadOptions());
        //        int countDel = 0;
        //        foreach (ContentRange cr in document.Content.Find(textDelete).Reverse())
        //        {
        //            cr.Delete();
        //            countDel++;
        //        }

        //        if (File.Exists(pathFileOut)) File.Delete(pathFileOut);

        //            if (ImageRoutes.Where(x=>x.typeAdjunte == TypeAdjunte.pdf).Count() > 0)
        //            {
        //                List<byte[]> listByte = new List<byte[]>();

        //                using (MemoryStream PDFGenerate = new MemoryStream())
        //                {
        //                    document.Save(PDFGenerate, SaveOptions.PdfDefault);
        //                    listByte.Add(PDFGenerate.ToArray());
        //                }

        //                foreach (var file in ImageRoutes.Where(x => x.typeAdjunte == TypeAdjunte.pdf))
        //                {
        //                   byte[] PdfBype = null;
        //                    if (File.Exists(file.RutaArchivo))
        //                    {
        //                        PdfBype = System.IO.File.ReadAllBytes(file.RutaArchivo);
        //                        if (PdfBype != null)
        //                        {
        //                            listByte.Add(PdfBype);
        //                        }
        //                    }
        //                }

        //                byte[] PdfFinale = MergeFiles(listByte);
        //                var inputFinale = Convert.ToBase64String(PdfFinale.ToArray(), 0, PdfFinale.ToArray().Length);
        //                File.WriteAllBytes(pathFileOut, Convert.FromBase64String(inputFinale));
        //            }

        //            else
        //            {
        //                document.Save(pathFileOut);
        //            }


        //        File.Delete(pathFileOutTemp);
        //    }
        //    catch(Exception ex)
        //    {
        //        throw ex;
        //    }
        //}

        public static byte[] MergeFiles(Dictionary <int, byte[]> sourceFiles)
        {
            iTextSharp.text.Document document = new iTextSharp.text.Document();
            using (MemoryStream ms = new MemoryStream())
            {
                PdfCopy copy = new PdfCopy(document, ms);
                document.Open();
                int documentPageCounter = 0;

                sourceFiles = sourceFiles.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);


                // Iterate through all pdf documents

                foreach (KeyValuePair <int, byte[]> pair in sourceFiles)
                {
                    // Create pdf reader
                    PdfReader reader        = new PdfReader(pair.Value);
                    int       numberOfPages = reader.NumberOfPages;

                    // Iterate through all pages
                    for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                    {
                        documentPageCounter++;
                        PdfImportedPage   importedPage = copy.GetImportedPage(reader, currentPageIndex);
                        PdfCopy.PageStamp pageStamp    = copy.CreatePageStamp(importedPage);

                        // Write header
                        ColumnText.ShowTextAligned(pageStamp.GetOverContent(), iTextSharp.text.Element.ALIGN_CENTER,
                                                   new Phrase(""), importedPage.Width / 2, importedPage.Height - 30,
                                                   importedPage.Width < importedPage.Height ? 0 : 1);

                        // Write footer
                        ColumnText.ShowTextAligned(pageStamp.GetOverContent(), iTextSharp.text.Element.ALIGN_CENTER,
                                                   new Phrase(String.Format("", documentPageCounter)), importedPage.Width / 2, 30,
                                                   importedPage.Width < importedPage.Height ? 0 : 1);

                        pageStamp.AlterContents();

                        copy.AddPage(importedPage);
                    }

                    copy.FreeReader(reader);
                    reader.Close();
                }

                document.Close();
                return(ms.GetBuffer());
            }
        }
Ejemplo n.º 7
0
        public async Task <byte[]> MergeFiles(List <ClaimFilePage> ClaimFilePages)
        {
            Document document = new Document();

            using (MemoryStream ms = new MemoryStream())
            {
                PdfCopy copy = new PdfCopy(document, ms);
                document.Open();
                int documentPageCounter = 0;

                // Iterate through all pdf documents
                foreach (var claimPage in ClaimFilePages)
                {
                    // Create pdf reader
                    PdfReader reader        = new PdfReader(claimPage.Page);
                    int       numberOfPages = reader.NumberOfPages;

                    // Iterate through all pages
                    for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                    {
                        documentPageCounter++;
                        PdfImportedPage   importedPage = copy.GetImportedPage(reader, currentPageIndex);
                        PdfCopy.PageStamp pageStamp    = copy.CreatePageStamp(importedPage);

                        // Write header
                        ColumnText.ShowTextAligned(pageStamp.GetOverContent(), Element.ALIGN_CENTER,
                                                   new Phrase(string.Empty), importedPage.Width / 2, importedPage.Height - 30,
                                                   importedPage.Width < importedPage.Height ? 0 : 1);

                        // Write footer
                        if (claimPage.ClaimId > 0)
                        {
                            ColumnText.ShowTextAligned(pageStamp.GetOverContent(), Element.ALIGN_CENTER,
                                                       new Phrase(String.Format($"Reclamo {claimPage.ClaimId}")), importedPage.Width / 2, 15,
                                                       importedPage.Width < importedPage.Height ? 0 : 1);
                        }

                        pageStamp.AlterContents();

                        copy.AddPage(importedPage);
                    }

                    copy.FreeReader(reader);
                    reader.Close();
                }

                document.Close();
                return(ms.GetBuffer());
            }
        }
Ejemplo n.º 8
0
        public static byte[] MergeFiles(List <byte[]> sourceFiles)
        {
            Document document = new Document();

            using (MemoryStream ms = new MemoryStream())
            {
                PdfCopy copy = new PdfCopy(document, ms);
                document.Open();
                int documentPageCounter = 0;

                // Iterate through all pdf documents
                for (int fileCounter = 0; fileCounter < sourceFiles.Count; fileCounter++)
                {
                    // Create pdf reader
                    PdfReader reader        = new PdfReader(sourceFiles[fileCounter]);
                    int       numberOfPages = reader.NumberOfPages;

                    // Iterate through all pages
                    for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                    {
                        documentPageCounter++;
                        PdfImportedPage   importedPage = copy.GetImportedPage(reader, currentPageIndex);
                        PdfCopy.PageStamp pageStamp    = copy.CreatePageStamp(importedPage);

                        // Write header
                        ColumnText.ShowTextAligned(pageStamp.GetOverContent(), Element.ALIGN_CENTER,
                                                   new Phrase("PDF Merger by Helvetic Solutions"), importedPage.Width / 2, importedPage.Height - 30,
                                                   importedPage.Width < importedPage.Height ? 0 : 1);

                        // Write footer
                        ColumnText.ShowTextAligned(pageStamp.GetOverContent(), Element.ALIGN_CENTER,
                                                   new Phrase(String.Format("Page {0}", documentPageCounter)), importedPage.Width / 2, 30,
                                                   importedPage.Width < importedPage.Height ? 0 : 1);

                        pageStamp.AlterContents();

                        copy.AddPage(importedPage);
                    }

                    copy.FreeReader(reader);
                    reader.Close();
                }

                document.Close();
                return(ms.GetBuffer());
            }
        }
Ejemplo n.º 9
0
        public byte[] PDF_Merger(List <string> li, string PrintedName)
        {
            List <byte[]> sourceFiles = FileReadIn(li);
            Document      document    = new Document();

            using (MemoryStream ms = new MemoryStream())
            {
                PdfCopy copy = new PdfCopy(document, ms);
                document.Open();
                int documentPageCounter = 0;

                // Iterate through all pdf documents
                for (int fileCounter = 0; fileCounter < sourceFiles.Count; fileCounter++)
                {
                    // Create pdf reader
                    PdfReader reader        = new PdfReader(sourceFiles[fileCounter]);
                    int       numberOfPages = reader.NumberOfPages;

                    // Iterate through all pages
                    for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                    {
                        documentPageCounter++;
                        PdfImportedPage   importedPage = copy.GetImportedPage(reader, currentPageIndex);
                        PdfCopy.PageStamp pageStamp    = copy.CreatePageStamp(importedPage);
                        pageStamp.AlterContents();
                        copy.AddPage(importedPage);
                    }
                    copy.FreeReader(reader);
                    reader.Close();
                }

                document.Close();
                if (PrintedName == "")
                {
                    PrintedName = "PM Merger Document ";
                }
                DateTime thisDay = DateTime.Today;
                System.IO.Directory.CreateDirectory(FolderUrl + "\\Merged Documents");
                System.IO.File.WriteAllBytes(FolderUrl + "\\Merged Documents\\" + PrintedName + " ( " + thisDay.ToString("yyyy. MM. dd.") + " ).pdf", ms.GetBuffer());
                Process.Start(FolderUrl + "\\Merged Documents");

                return(ms.GetBuffer());
            }
        }
Ejemplo n.º 10
0
        private static int Append(PdfCopy writer, PdfReader reader, Document document, int currentPage, int totalPages)
        {
            var origPageSize = document.PageSize;

            for (int i = 0; i < reader.NumberOfPages; i++)
            {
                // read the page size and rotation from the original pdf
                var pageRect = reader.GetPageSizeWithRotation(i + 1);

                // set the page size of the read in page (and if there is an orientation change)
                // this has to happen *before* adding a "new" page
                document.SetPageSize(pageRect);
                document.NewPage();

                // get the imported page from the reader
                var importedPage = writer.GetImportedPage(reader, i + 1);

                // create a page stamp so we can add page numbers
                var stamp = writer.CreatePageStamp(importedPage);

                // get the content to write the page numbers to
                var content = stamp.GetUnderContent();

                // add the text into the page stamp content
                var pageText = String.Format("Page {0} of {1}", currentPage, totalPages);
                content.BeginText();
                content.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 8);
                content.SetColorFill(FooterColor);
                content.ShowTextAligned(PdfContentByte.ALIGN_CENTER, pageText, pageRect.Width - 92, 5, 0);
                content.EndText();

                // commit the changes made to the page stamp content
                stamp.AlterContents();

                // append the altered page to the copy
                writer.AddPage(importedPage);

                document.SetPageSize(origPageSize);
                currentPage++;
            }

            return(currentPage);
        }
Ejemplo n.º 11
0
        public void TestPdf()
        {
            string fileTemplate   = Path.Combine(CommonHelper.MapPath("~/Documents/Templates"), ProductQuoteApp.Resources.Resources.FileNamePdfProductQuoteTemplate);
            string fileNameExport = string.Format("productQuote_{0}_{1}.pdf", 1, Guid.NewGuid().ToString());
            string fileExport     = Path.Combine(CommonHelper.MapPath("~/Documents/Export"), fileNameExport);


            PdfReader  reader = new PdfReader(fileTemplate);
            FileStream fs     = new FileStream(fileExport, FileMode.Create, FileAccess.Write);

            iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
            Document document = new Document(size);

            PdfCopy copy = new PdfCopy(document, fs);

            document.Open();

            PdfImportedPage page = null;

            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                page = copy.GetImportedPage(reader, i);

                //En la primer pagina ponemos los datos
                if (i == 1)
                {
                    PdfCopy.PageStamp    pageStamp = copy.CreatePageStamp(page);
                    BaseFont             bf        = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    iTextSharp.text.Font fontText  = new iTextSharp.text.Font(bf, 9);

                    ColumnText.ShowTextAligned(pageStamp.GetOverContent(), Element.ALIGN_RIGHT, new Phrase("Buenos Aires, 15 de septiembre de 2017", fontText), 525, 720, 0);
                    //new Phrase("Buenos Aires, 15 de septiembre de 2017", fontText), page.Width / 2, page.Height - 30, page.Width < page.Height ? 0 : 1);

                    pageStamp.AlterContents();
                }

                copy.AddPage(page);
            }

            copy.FreeReader(reader);
            document.Close();
            reader.Close();
        }
Ejemplo n.º 12
0
        public Document concatenarArchivosPdf(List <string> pdf, Stream os)
        {
            Document document = new Document();
            PdfCopy  copy     = new PdfCopy(document, os);

            document.Open();
            PdfImportedPage page;

            // this object **REQUIRED** to add content when concatenating PDFs
            PdfCopy.PageStamp stamp;
            // image watermark/background

            /*iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(Request.MapPath("cat/kuujinbo2.gif"));
             * pdfImage.SetAbsolutePosition(200, 400);*/
            // set transparency
            PdfGState state = new PdfGState();

            state.FillOpacity   = 0.3F;
            state.StrokeOpacity = 0.3F;

            foreach (string p in pdf)
            {
                //  string pPath = Request.MapPath(string.Format("cat/{0}.pdf", p));
                string    pPath  = p;
                PdfReader reader = new PdfReader(new RandomAccessFileOrArray(pPath), null);
                int       pages  = reader.NumberOfPages;
                // loop over document pages
                for (int i = 0; i < pages;)
                {
                    page  = copy.GetImportedPage(reader, ++i);
                    stamp = copy.CreatePageStamp(page);
                    PdfContentByte cb = stamp.GetUnderContent();
                    cb.SaveState();
                    cb.SetGState(state);
                    //cb.AddImage(pdfImage);
                    stamp.AlterContents();
                    copy.AddPage(page);
                }
                reader.Close();
            }
            document.Close();
            return(document);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Merge pdf files.
        /// </summary>
        /// <param name="sourceFiles">PDF files being merged.</param>
        /// <returns></returns>
        public byte[] MergeFiles(List <byte[]> sourceFiles)
        {
            Document document = new Document();

            using (MemoryStream ms = new MemoryStream())
            {
                PdfCopy copy = new PdfCopy(document, ms);
                document.Open();
                int documentPageCounter = 0;

                // Iterate through all pdf documents
                for (int fileCounter = 0; fileCounter < sourceFiles.Count; fileCounter++)
                {
                    // Create pdf reader
                    PdfReader reader        = new PdfReader(sourceFiles[fileCounter]);
                    int       numberOfPages = reader.NumberOfPages;

                    // Iterate through all pages
                    for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                    {
                        documentPageCounter++;
                        PdfImportedPage   importedPage = copy.GetImportedPage(reader, currentPageIndex);
                        PdfCopy.PageStamp pageStamp    = copy.CreatePageStamp(importedPage);

                        pageStamp.AlterContents();

                        copy.AddPage(importedPage);
                    }

                    copy.FreeReader(reader);
                    reader.Close();
                }

                document.Close();
                return(ms.GetBuffer());
            }
        }
Ejemplo n.º 14
0
// ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            using (ZipFile zip = new ZipFile()) {
                MovieLinks1  ml = new MovieLinks1();
                byte[]       r1 = Utility.PdfBytes(ml);
                MovieHistory mh = new MovieHistory();
                byte[]       r2 = Utility.PdfBytes(mh);
                using (MemoryStream ms = new MemoryStream()) {
                    // step 1
                    using (Document document = new Document()) {
                        // step 2
                        using (PdfCopy copy = new PdfCopy(document, ms)) {
                            // step 3
                            document.Open();
                            // step 4
                            // reader for document 1
                            PdfReader reader1 = new PdfReader(r1);
                            int       n1      = reader1.NumberOfPages;
                            // reader for document 2
                            PdfReader reader2 = new PdfReader(r2);
                            int       n2      = reader2.NumberOfPages;
                            // initializations
                            PdfImportedPage   page;
                            PdfCopy.PageStamp stamp;
                            // Loop over the pages of document 1
                            for (int i = 0; i < n1;)
                            {
                                page  = copy.GetImportedPage(reader1, ++i);
                                stamp = copy.CreatePageStamp(page);
                                // add page numbers
                                ColumnText.ShowTextAligned(
                                    stamp.GetUnderContent(), Element.ALIGN_CENTER,
                                    new Phrase(string.Format("page {0} of {1}", i, n1 + n2)),
                                    297.5f, 28, 0
                                    );
                                stamp.AlterContents();
                                copy.AddPage(page);
                            }

                            // Loop over the pages of document 2
                            for (int i = 0; i < n2;)
                            {
                                page  = copy.GetImportedPage(reader2, ++i);
                                stamp = copy.CreatePageStamp(page);
                                // add page numbers
                                ColumnText.ShowTextAligned(
                                    stamp.GetUnderContent(), Element.ALIGN_CENTER,
                                    new Phrase(string.Format("page {0} of {1}", n1 + i, n1 + n2)),
                                    297.5f, 28, 0
                                    );
                                stamp.AlterContents();
                                copy.AddPage(page);
                            }
                        }
                    }
                    zip.AddEntry(RESULT, ms.ToArray());
                    zip.AddEntry(Utility.ResultFileName(ml.ToString() + ".pdf"), r1);
                    zip.AddEntry(Utility.ResultFileName(mh.ToString() + ".pdf"), r2);
                }
                zip.Save(stream);
            }
        }
Ejemplo n.º 15
0
        public override void SaveDocument(ViewModels.DocumentViewModel document)
        {
            string srcDocPath;
            string targetFilePath = SafeFilePath(document.DocName);
            Stream stream;

            iTextSharp.text.Image image;
            PdfDictionary         pageDict;
            PdfImportedPage       importedPage;
            PdfContentByte        contentByte;
            //iTextSharp.text.Paragraph para;
            PdfCopy targetPdf;

            iTextSharp.text.Document doc;
            //iTextSharp.text.pdf.BaseFont baseFont;
            //iTextSharp.text.Font font;
            PdfReader srcReader;

            //ColumnText ct;
            PdfCopy.PageStamp pageStamp;

            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(targetFilePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(targetFilePath));
                }

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

                doc       = new iTextSharp.text.Document();
                targetPdf = new PdfCopy(doc, stream);
                doc.Open();

                //baseFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.TIMES_ROMAN, iTextSharp.text.pdf.BaseFont.CP1252, false);
                //font = new iTextSharp.text.Font(baseFont, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);

                foreach (ViewModels.PageViewModel vm in document.Pages)
                {
                    srcDocPath = FileIO.ToTempFileName(vm.DocName);

                    // Copy pageDict from source...
                    if (Path.GetExtension(srcDocPath).ToUpperInvariant() == ".PDF")
                    {
                        srcReader    = new iTextSharp.text.pdf.PdfReader(srcDocPath);
                        pageDict     = srcReader.GetPageN(vm.Number);
                        importedPage = targetPdf.GetImportedPage(srcReader, vm.Number);
                        pageStamp    = targetPdf.CreatePageStamp(importedPage);

                        //add any strings
                        foreach (Common.UIString str in vm.Strings)
                        {
                            ColumnText.ShowTextAligned(pageStamp.GetOverContent(),
                                                       iTextSharp.text.Element.ALIGN_LEFT,
                                                       new iTextSharp.text.Phrase(str.String),
                                                       (float)str.X,
                                                       (float)(importedPage.Height - str.Y - (str.Height * 0.75)),
                                                       0);
                        }
                        // apply any added rotation
                        pageDict.Put(PdfName.ROTATE, new PdfNumber((vm.FlatRotation) % 360f));
                        pageStamp.AlterContents();
                        targetPdf.AddPage(importedPage);

                        targetPdf.FreeReader(srcReader);
                        srcReader.Close();
                    }

                    if (vm.ImageStream != null && targetPdf.NewPage())
                    {
                        contentByte = new PdfContentByte(targetPdf);

                        image = iTextSharp.text.Image.GetInstance(vm.ImageStream);

                        image.ScalePercent(72f / image.DpiX * 100);
                        image.SetAbsolutePosition(0, 0);

                        contentByte.AddImage(image);
                        contentByte.ToPdf(targetPdf);
                    }
                }
                targetPdf.Close();
                doc.Close();
                stream.Close();
            }
            catch (System.IO.IOException e)
            {
                Toolbox.MessageBox(e.Message);
            }
            catch (Exception e)
            {
                Toolbox.MessageBoxException(e);
            }
            finally
            {
                //if (targetPdf != null)
                //    targetPdf.Close();

                //doc.Close();
                //memStream.Close();
            }
        }
Ejemplo n.º 16
0
        private static byte[] merge_files(LinkedList <PageInfo> ll)
        {
            using (Document document = new Document()) {
                using (MemoryStream ms = new MemoryStream()) {
                    PdfCopy copy = new PdfCopy(document, ms);
                    document.Open();
                    int total_pages = count_pages(ll);

                    Rectangle sheet_number_blockhout_ = new Rectangle(1062, 17, 1180, 110);
                    sheet_number_blockhout_.BackgroundColor = BaseColor.WHITE;
                    Rectangle revisions_blockout_ = new Rectangle(817, 17, 1032, 110);
                    revisions_blockout_.BackgroundColor = BaseColor.WHITE;
                    Rectangle item_descr_blockout_ = new Rectangle(605, 17, 787, 110);
                    item_descr_blockout_.BackgroundColor = BaseColor.WHITE;
                    Rectangle item_textarea_ = new Rectangle(605, 78, 787, 110);
                    item_textarea_.BackgroundColor = BaseColor.WHITE;
                    Rectangle item_descr_textarea_ = new Rectangle(605, 17, 787, 78);
                    item_descr_textarea_.BackgroundColor = BaseColor.WHITE;

                    var nd_ = ll.First;
                    while (nd_ != null)
                    {
                        if (nd_.Value.fileInfo == null)
                        {
                            nd_ = nd_.Next;
                            continue;
                        }
                        using (PdfReader rdr_ = new PdfReader(nd_.Value.fileInfo.FullName)) {
                            var sn_    = nd_.Value.FirstSheetNo();
                            var descr_ = nd_.Value.FirstDescription();
                            int pg_    = 1;
                            int document_page_counter = 0;
                            while (sn_ != null)
                            {
                                if (pg_ > rdr_.NumberOfPages)
                                {
                                    sn_ = sn_.Next;
                                    continue;
                                }
                                PdfImportedPage   ip_ = copy.GetImportedPage(rdr_, pg_++);
                                PdfCopy.PageStamp ps_ = copy.CreatePageStamp(ip_);
                                PdfContentByte    cb_ = ps_.GetOverContent();
                                cb_.Rectangle(sheet_number_blockhout_);
                                cb_.Rectangle(revisions_blockout_);
                                cb_.Rectangle(item_descr_blockout_);

                                Font  sheet_number_font_ = FontFactory.GetFont(@"Arial", 31);
                                Chunk sheet_number_      = new Chunk(sn_.Value.ToString(), sheet_number_font_);
                                sheet_number_.SetBackground(BaseColor.WHITE);
                                ColumnText.ShowTextAligned(cb_,
                                                           Element.ALIGN_CENTER,
                                                           new Phrase(sheet_number_),
                                                           1127, 60,
                                                           0);

                                if (nd_.Value.VendorInfo)
                                {
                                    Font   item_descr_font_ = FontFactory.GetFont(@"Tw Cen MT", 17, Font.BOLD);
                                    string desc_            = @"VENDOR INFO";
                                    Chunk  item_descr_      = new Chunk(desc_, item_descr_font_);
                                    sheet_number_.SetBackground(BaseColor.WHITE);
                                    ColumnText.ShowTextAligned(cb_,
                                                               Element.ALIGN_CENTER,
                                                               new Phrase(item_descr_),
                                                               700, 60,
                                                               0);
                                }
                                else
                                {
                                    Font   item_font_ = FontFactory.GetFont(@"Tw Cen MT", 17, Font.BOLD);
                                    string item_name_ = string.Format("{0}", nd_.Value.Name);
                                    Chunk  item_      = new Chunk(item_name_, item_font_);
                                    sheet_number_.SetBackground(BaseColor.WHITE);
                                    ColumnText item_column_ = new ColumnText(cb_);
                                    item_column_.SetSimpleColumn(item_textarea_);
                                    item_column_.SetText(new Phrase(item_));
                                    item_column_.Alignment = Element.ALIGN_CENTER;
                                    item_column_.Go();

                                    Font   item_descr_font_ = FontFactory.GetFont(@"Tw Cen MT", 12, Font.BOLD);
                                    string desc_            = string.Format(@"{0}", descr_.Value);
                                    if (document_page_counter++ > 0 && rdr_.NumberOfPages > 1)
                                    {
                                        desc_ = string.Format(@"SEE SHEET {0}", nd_.Value.FirstSheetNo().Value);
                                    }
                                    Chunk      item_descr_        = new Chunk(desc_, item_descr_font_);
                                    Phrase     ph_                = new Phrase(item_descr_);
                                    ColumnText item_descr_column_ = new ColumnText(cb_);
                                    item_descr_column_.SetSimpleColumn(item_descr_textarea_);
                                    item_descr_column_.SetText(ph_);
                                    item_descr_column_.Alignment = Element.ALIGN_CENTER;
                                    item_descr_column_.Go();
                                }
                                ps_.AlterContents();
                                sn_    = sn_.Next;
                                descr_ = descr_.Next;
                                copy.AddPage(ip_);
                            }
                        }
                        nd_ = nd_.Next;
                    }
                    document.Close();
                    return(ms.GetBuffer());
                }
            }
        }