當前位置: 首頁>>代碼示例>>C#>>正文


C# PdfCopy.Close方法代碼示例

本文整理匯總了C#中iTextSharp.text.pdf.PdfCopy.Close方法的典型用法代碼示例。如果您正苦於以下問題:C# PdfCopy.Close方法的具體用法?C# PdfCopy.Close怎麽用?C# PdfCopy.Close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在iTextSharp.text.pdf.PdfCopy的用法示例。


在下文中一共展示了PdfCopy.Close方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: CombineMultiplePDFs

        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();
        }
開發者ID:rayanc,項目名稱:Pecuniaus,代碼行數:41,代碼來源:PdfHelper.cs

示例2: Merge

        /// <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;
            }
        }
開發者ID:cserspring,項目名稱:pdf_split_merge,代碼行數:32,代碼來源:PdfUtilities.cs

示例3: CombineMultiplePDFs

		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.");
			}

		}
開發者ID:sanyak073,項目名稱:SurplusFundsEntry,代碼行數:42,代碼來源:MainWindow.xaml.cs

示例4: LargeFilePerformanceTest

        public virtual void LargeFilePerformanceTest() {
            const string target = "PdfCopyTest/";
            const string output = "copyLargeFile.pdf";
            const string cmp = "cmp_copyLargeFile.pdf";
            
            Directory.CreateDirectory(target);

            Stopwatch timer = new Stopwatch();
            timer.Start();

            PdfReader firstSourceReader = new PdfReader(RESOURCES + "frontpage.pdf");
            PdfReader secondSourceReader = new PdfReader(RESOURCES + "large_pdf.pdf");

            Document document = new Document();

            PdfCopy copy = new PdfCopy(document, File.Create(target + output));
            copy.SetMergeFields();

            document.Open();
            copy.AddDocument(firstSourceReader);
            copy.AddDocument(secondSourceReader);

            copy.Close();
            document.Close();

            timer.Stop();
            Console.WriteLine(timer.ElapsedMilliseconds);

            CompareTool cmpTool = new CompareTool();
            String errorMessage = cmpTool.CompareByContent(target + output, RESOURCES + cmp, target, "diff");

            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
開發者ID:newlysoft,項目名稱:itextsharp,代碼行數:35,代碼來源:PdfCopyTest.cs

示例5: CopyFields4Test

        public virtual void CopyFields4Test() {
            string target = "PdfCopyTest/";
            Directory.CreateDirectory(target);
            const string outfile = "copyFields4.pdf";
            const string inputFile = "link.pdf";

            Document document = new Document();
            MemoryStream stream = new MemoryStream();
            PdfWriter.GetInstance(document, stream);
            Font font = new Font(BaseFont.CreateFont(RESOURCES + "fonts/georgia.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 9);
            document.Open();
            document.Add(new Phrase("text", font));
            document.Close();

            Document pdfDocument = new Document();
            PdfCopy copier = new PdfCopy(pdfDocument, new FileStream(target + outfile, FileMode.Create));
            copier.SetMergeFields();
            pdfDocument.Open();

            PdfReader reader1 = new PdfReader(RESOURCES + inputFile);
            PdfReader reader2 = new PdfReader(stream.ToArray());

            copier.AddDocument(reader1);
            copier.AddDocument(reader2);
            copier.Close();
            CompareTool cmpTool = new CompareTool();
            string errorMessage = cmpTool.CompareByContent(target + outfile, RESOURCES + "cmp_" + outfile, target, "diff");
            if (errorMessage != null)
                Assert.Fail(errorMessage);
        }
開發者ID:newlysoft,項目名稱:itextsharp,代碼行數:30,代碼來源:PdfCopyTest.cs

示例6: CopyFields3Test

        public virtual void CopyFields3Test() {
            Document pdfDocument = new Document();
            Directory.CreateDirectory("PdfCopyTest/");
            PdfCopy copier = new PdfCopy(pdfDocument, new FileStream("PdfCopyTest/copyFields3.pdf", FileMode.Create));
            copier.SetMergeFields();
            pdfDocument.Open();

            PdfReader reader = new PdfReader(RESOURCES + "hello2_with_comments.pdf");
            copier.AddDocument(reader);
            copier.Close();
            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent("PdfCopyTest/copyFields3.pdf", RESOURCES + "cmp_copyFields3.pdf", "PdfCopyTest/", "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
開發者ID:newlysoft,項目名稱:itextsharp,代碼行數:16,代碼來源:PdfCopyTest.cs

示例7: CopyFields1Test

        public virtual void CopyFields1Test() {
            Document pdfDocument = new Document();
            Directory.CreateDirectory("PdfCopyTest/");
            PdfCopy copier = new PdfCopy(pdfDocument, new FileStream("PdfCopyTest/copyFields.pdf", FileMode.Create));
            copier.SetMergeFields();

            pdfDocument.Open();

            PdfReader readerMain = new PdfReader(RESOURCES + "fieldsOn3-sPage.pdf");
            PdfReader secondSourceReader = new PdfReader(RESOURCES + "fieldsOn2-sPage.pdf");
            PdfReader thirdReader = new PdfReader(RESOURCES + "appearances1.pdf");

            copier.AddDocument(readerMain);
            copier.CopyDocumentFields(secondSourceReader);
            copier.AddDocument(thirdReader);

            copier.Close();
            readerMain.Close();
            secondSourceReader.Close();
            thirdReader.Close();
            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent("PdfCopyTest/copyFields.pdf", RESOURCES + "cmp_copyFields.pdf", "PdfCopyTest/", "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
開發者ID:newlysoft,項目名稱:itextsharp,代碼行數:26,代碼來源:PdfCopyTest.cs

示例8: TestFullCompression2

        public virtual void TestFullCompression2() {
            Directory.CreateDirectory("PdfCopyTest/");
            String outfile = "PdfCopyTest/out-forms.pdf";
            String first = RESOURCES + "subscribe.pdf";
            String second = RESOURCES + "filled_form_1.pdf";
            FileStream out_ = new FileStream(outfile, FileMode.Create);
            PdfReader reader = new PdfReader(first);
            PdfReader reader2 = new PdfReader(second);
            Document pdfDocument = new Document();
            PdfCopy pdfCopy = new PdfCopy(pdfDocument, out_);
            pdfCopy.SetMergeFields();
            pdfCopy.SetFullCompression();
            pdfCopy.CompressionLevel = PdfStream.BEST_COMPRESSION;
            pdfDocument.Open();
            pdfCopy.AddDocument(reader);
            pdfCopy.AddDocument(reader2);
            pdfCopy.Close();
            reader.Close();
            reader2.Close();

            reader = new PdfReader("PdfCopyTest/out-forms.pdf");
            Assert.NotNull(reader.GetPageN(1));
            reader.Close();
        }
開發者ID:newlysoft,項目名稱:itextsharp,代碼行數:24,代碼來源:PdfCopyTest.cs

示例9: TestNeedAppearancesMixed

        public virtual void TestNeedAppearancesMixed() {
            String f1 = RESOURCES + "appearances1.pdf";
            String f2 = RESOURCES + "appearances2(needAppearancesFalse).pdf";
            String f3 = RESOURCES + "appearances3(needAppearancesFalseWithStreams).pdf";
            String f4 = RESOURCES + "appearances4.pdf";

            Directory.CreateDirectory("PdfCopyTest/");
            FileStream outputPdfStream =
                new FileStream("PdfCopyTest/appearances(mixed).pdf", FileMode.Create);
            Document document = new Document();
            PdfCopy copy = new PdfCopy(document, outputPdfStream);
            copy.SetMergeFields();
            document.Open();
            foreach (String f in new String[] {f1, f2, f3, f4}) {
                PdfReader r = new PdfReader(f);
                copy.AddDocument(r);
            }
            copy.Close();
            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent("PdfCopyTest/appearances(mixed).pdf", RESOURCES + "cmp_appearances(mixed).pdf", "PdfCopyTest/", "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
開發者ID:newlysoft,項目名稱:itextsharp,代碼行數:24,代碼來源:PdfCopyTest.cs

示例10: GenerarReporte

        private string GenerarReporte()
        {
            GenerarAnverso();
            GenerarReverso();
            var fileAnversoMarca = fileAnverso;
            var fileReversoMarca = fileReverso;

            if(pedido.EstadoPedido == "C")
            {
                fileAnversoMarca = MarcaCancelado(fileAnverso);
            }

            var anversoReader = new PdfReader(fileAnversoMarca);
            var reversoReader = new PdfReader(fileReversoMarca);

            var document = new Document(PageSize.LETTER.Rotate(), 10, 10, 10, 10);

            var filePedido = Path.GetTempFileName() + ".pdf";

            var copy = new PdfCopy(document, new FileStream(filePedido, FileMode.Create));

            document.Open();

            for (var page = 1; page <= anversoReader.NumberOfPages; page++)
            {
                copy.AddPage(copy.GetImportedPage(anversoReader, page));
                copy.AddPage(copy.GetImportedPage(reversoReader, 1));
            }

            copy.Close();
            anversoReader.Close();
            reversoReader.Close();

            File.Delete(fileReversoMarca);
            File.Delete(fileAnversoMarca);
            File.Delete(fileAnverso);
            File.Delete(fileReverso);

            return filePedido;
        }
開發者ID:bulbix,項目名稱:adquisiciones,代碼行數:40,代碼來源:ReportePedido.cs

示例11: EvenOddMerge

        /// <summary>
        /// Takes pages from two pdf files, and produces an output file
        /// whose odd pages are the contents of the first, and
        /// even pages are the contents of the second. Useful for
        /// merging front/back output from single sided scanners.
        /// </summary>
        /// <param name="oddPageFile">The file supplying odd numbered pages</param>
        /// <param name="evenPageFile">The file supplying even numbered pages</param>
        /// <param name="outputFile">The output file containing the merged pages</param>
        /// <param name="skipExtraPages">Set to true to skip any extra pages if
        ///                              one file is longer than the other</param>
        public void EvenOddMerge(String oddPageFile, String evenPageFile, 
                                 String outputFile, bool skipExtraPages)
        {
            if (!String.IsNullOrEmpty(oddPageFile) && !String.IsNullOrWhiteSpace(oddPageFile) &&
                !String.IsNullOrEmpty(evenPageFile) && !String.IsNullOrWhiteSpace(evenPageFile) &&
                !String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile))
            {
                var oddPageDocument = new iTextSharpPDF.PdfReader(oddPageFile);
                var evenPageDocument = new iTextSharpPDF.PdfReader(evenPageFile);
                try
                {
                    iTextSharpText.Document mergedOutputDocument = null;
                    iTextSharpPDF.PdfCopy mergedOutputFile = null;

                    int lastPage = 0;
                    switch (skipExtraPages)
                    {
                        case (false):
                            lastPage = oddPageDocument.NumberOfPages;
                            if (evenPageDocument.NumberOfPages > oddPageDocument.NumberOfPages)
                                lastPage = evenPageDocument.NumberOfPages;
                            else
                                lastPage = oddPageDocument.NumberOfPages;
                            break;
                        case (true):
                            if (evenPageDocument.NumberOfPages < oddPageDocument.NumberOfPages)
                                lastPage = evenPageDocument.NumberOfPages;
                            else
                                lastPage = oddPageDocument.NumberOfPages;
                            break;
                    }

                    try
                    {
                        mergedOutputDocument = new iTextSharpText.Document();
                        mergedOutputFile = new iTextSharpPDF.PdfCopy(mergedOutputDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite));
                        mergedOutputDocument.Open();
                        for (int loop = 1; loop <= lastPage; loop++)
                        {
                            // Extract and merge odd page
                            if (loop <= oddPageDocument.NumberOfPages)
                            {
                                mergedOutputDocument.SetPageSize(oddPageDocument.GetPageSizeWithRotation(loop));
                                mergedOutputFile.AddPage(mergedOutputFile.GetImportedPage(oddPageDocument, loop));
                            }
                            // Extract and merge even page
                            if (loop <= evenPageDocument.NumberOfPages)
                            {
                                mergedOutputDocument.SetPageSize(evenPageDocument.GetPageSizeWithRotation(loop));
                                mergedOutputFile.AddPage(mergedOutputFile.GetImportedPage(evenPageDocument, loop));
                            }
                        }
                    }
                    finally
                    {
                        if (mergedOutputDocument != null && mergedOutputDocument.IsOpen()) mergedOutputDocument.Close();
                        if (mergedOutputFile != null)
                        {
                            mergedOutputFile.Close();
                            mergedOutputFile.FreeReader(oddPageDocument);
                            mergedOutputFile.FreeReader(evenPageDocument);
                        }
                    }
                }
                catch
                {
                    try
                    {
                        File.Delete(outputFile);
                    }
                    catch { }
                    throw;
                }
                finally
                {
                    try
                    {
                        if (oddPageDocument != null) oddPageDocument.Close();
                        oddPageDocument = null;
                    }
                    catch { }
                    try
                    {
                        if (evenPageDocument != null) evenPageDocument.Close();
                        evenPageDocument = null;
                    }
                    catch { }
                }
            }
//.........這裏部分代碼省略.........
開發者ID:stchan,項目名稱:PdfMiniTools,代碼行數:101,代碼來源:CoreTools.cs

示例12: SplitPDF

        /// <summary>
        /// 
        /// </summary>
        /// <param name="inputFile">The PDF file to split</param>
        /// <param name="splitStartPages"></param>
        public void SplitPDF(String inputFile, SortedList<int, String> splitStartPages)
        {
            if (!String.IsNullOrEmpty(inputFile) &&
                !String.IsNullOrWhiteSpace(inputFile) &&
                splitStartPages != null &&
                splitStartPages.Count >= 2)
            {
                var inputDocument = new iTextSharpPDF.PdfReader(inputFile);
                // First split must begin with page 1
                // Last split must not be higher than last page
                if (splitStartPages.Keys[0] == 1 &&
                    splitStartPages.Keys[splitStartPages.Count - 1] <= inputDocument.NumberOfPages)
                {
                    int currentPage = 1;
                    int firstPageOfSplit;
                    int lastPageOfSplit;
                    try
                    {
                        for (int splitPoint = 0; splitPoint <= (splitStartPages.Count - 1); splitPoint++)
                        {
                            firstPageOfSplit = currentPage;
                            if (splitPoint < (splitStartPages.Count - 1))
                            {
                                lastPageOfSplit = splitStartPages.Keys[splitPoint + 1] - 1;
                            }
                            else
                            {
                                lastPageOfSplit = inputDocument.NumberOfPages;
                            }
                            iTextSharpText.Document splitDocument = null;
                            iTextSharpPDF.PdfCopy splitOutputFile = null;
                            try
                            {
                                splitDocument = new iTextSharpText.Document();
                                splitOutputFile = new iTextSharpPDF.PdfCopy(splitDocument, new FileStream(splitStartPages.Values[splitPoint], FileMode.Create, FileAccess.ReadWrite));
                                splitDocument.Open();
                                for (int outputPage = firstPageOfSplit; outputPage <= lastPageOfSplit; outputPage++)
                                {
                                    splitDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(currentPage));
                                    splitOutputFile.AddPage(splitOutputFile.GetImportedPage(inputDocument, currentPage));
                                    currentPage++;
                                }
                            }
                            finally
                            {
                                if (splitDocument != null && splitDocument.IsOpen()) splitDocument.Close();
                                if (splitOutputFile != null)
                                {
                                    splitOutputFile.Close();
                                    splitOutputFile.FreeReader(inputDocument);
                                }
                                splitDocument = null;
                                splitOutputFile = null;
                            }
                        }
                    }
                    catch
                    {
                        // Cleanup any files that may have
                        // been written
                        foreach (KeyValuePair<int, String> split in splitStartPages)
                        {
                            try
                            {
                                File.Delete(split.Value);
                            }
                            catch { }
                        }
                        throw;
                    }
                    finally
                    {
                        if (inputDocument != null) inputDocument.Close();
                    }

                }
                else
                {
                    if (splitStartPages.Keys[splitStartPages.Count - 1] > inputDocument.NumberOfPages) throw new ArgumentOutOfRangeException("splitStartPages", String.Format("Final page number must be less than the number of pages ({0}). Passed value is {1}.", inputDocument.NumberOfPages, splitStartPages.Keys[splitStartPages.Count - 1]));
                    throw new ArgumentOutOfRangeException("splitStartPages", "First page number must be 1.");
                }
            }
            else
            {
                if (inputFile == null) throw new ArgumentNullException("inputFile", exceptionArgumentNullOrEmptyString);
                if (splitStartPages == null) throw new ArgumentNullException("splitStartPages", exceptionArgumentNullOrEmptyString);
                throw new ArgumentOutOfRangeException("splitStartPages", "Must contain at least two KeyValue pairs.");
            }
        }
開發者ID:stchan,項目名稱:PdfMiniTools,代碼行數:94,代碼來源:CoreTools.cs

示例13: ExtractPDFPages

        /// <summary>
        /// Extracts a range of pages from a PDF file,
        /// and writes them to a new file.
        /// </summary>
        /// <param name="inputFile">The PDF to extract pages from.</param>
        /// <param name="outputFile">The new file to write the extracted pages to.</param>
        /// <param name="firstPage">The first page to extract.</param>
        /// <param name="lastPage">The last page to extract.</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <remarks><see cref="FileStream"/> constructor exceptions may also be thrown.</remarks>
        public void ExtractPDFPages(String inputFile, String outputFile, int firstPage, int lastPage)
        {
            if (!String.IsNullOrEmpty(inputFile) && !String.IsNullOrWhiteSpace(inputFile) &&
                !String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile) &&
                firstPage > 0 && lastPage > 0 &&
                lastPage >= firstPage)
            {
                var inputDocument = new iTextSharpPDF.PdfReader(inputFile);
                try
                {
                    // Page numbers specified must not be greater
                    // than the number of pages in the document
                    if (firstPage <= inputDocument.NumberOfPages &&
                        lastPage <= inputDocument.NumberOfPages)
                    {
                        iTextSharpText.Document extractOutputDocument = null;
                        iTextSharpPDF.PdfCopy extractOutputFile = null;
                        try
                        {
                            extractOutputDocument = new iTextSharpText.Document();
                            extractOutputFile = new iTextSharpPDF.PdfCopy(extractOutputDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite));
                            extractOutputDocument.Open();
                            for (int loop = firstPage; loop <= lastPage; loop++)
                            {
                                extractOutputDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(loop));
                                extractOutputFile.AddPage(extractOutputFile.GetImportedPage(inputDocument, loop));
                            }
                        }
                        finally
                        {
                            if (extractOutputDocument != null && extractOutputDocument.IsOpen()) extractOutputDocument.Close();
                            if (extractOutputFile != null)
                            {
                                extractOutputFile.Close();
                                extractOutputFile.FreeReader(inputDocument);
                            }
                        }
                    }
                    else
                    {
                        if (firstPage > inputDocument.NumberOfPages) throw new ArgumentOutOfRangeException("firstPage", String.Format(exceptionParameterCannotBeGreaterThan,"firstPage", "the number of pages in the document."));
                        throw new ArgumentOutOfRangeException("lastPage", String.Format(exceptionParameterCannotBeGreaterThan,"firstPage", "the number of pages in the document."));
                    }

                }
                catch
                {
                    try
                    {
                        File.Delete(outputFile);
                    }
                    catch { }
                    throw;

                }
                finally
                {
                    if (inputDocument != null) inputDocument.Close();
                    inputDocument = null;
                }
            }
            else
            {
                if (String.IsNullOrEmpty(inputFile) || String.IsNullOrWhiteSpace(inputFile)) throw new ArgumentNullException("inputFile", exceptionArgumentNullOrEmptyString);
                if (String.IsNullOrEmpty(outputFile) || String.IsNullOrWhiteSpace(outputFile)) throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString);
                if (firstPage < 1) throw new ArgumentOutOfRangeException("firstPage", exceptionArgumentZeroOrNegative);
                if (lastPage < 1) throw new ArgumentOutOfRangeException("lastPage", exceptionArgumentZeroOrNegative);
                if (lastPage < firstPage) throw new ArgumentOutOfRangeException("lastPage", String.Format(exceptionParameterCannotBeLessThan, "lastPage", "firstPage"));
            }
        }
開發者ID:stchan,項目名稱:PdfMiniTools,代碼行數:81,代碼來源:CoreTools.cs

示例14: SplitWorkerDoWork

        private void SplitWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            object[] args = (object[])e.Argument;
            PdfFile pdfFile = (PdfFile)args[0];
            PageRangeParser pageRangeParser = (PageRangeParser)args[1];
            string destinationPath = (string)args[2];
            bool overwriteFile = (bool)args[3];
            FileStream outFileStream = null;
            Document destinationDoc = null;
            PdfCopy pdfCopy = null;
            int skippedFiles = 0;
            string exportFileName = string.Empty;
            string errorMsg = string.Empty;
            int exportFileCnt = 0, totalNumberOPages = 0, pageCnt = 0;
            EasySplitAndMergePdf.Helper.PageRange[] pageRanges = null;

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

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

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

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

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

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

                        if (outFileStream != null)
//.........這裏部分代碼省略.........
開發者ID:Mohamed1976,項目名稱:EasySplitAndMergePdf,代碼行數:101,代碼來源:SplitPdfViewModel.cs

示例15: ConcatenatePDFFiles

 /// <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);
     }
 }
開發者ID:stchan,項目名稱:PdfMiniTools,代碼行數:56,代碼來源:CoreTools.cs


注:本文中的iTextSharp.text.pdf.PdfCopy.Close方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。