GetImportedPage() public method

public GetImportedPage ( PdfReader reader, int pageNumber ) : PdfImportedPage
reader PdfReader
pageNumber int
return PdfImportedPage
Esempio n. 1
5
        /// <summary>
        /// Extract a single page from PDF file.
        /// </summary>
        /// <param name="sourceFile">The source file.</param>
        /// <param name="outputFile">The output file.</param>
        /// <param name="pageNumber">The specific page number.</param>
        public static void ExtractPage(string sourceFile, string outputFile, int pageNumber)
        {
            try
            {
                PdfReader reader = new PdfReader(sourceFile);
                if (pageNumber > reader.NumberOfPages)
                {
                    Console.WriteLine("This page number is out of reach.");
                    return;
                }

                Document document = new Document();
                PdfCopy pdfCopy = new PdfCopy(document, new FileStream(outputFile, FileMode.Create));
                document.Open();

                PdfImportedPage importedPage = pdfCopy.GetImportedPage(reader, pageNumber);
                pdfCopy.AddPage(importedPage);

                document.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static bool Collate(string frontSide, string backSide, string saveAs, bool backSideIsInReverseOrder = true)
        {
            try
            {
                bool backSideIsAscending = !backSideIsInReverseOrder;

                using (FileStream stream = new FileStream(saveAs, FileMode.Create))
                using (Document doc = new Document())
                using (PdfCopy pdf = new PdfCopy(doc, stream))
                {
                    doc.Open();

                    int b = 0;

                    using (PdfReader front = new PdfReader(frontSide))
                    {
                        using (PdfReader back = new PdfReader(backSide))
                        {
                            for (int p = 1; p <= front.NumberOfPages; p++)
                            {
                                pdf.AddPage(pdf.GetImportedPage(front, p));

                                pdf.FreeReader(front);

                                if (p <= back.NumberOfPages)
                                {
                                    if (backSideIsAscending)
                                        b = p;
                                    else
                                        b = back.NumberOfPages - p + 1;

                                    pdf.AddPage(pdf.GetImportedPage(back, b));

                                    pdf.FreeReader(back);
                                }
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);

                return false;
            }

            return true;
        }
Esempio n. 3
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);
      }       
    }
Esempio n. 4
0
        public void TestExtraXObjects()
        {
#if DRAWING
            PdfReader sourceR = new PdfReader(CreateImagePdf());
            try
            {
                int sourceXRefCount = sourceR.XrefSize;

                Document document = new Document();
                MemoryStream outStream = new MemoryStream();
                PdfCopy copy = new PdfCopy(document, outStream);
                document.Open();
                PdfImportedPage importedPage = copy.GetImportedPage(sourceR, 1);
                copy.AddPage(importedPage);
                document.Close();

                PdfReader targetR = new PdfReader(outStream.ToArray());
                int destinationXRefCount = targetR.XrefSize;

                //        TestResourceUtils.saveBytesToFile(createImagePdf(), new File("./source.pdf"));
                //        TestResourceUtils.saveBytesToFile(out.toByteArray(), new File("./result.pdf"));

                Assert.AreEqual(sourceXRefCount, destinationXRefCount);
            }
            finally
            {
                sourceR.Close();
            }
#endif// DRAWING
        }
Esempio n. 5
0
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      MovieLinks1 ml = new MovieLinks1();
      MovieHistory mh = new MovieHistory();
      List<byte[]> pdf = new List<byte[]>() {
        Utility.PdfBytes(ml),
        Utility.PdfBytes(mh)
      };
      string[] names = {ml.ToString(), mh.ToString()};
      using (ZipFile zip = new ZipFile()) { 
        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
              for (int i = 0; i < pdf.Count; ++i) {
                zip.AddEntry(Utility.ResultFileName(names[i] + ".pdf"), pdf[i]);
                PdfReader reader = new PdfReader(pdf[i]);
                // loop over the pages in that document
                int n = reader.NumberOfPages;
                for (int page = 0; page < n; ) {
                  copy.AddPage(copy.GetImportedPage(reader, ++page));
                }
              }
            }
          }
          zip.AddEntry(RESULT, ms.ToArray());
        }
        zip.Save(stream);    
      }
    }
Esempio n. 6
0
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // use one of the previous examples to create a PDF
      MovieTemplates mt = new MovieTemplates();
      // Create a reader
      byte[] pdf = Utility.PdfBytes(mt);
      PdfReader reader = new PdfReader(pdf);
      // loop over all the pages in the original PDF
      int n = reader.NumberOfPages;      
      using (ZipFile zip = new ZipFile()) {
        for (int i = 0; i < n; ) {
          string dest = string.Format(RESULT, ++i);
          using (MemoryStream ms = new MemoryStream()) {
// We'll create as many new PDFs as there are pages
            // step 1
            using (Document document = new Document()) {
              // step 2
              using (PdfCopy copy = new PdfCopy(document, ms)) {
                // step 3
                document.Open();
                // step 4
                copy.AddPage(copy.GetImportedPage(reader, i));
              }
            }
            zip.AddEntry(dest, ms.ToArray());
          }
        }
        zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf);
        zip.Save(stream);       
      }
    }
Esempio n. 7
0
        public void ExtractPage(string sourcePdfPath, string outputPdfPath,
            int pageNumber, string password = "")
        {
            PdfReader reader = null;
            Document document = null;
            PdfCopy pdfCopyProvider = null;
            PdfImportedPage importedPage = null;

            try
            {
                // Intialize a new PdfReader instance with the contents of the source Pdf file:
                reader = new PdfReader(sourcePdfPath, Encoding.UTF8.GetBytes(password));

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

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

                document.Open();

                // Extract the desired page number:
                importedPage = pdfCopyProvider.GetImportedPage(reader, pageNumber);
                pdfCopyProvider.AddPage(importedPage);
                document.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 8
0
// ---------------------------------------------------------------------------    
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        // Use previous examples to create PDF files
        MovieLinks1 m = new MovieLinks1(); 
        byte[] pdfM = Utility.PdfBytes(m);
        LinkActions l = new LinkActions();
        byte[] pdfL = l.CreatePdf();
        // Create readers.
        PdfReader[] readers = {
          new PdfReader(pdfL),
          new PdfReader(pdfM)
        };
        
        // step 1
        //Document document = new Document();
        // step 2
        using (var ms = new MemoryStream()) { 
          // step 1
          using (Document document = new Document()) {
            using (PdfCopy copy = new PdfCopy(document, ms)) {
              // step 3
              document.Open();
              // step 4
              int n;
              // copy the pages of the different PDFs into one document
              for (int i = 0; i < readers.Length; i++) {
                readers[i].ConsolidateNamedDestinations();
                n = readers[i].NumberOfPages;
                for (int page = 0; page < n; ) {
                  copy.AddPage(copy.GetImportedPage(readers[i], ++page));
                }
              }
              // Add named destination  
              copy.AddNamedDestinations(
                // from the second document
                SimpleNamedDestination.GetNamedDestination(readers[1], false),
                // using the page count of the first document as offset
                readers[0].NumberOfPages
              );
            }
            zip.AddEntry(RESULT1, ms.ToArray());
          }
          
          // Create a reader
          PdfReader reader = new PdfReader(ms.ToArray());
          // Convert the remote destinations into local destinations
          reader.MakeRemoteNamedDestinationsLocal();
          using (MemoryStream ms2 = new MemoryStream()) {
            // Create a new PDF containing the local destinations
            using (PdfStamper stamper = new PdfStamper(reader, ms2)) {
            }
            zip.AddEntry(RESULT2, ms2.ToArray());
          }
          
        }
        zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdfM);
        zip.AddEntry(Utility.ResultFileName(l.ToString() + ".pdf"), pdfL);
        zip.Save(stream);             
      }   
   }
        public void Combine(string saveFileName, IEnumerable<string> files)
        {
            byte[] mergedPdf = null;
            using (MemoryStream ms = new MemoryStream())
            {
                using (Document document = new Document())
                {
                    using (PdfCopy copy = new PdfCopy(document, ms))
                    {
                        document.Open();

                        foreach (var item in files.OrderBy(x=> x))
                        {
                            PdfReader reader = new PdfReader(item);

                            // loop over the pages in that document
                            int n = reader.NumberOfPages;
                            for (int page = 0; page < n; )
                            {
                                copy.AddPage(copy.GetImportedPage(reader, ++page));
                            }

                            reader.Close();
                        }                        
                    }
                }
                mergedPdf = ms.ToArray();
            }

            File.WriteAllBytes(String.Concat(saveFileName, ".pdf"), mergedPdf);
        }
Esempio n. 10
0
        /// <summary>
        /// Merges multiple pdf files into 1 pdf file.
        /// </summary>
        /// <param name="FilesToMerge">Files to merger (Byte array for each file)</param>
        /// <returns>1 file with all the files passed in</returns>
        public static byte[] MergeFiles(IEnumerable<byte[]> FilesToMerge)
        {
            //Declare the memory stream to use
            using (var MemoryStreamToWritePdfWith = new MemoryStream())
            {
                //declare the new document which we will merge all the files into
                using (var NewFileToMergeIntoWith = new Document())
                {
                    //holds the byte array which we will return
                    byte[] ByteArrayToReturn;

                    //declare the pdf copy to write the data with
                    using (var PdfCopyWriter = new PdfCopy(NewFileToMergeIntoWith, MemoryStreamToWritePdfWith))
                    {
                        //set the page size of the new file
                        //NewFileToMergeIntoWith.SetPageSize(PageSize.GetRectangle("Letter").Rotate().Rotate());

                        //go open the new file that we are writing into
                        NewFileToMergeIntoWith.Open();

                        //now loop through all the files we want to merge
                        foreach (var FileToMerge in FilesToMerge)
                        {
                            //declare the pdf reader so we can copy it
                            using (var PdfFileReader = new PdfReader(FileToMerge))
                            {
                                //figure out how many pages are in this pdf, so we can add each of the pdf's
                                int PdfFilePageCount = PdfFileReader.NumberOfPages;

                                // loop over document pages (start with page 1...not a 0 based index)
                                for (int i = 1; i <= PdfFilePageCount; i++)
                                {
                                    //set the file size for this page
                                    NewFileToMergeIntoWith.SetPageSize(PdfFileReader.GetPageSize(i));

                                    //add a new page for the next page
                                    NewFileToMergeIntoWith.NewPage();

                                    //now import the page
                                    PdfCopyWriter.AddPage(PdfCopyWriter.GetImportedPage(PdfFileReader, i));
                                }
                            }
                        }

                        //now close the new file which we merged everyting into
                        NewFileToMergeIntoWith.Close();

                        //grab the buffer and throw it into a byte array to return
                        ByteArrayToReturn = MemoryStreamToWritePdfWith.GetBuffer();

                        //flush out the memory stream
                        MemoryStreamToWritePdfWith.Flush();
                    }

                    //now return the byte array
                    return ByteArrayToReturn;
                }
            }
        }
Esempio n. 11
0
        private IList<PdfImportedPage> ExtractPagesFromFile(string sourcePdfPath)
        {
            IList<PdfImportedPage> pages = new List<PdfImportedPage>();

            PdfReader reader = new PdfReader(sourcePdfPath);
            PdfCopy pdfCopyProvider = new PdfCopy(new Document(), new MemoryStream());
            for (int i = 0; i < reader.NumberOfPages; i++)
            {
                pages.Add(pdfCopyProvider.GetImportedPage(reader, i + 1));
            }
            return pages;
        }
 /**
  * Creates a new PDF based on the one in the reader
  * @param reader a reader with a PDF file
  * @throws IOException
  * @throws DocumentException
  */
 private void ManipulateWithCopy(PdfReader reader)
 {
     int n = reader.NumberOfPages;
     Document document = new Document();
     PdfCopy copy = new PdfCopy(document, new MemoryStream());
     document.Open();
     for (int i = 0; i < n; )
     {
         copy.AddPage(copy.GetImportedPage(reader, ++i));
     }
     document.Close();
 }
Esempio n. 13
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++)
                    {
                        PdfImportedPage importedPage = copy.GetImportedPage(reader, currentPageIndex);

                        //***************************************
                        // Uncomment and alter for watermarking.
                        //***************************************
                        //
                        //documentPageCounter++;
                        //PdfCopy.PageStamp pageStamp = copy.CreatePageStamp(importedPage);
                        //
                        //// Write header
                        //ColumnText.ShowTextAligned(pageStamp.GetOverContent(), Element.ALIGN_CENTER,
                        //    new Phrase("PDF Merged with me.AxeyWorks PDFMerge"), importedPage.Width / 2, importedPage.Height - 30,
                        //    importedPage.Width < importedPage.Height ? 0 : 1);
                        //
                        //// Write footer
                        //ColumnText.ShowTextAligned(pageStamp.GetOverContent(), Element.ALIGN_CENTER,
                        //    new Phrase($"Page {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();
            }
        }
Esempio n. 14
0
// ---------------------------------------------------------------------------
    /**
     * Creates a new PDF based on the one in the reader
     * @param reader a reader with a PDF file
     */
    private byte[] ManipulateWithCopy(PdfReader reader) {
      using (MemoryStream ms = new MemoryStream()) {
        int n = reader.NumberOfPages;
        using (Document document = new Document()) {
          using (PdfCopy copy = new PdfCopy(document, ms)) {
            document.Open();
            for (int i = 0; i < n;) {
              copy.AddPage(copy.GetImportedPage(reader, ++i));
            }
          }
        }
        return ms.ToArray();
      }
    }    
Esempio n. 15
0
// ---------------------------------------------------------------------------
    /**
     * Fills out a data sheet, flattens it, and adds it to a combined PDF.
     * @param copy the PdfCopy instance (can also be PdfSmartCopy)
     */
    public void AddDataSheets(PdfCopy copy) {
      IEnumerable<Movie> movies = PojoFactory.GetMovies();
      // Loop over all the movies and fill out the data sheet
      foreach (Movie movie in movies) {
        PdfReader reader = new PdfReader(DATASHEET_PATH);
        using (var ms = new MemoryStream()) {
          using (PdfStamper stamper = new PdfStamper(reader, ms)) {
            Fill(stamper.AcroFields, movie);
            stamper.FormFlattening = true;
          }
          reader = new PdfReader(ms.ToArray());
          copy.AddPage(copy.GetImportedPage(reader, 1));
        }
      }
    }    
Esempio n. 16
0
        public static void Merge(string file, string OutFile, ref SetupStationaryFields.addresscollection aic)
        {
            using (FileStream stream = new FileStream(OutFile, FileMode.Create))
            {
                using (Document doc = new Document())
                {
                    using (PdfCopy pdf = new PdfCopy(doc, stream))
                    {
                        doc.Open();

                        PdfReader reader = null;
                        PdfImportedPage page = null;

                        //fixed typo
                        int ii = 0;
                        int count = 0;

                        foreach (SetupStationaryFields.addressitem ai in aic)
                        {

                            if ((!ai.ommitted))
                            {

                                reader = new PdfReader(file);
                                PdfReader.unethicalreading = true;
                                count = reader.NumberOfPages;
                                for (int i = 0; i <= reader.NumberOfPages - 1; i++)
                                {
                                    page = pdf.GetImportedPage(reader, i + 1);
                                    pdf.AddPage(page);
                                }

                                pdf.FreeReader(reader);
                                reader.Close();

                                ai.startpage = ((ii) * count) + 1;
                                ai.endpage = (ii * count) + count;
                                ii = ii + 1;

                            }
                        }
                    }
                }
                stream.Close();
            }
        }
Esempio n. 17
0
        protected override void Convert(ConversionOptions options)
        {
            if (m_sourceFiles != null)
            {
                if (m_sourceFiles.Count == 1 && !m_forceConversion)
                {
                    this.OutputFile = m_sourceFiles[0];
                }
                else
                {
                    try
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (Document doc = new Document(options.Orientation == PageOrientation.Portrait ? PageSize.LETTER : PageSize.LETTER_LANDSCAPE))
                            {
                                PdfCopy copy = new PdfCopy(doc, ms);
                                PdfReader reader;
                                doc.Open();
                                int n;
                                foreach (byte[] file in m_sourceFiles)
                                {
                                    if (file != null)
                                    {
                                        reader = new PdfReader(file);
                                        n = reader.NumberOfPages;
                                        for (int page = 1; page <= n; page++)
                                        {
                                            copy.AddPage(copy.GetImportedPage(reader, page));
                                        }
                                        copy.FreeReader(reader);
                                    }
                                }
                            }

                            this.OutputFile = ms.ToArray();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new ConversionEngineException("Error when merging Pdf files.", null, "pdf", this, ex);
                    }
                }
            }
        }
        // ---------------------------------------------------------------------------  
        /**
         * Manipulates a PDF file src with the file dest as result
         * @param src the original PDF
         */
        public byte[] ManipulatePdf(List<byte[]> src)
        {
            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
                        int page_offset = 0;
                        // Create a list for the bookmarks
                        List<Dictionary<String, Object>> bookmarks =
                            new List<Dictionary<String, Object>>();

                        for (int i = 0; i < src.Count; i++)
                        {
                            PdfReader reader = new PdfReader(src[i]);
                            // merge the bookmarks
                            IList<Dictionary<String, Object>> tmp =
                                SimpleBookmark.GetBookmark(reader);
                            SimpleBookmark.ShiftPageNumbers(tmp, page_offset, null);
                            foreach (var d in tmp) bookmarks.Add(d);

                            // add the pages
                            int n = reader.NumberOfPages;
                            page_offset += n;
                            for (int page = 0; page < n; )
                            {
                                copy.AddPage(copy.GetImportedPage(reader, ++page));
                            }
                        }
                        // Add the merged bookmarks
                        copy.Outlines = bookmarks;
                    }
                }
                return ms.ToArray();
            }
        }
Esempio n. 19
0
        public void CombineMultiplePDFs(string[] fileNames, string outFile)
        {
            // step 1: creation of a document-object
            Document document = new Document();

            // step 2: we create a writer that listens to the document
            PdfCopy writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
            if (writer == null)
            {
                return;
            }

            // step 3: we open the document
            document.Open();

            foreach (string fileName in fileNames)
            {
                // we create a reader for a certain document
                PdfReader reader = new PdfReader(fileName);
                reader.ConsolidateNamedDestinations();

                // step 4: we add content
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    PdfImportedPage page = writer.GetImportedPage(reader, i);
                    writer.AddPage(page);
                }

                PRAcroForm form = reader.AcroForm;
                if (form != null)
                {
                    writer.CopyAcroForm(reader);
                }

                reader.Close();
            }

            // step 5: we close the document and writer
            writer.Close();
            document.Close();
        }
Esempio n. 20
0
        public void ExtractPages(string sourcePdfPath, 
            string outputPdfPath, int[] extractThesePages)
        {
            PdfReader reader = null;
            Document sourceDocument = null;
            PdfCopy pdfCopyProvider = null;
            PdfImportedPage importedPage = null;

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

                // For simplicity, I am assuming all the pages share the same size
                // and rotation as the first page:
                sourceDocument = new Document(reader.GetPageSizeWithRotation(extractThesePages[0]));

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

                sourceDocument.Open();

                // Walk the array and add the page copies to the output file:
                foreach (int pageNumber in extractThesePages)
                {
                    importedPage = pdfCopyProvider.GetImportedPage(reader, pageNumber);
                    pdfCopyProvider.AddPage(importedPage);
                }
                sourceDocument.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 21
0
        public void ExtractPages(string sourcePdfPath, string outputPdfPath,
    int startPage, int endPage, string password = "")
        {
            PdfReader reader = null;
            Document sourceDocument = null;
            PdfCopy pdfCopyProvider = null;
            PdfImportedPage importedPage = null;

            try
            {

                // Intialize a new PdfReader instance with the contents of the source Pdf file:
                reader = new PdfReader(sourcePdfPath, Encoding.UTF8.GetBytes(password));

                // For simplicity, I am assuming all the pages share the same size
                // and rotation as the first page:
                sourceDocument = new Document(reader.GetPageSizeWithRotation(startPage));

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

                sourceDocument.Open();

                // Walk the specified range and add the page copies to the output file:
                for (int i = startPage; i <= endPage; i++)
                {
                    importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                    pdfCopyProvider.AddPage(importedPage);
                }
                sourceDocument.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 22
0
        //99% of credit goes to this person: http://stackoverflow.com/a/20491695
        public static bool Merge(List<string> fullFilePaths, string saveAs)
        {
            try
            {
                using (FileStream stream = new FileStream(saveAs, FileMode.Create))
                using (Document doc = new Document())
                using (PdfCopy pdf = new PdfCopy(doc, stream))
                {
                    doc.Open();

                    PdfReader reader = null;
                    PdfImportedPage page = null;

                    fullFilePaths.ForEach(file =>
                    {
                        using (reader = new PdfReader(file))
                        {
                            for (int i = 0; i < reader.NumberOfPages; i++)
                            {
                                page = pdf.GetImportedPage(reader, i + 1);
                                pdf.AddPage(page);
                            }

                            pdf.FreeReader(reader);
                        }
                    });
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);

                return false;
            }

            return true;
        }
Esempio n. 23
0
        /// <summary>
        /// Create a PDF from a subset of source PDF pages specified in a page range.
        /// </summary>
        /// <param name="FirstPage">first source page</param>
        /// <param name="LastPage">last source page</param>
        /// <param name="srcPath">the source file</param>
        /// <param name="outputPath">New PDF with the specefied pages.</param>
        /// <returns>True if all goes well</returns>
        public static bool RipPdf(int FirstPage, int LastPage, string srcPath, string outputPath)
        {
            bool result = true;

            PdfReader reader = null;
            Document document = null;
            PdfCopy pdfCopyProvider = null;
            PdfImportedPage importedPage = null;

            // Intialize a new PdfReader instance with the contents of the source Pdf file:
            using (reader = new PdfReader(srcPath))
            {

                // For simplicity, I am assuming all the pages share the same size
                // and rotation as the first page:
                using (document = new Document(reader.GetPageSizeWithRotation(FirstPage)))
                {

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

                    document.Open();

                    // Walk the specified range and add the page copies to the output file:
                    for (int i = FirstPage; i <= LastPage; i++)
                    {
                        importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                        pdfCopyProvider.AddPage(importedPage);
                    }

                }//Dispose of document
            }//Dispose of reader

            return result;
        }
Esempio n. 24
0
        /// <summary>
        /// Extract pages from a pdf file.
        /// </summary>
        /// <param name="source">The source file.</param>
        /// <param name="output">The output file.</param>
        /// <param name="startPage">The start page.</param>
        /// <param name="endPage">The last page.</param>
        public static void ExtractPages(string source, string output, int startPage, int endPage)
        {
            try
            {
                PdfReader reader = new PdfReader(source);
                Document document = new Document();

                PdfCopy pdfCopy = new PdfCopy(document, new FileStream(output, FileMode.Create));

                document.Open();
                for (int i = startPage; i <= endPage; i++)
                {
                    PdfImportedPage importedPage = pdfCopy.GetImportedPage(reader, i);
                    pdfCopy.AddPage(importedPage);
                }

                document.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Merge multiple pdf files into one pdf file.
        /// </summary>
        /// <param name="sources">The source files.</param>
        /// <param name="outputFile">The output file.</param>
        public static void Merge(string[] sources, string outputFile)
        {
            try
            {
                Document document = new Document();
                PdfCopy pdfCopy = new PdfCopy(document, new FileStream(outputFile, FileMode.Create));

                document.Open();
                foreach (var source in sources)
                {
                    PdfReader reader = new PdfReader(source);
                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfImportedPage page = pdfCopy.GetImportedPage(reader, i);
                        pdfCopy.AddPage(page);
                    }
                    reader.Close();
                }

                pdfCopy.Close();
                document.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 26
0
        private void bCreatePDF_Click(Object sender, EventArgs e)
        {
            Match match = Regex.Match(tb_pages.Text, @"^(\d+|\d+-\d+)(,(\d+|\d+-\d+))*$");

            if (match.Success)
            {

                // Grab pages from text box
                List<int> pages = getNums(tb_pages.Text);

                PdfReader pdfReader = new PdfReader(openPDF_Dialog.FileName);
                int numberOfPages = pdfReader.NumberOfPages;
                bool page_validates = true;

                foreach (int p in pages)
                {
                    if (p > numberOfPages)
                    {
                        page_validates = false;
                    }
                }

                if (pages.Any() && page_validates)
                {

                    SaveFileDialog savePDF_Dialog = new SaveFileDialog();
                    savePDF_Dialog.Filter = "pdf files (*.pdf)|*.pdf";
                    savePDF_Dialog.FilterIndex = 2;
                    savePDF_Dialog.RestoreDirectory = false;

                    string save_path = "";

                    if (savePDF_Dialog.ShowDialog() == DialogResult.OK)
                    {
                        save_path = savePDF_Dialog.FileName;
                    }

                    pages.Sort();

                    PdfReader reader = null;
                    Document document = null;
                    PdfCopy pdfCopyProvider = null;
                    PdfImportedPage importedPage = null;

                    try
                    {
                        reader = new PdfReader(openPDF_Dialog.FileName);

                        string extracted_pdf_name = "";
                        if (String.IsNullOrEmpty(save_path))
                        {
                            // User willfully canceled saving... do nothing
                        }
                        else
                        {
                            extracted_pdf_name = save_path;

                            Console.Out.WriteLine(extracted_pdf_name);
                            document = new Document(reader.GetPageSizeWithRotation(pages[0]));

                            pdfCopyProvider = new PdfCopy(document, new FileStream(extracted_pdf_name, FileMode.Create));
                            document.Open();

                            foreach (int p in pages)
                            {
                                importedPage = pdfCopyProvider.GetImportedPage(reader, p);
                                pdfCopyProvider.AddPage(importedPage);
                            }

                            document.Close();
                            reader.Close();

                            tb_pages.Clear();

                            tb_pages.Enabled = false;
                            bCreatePDF.Enabled = false;
                            lPathPDF.Text = "No PDF File Selected...";

                            MessageBox.Show($"PDF Created at: {extracted_pdf_name}");

                            pdfViewer.LoadFile("meh.pdf");
                            selectedPages.Clear();
                            cbPageSelected.Checked = false;
                            bPrevPage.Enabled = false;
                            bNextPage.Enabled = false;
                            cbPageSelected.Enabled = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.Out.WriteLine(ex.Message);
                    }
                }
                else
                {
                    MessageBox.Show("ERROR: Invalid format in Pages entry.\n\nOnly numbers, dashes, and commas are accepted.\nCheck your date ranges to make sure they're correct.\nMake sure pages entered fall within source PDF page range.");
                }
            }
            else
            {
                MessageBox.Show("ERROR: Invalid format in Pages entry.\n\nOnly numbers, dashes, and commas are accepted.\nCheck your date ranges to make sure they're correct.\nMake sure pages entered fall within source PDF page range.");
            }
        }
Esempio n. 27
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (openFile1.SafeFileName == "" || openFile2.SafeFileName == "")
            {
                MessageBox.Show("No haz seleccionado ningún PDF", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            MessageBox.Show("Se unira \"" + openFile1.SafeFileName + "\" con \"" + openFile2.SafeFileName + "\"");
            saveFile.Filter = "Adobe Acrobat Document PDF (*.pdf)|*.pdf";
            saveFile.FilterIndex = 1;
            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show("Se guardara en la siguiente ruta:\n" + saveFile.FileName);

                FileStream myStream = new FileStream(saveFile.FileName,FileMode.OpenOrCreate);

                PdfReader reader  = new PdfReader(openFile1.FileName);
                PdfReader reader2 = new PdfReader(openFile2.FileName);
                Document document = new Document(reader.GetPageSizeWithRotation(1));
                PdfCopy writer = new PdfCopy(document, myStream);
                document.Open();
                document.AddCreationDate();
                if (txtAutor.Text != null)
                {
                    document.AddAuthor(txtAutor.Text);
                }
                if (txtHeader.Text != null)
                {
                    document.AddHeader(txtHeader.Text, "Document");
                }
                if (txtKeywords.Text != null)
                {
                    document.AddKeywords(txtKeywords.Text);
                }

                document.AddProducer();

                if (txtTitulo.Text != null)
                {
                    document.AddTitle(txtTitulo.Text);
                }
                // Calculando incremento
                progressBar.Refresh();
                int incremento = (int)(100 / (reader.NumberOfPages + reader2.NumberOfPages));
                MessageBox.Show("Incremento es: " + incremento);
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    writer.AddPage(writer.GetImportedPage(reader, i));
                    progressBar.PerformStep();
                    progressBar.Increment(++incremento);
                }
                progressBar.Increment(50);
                for (int i = 1; i <= reader2.NumberOfPages; i++)
                {
                    writer.AddPage(writer.GetImportedPage(reader2, i));
                    progressBar.PerformStep();
                }
                progressBar.Increment(100);
                document.Close();
            }
        }
        private void InsertDestinationsIntoDocument(string document, IEnumerable<INamedDestination> nameddests)
        {
            if (!File.Exists(document))
                throw new FileNotFoundException("Document not found.", document);

            var extensionIndex = document.IndexOf(".pdf");
            var tempDoc = document.Substring(0, extensionIndex) + "-2.pdf";
            var doc = new Document();
            var copy = new PdfCopy(doc, new FileStream(tempDoc, FileMode.Create));
            doc.Open();
            var reader = new PdfReader(document);
            copy.Outlines = GetBookmarksFromDocument(document).ToList();
            for (int page = 0; page < reader.NumberOfPages; )
            {
                copy.AddPage(copy.GetImportedPage(reader, ++page));
            }
            foreach (var destination in nameddests)
            {
                copy.AddNamedDestination(destination.Name, destination.Page, destination.Destination);
            }
            copy.FreeReader(reader);
            reader.Close();
            doc.Close();
            // TODO: Uniqueness tests?
        }
		public static void CombineMultiplePDFs(string[] fileNames, string outFile)
		{
			try
			{
				iTextSharp.text.Document document = new iTextSharp.text.Document();
				PdfCopy writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
				if (writer == null)
				{
					return;
				}
				document.Open();

				foreach (string fileName in fileNames)
				{
					if (System.IO.File.Exists(fileName))
					{
						PdfReader reader = new PdfReader(fileName);
						reader.ConsolidateNamedDestinations();
						for (int i = 1; i <= reader.NumberOfPages; i++)
						{
							PdfImportedPage page = writer.GetImportedPage(reader, i);
							writer.AddPage(page);
						}

						PRAcroForm form = reader.AcroForm;
						if (form != null)
						{
							writer.CopyDocumentFields(reader);
						}
						reader.Close();
					}
				}
				writer.Close();
				document.Close();

			}
			catch
			{
				MessageBox.Show("Close the pdf file and try again.");
			}

		}
Esempio n. 30
-1
 /// <summary>
 /// Concatenates two or more PDF files into one file.
 /// </summary>
 /// <param name="inputFiles">A string array containing the names of the pdf files to concatenate</param>
 /// <param name="outputFile">Name of the concatenated file.</param>
 public void ConcatenatePDFFiles(String[] inputFiles, String outputFile)
 {
     if (inputFiles != null && inputFiles.Length > 0)
     {
         if (!String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile))
         {
             var concatDocument = new iTextSharpText.Document();
             var outputCopy = new iTextSharpPDF.PdfCopy(concatDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite));
             concatDocument.Open();
             try
             {
                 for (int loop = 0; loop <= inputFiles.GetUpperBound(0); loop++)
                 {
                     var inputDocument = new iTextSharpPDF.PdfReader(inputFiles[loop]);
                     for (int pageLoop = 1; pageLoop <= inputDocument.NumberOfPages; pageLoop++)
                     {
                         concatDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(pageLoop));
                         outputCopy.AddPage(outputCopy.GetImportedPage(inputDocument, pageLoop));
                     }
                     inputDocument.Close();
                     outputCopy.FreeReader(inputDocument);
                     inputDocument = null;
                 }
                 concatDocument.Close();
                 outputCopy.Close();
             }
             catch
             {
                 if (concatDocument != null && concatDocument.IsOpen()) concatDocument.Close();
                 if (outputCopy != null) outputCopy.Close();
                 if (File.Exists(outputFile))
                 {
                     try
                     {
                         File.Delete(outputFile);
                     }
                     catch { }
                 }
                 throw;
             }
         }
         else
         {
             throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString);
         }
     }
     else
     {
         throw new ArgumentNullException("inputFiles", exceptionArgumentNullOrEmptyString);
     }
 }