Ejemplo n.º 1
0
        /// <summary>
        /// Append source files to the end of original file.
        /// </summary>
        /// <param name="sourceFiles">The list of source files</param>
        /// <param name="originalFile">Original file to append source files to the end of it</param>
        public void Append(string[] sourceFiles, string originalFile)
        {
            PdfDocument pdfOriginal = null;
            PdfDocument pdfTemp     = null;
            PdfMerger   pdfMerger   = null;

            try
            {
                pdfOriginal = new PdfDocument(new PdfReader(originalFile));

                // Step 1: Temporary file to prevent rewrite on the original file.
                //         Destination file will be changed with the original in the last step.
                //         In case if the destination file in an existing file
                pdfTemp   = new PdfDocument(new PdfWriter(originalFile + "temp"));
                pdfMerger = new PdfMerger(pdfTemp);

                // Step 2: First add the original file content.
                pdfMerger.Merge(pdfOriginal, 1, pdfOriginal.GetNumberOfPages());

                // Step 3: Then add the other source file content
                for (var i = 0; i < sourceFiles.Length; i++)
                {
                    using (var sourceFile = new PdfDocument(new PdfReader(sourceFiles[i])))
                    {
                        pdfMerger.Merge(sourceFile, 1, sourceFile.GetNumberOfPages());

                        // Update merge job progress.
                        OnUpdateProgress?.Invoke(i);
                    }
                }

                pdfTemp.Close();
                pdfOriginal.Close();
                pdfMerger.Close();

                // Step 4: Replace the original file with the temp one.
                File.Delete(originalFile);
                File.Move(originalFile + "temp", originalFile);
            }
            catch (Exception e)
            {
                if (pdfTemp != null && !pdfTemp.IsClosed())
                {
                    pdfTemp.Close();
                    pdfOriginal.Close();
                    pdfMerger?.Close();
                }

                File.Delete(originalFile + "temp");
                throw new Exception(e.Message);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Split specific pages from the source file and save them in the destination file.
        /// </summary>
        /// <param name="sourceFile">The source file to split pages from it</param>
        /// <param name="destinationFile">The destination file to save splitted pages into it</param>
        /// <param name="pageRange">Specific pages to split them</param>
        public void Split(string sourceFile, string destinationFile, int[] pageRange)
        {
            PdfDocument pdfDestination = null;
            PdfDocument pdfSource      = null;
            PdfMerger   pdfMerger      = null;

            try
            {
                // Step 1: Temporary file to prevent rewrite on the original file.
                //         Destination file will be changed with the original in the last step.
                //         In case if the destination file in an existing file
                pdfDestination = new PdfDocument(new PdfWriter(destinationFile + "temp"));
                pdfMerger      = new PdfMerger(pdfDestination);

                pdfSource = new PdfDocument(new PdfReader(sourceFile));

                // Extract and merge each page from the source page.
                for (var i = 0; i < pageRange.Length; i++)
                {
                    pdfMerger.Merge(pdfSource, pageRange[i], pageRange[i]);

                    OnUpdateProgress?.Invoke(i);
                }

                pdfDestination.Close();
                pdfMerger.Close();
                pdfSource.Close();

                // Step 5: Replace the original file with the temp one.
                File.Delete(destinationFile);
                File.Move(destinationFile + "temp", destinationFile);
            }
            catch (Exception e)
            {
                if (pdfDestination != null && !pdfDestination.IsClosed())
                {
                    pdfDestination.AddNewPage();
                    pdfDestination.Close();

                    pdfMerger?.Close();
                    pdfSource?.Close();
                }

                File.Delete(destinationFile + "temp");
                throw new Exception(e.Message);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Merge source files together and save them into destination file.
        /// </summary>
        /// <param name="sourceFiles">The list of source files</param>
        /// <param name="destinationFile">Destination file to save merged files into it</param>
        public void Merge(string[] sourceFiles, string destinationFile)
        {
            PdfDocument pdfDestination = null;
            PdfMerger   pdfMerger      = null;

            try
            {
                // Step 1: Temporary file to prevent rewrite on the original file.
                //         Destination file will be changed with the original in the last step.
                //         In case if the destination file in an existing file
                pdfDestination = new PdfDocument(new PdfWriter(destinationFile + "temp"));
                pdfMerger      = new PdfMerger(pdfDestination);

                for (var i = 0; i < sourceFiles.Length; i++)
                {
                    using (var pdfSource = new PdfDocument(new PdfReader(sourceFiles[i])))
                    {
                        pdfMerger.Merge(pdfSource, 1, pdfSource.GetNumberOfPages());

                        // Update merge job progress.
                        OnUpdateProgress?.Invoke(i);
                    }
                }

                pdfDestination.Close();
                pdfMerger.Close();

                // Step 2: Replace the destination file with the temp one.
                File.Delete(destinationFile);
                File.Move(destinationFile + "temp", destinationFile);
            }
            catch (Exception e)
            {
                if (pdfDestination != null && !pdfDestination.IsClosed())
                {
                    pdfDestination.AddNewPage();
                    pdfDestination.Close();
                    pdfMerger?.Close();
                }

                File.Delete(destinationFile + "temp");
                throw new Exception(e.Message);
            }
        }
Ejemplo n.º 4
0
        private void btnInvoice_Click(object sender, EventArgs e)
        {
            textBox4.Clear();
            if (textBox2.Text.Length < 1)
            {
                MessageBox.Show("ソースファイルを選択してください。");
                return;
            }
            else if (textBox3.Text.Length < 1)
            {
                MessageBox.Show("目標フォルダを選択してください。");
                return;
            }
            else
            {
                string   allLog = "";
                DateTime dt     = DateTime.Now;
                try
                {
                    string       sourceFileName = textBox2.Text.Split(',')[0];
                    string       TargetPath = textBox3.Text + @"\\";
                    SetRectangle JudgePDFType = new SetRectangle(100, 0, 50, 300, sourceFileName);
                    int          cx1 = 0, cy1 = 0, cx2 = 0, cy2 = 0, dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0;
                    if (JudgePDFType.GetPreName(1).Length >= 7)
                    {
                        if (Regex.IsMatch(JudgePDFType.GetPreName(1).Substring(7).Split(' ')[0], @"^[+-]?\d*[.]?\d*$"))
                        {
                            cx1 = 100; cy1 = 0; cx2 = 50; cy2 = 300;
                            dx1 = 50; dy1 = 350; dx2 = 10; dy2 = 20;
                        }
                        else
                        {
                            cx1 = 0; cy1 = 450; cx2 = 400; cy2 = 50;
                            dx1 = 330; dy1 = 540; dx2 = 150; dy2 = 15;
                        }
                    }
                    else
                    {
                        cx1 = 0; cy1 = 450; cx2 = 400; cy2 = 50;
                        dx1 = 330; dy1 = 540; dx2 = 150; dy2 = 15;
                    }

                    SetRectangle invoiceCustRec = new SetRectangle(cx1, cy1, cx2, cy2, sourceFileName);
                    SetRectangle invoiceDateRec = new SetRectangle(dx1, dy1, dx2, dy2, sourceFileName);

                    int times = 1;


                    for (int page = 1; page <= invoiceCustRec.pdfDoc.GetNumberOfPages();)
                    {
                        string strCustRec   = invoiceCustRec.GetPreName(page);
                        string customerCode = strCustRec.Substring(7).Split(' ')[0];
                        string customerName = strCustRec.Substring(strCustRec.IndexOf(' ', 9) + 1).Trim();
                        string date         = invoiceDateRec.GetPreName(page).Trim();

                        //名前設定
                        string targetFolderName = customerCode + "_" + customerName;
                        string fileName         = date + "_" + targetFolderName + ".pdf";

                        PdfReader pdfReader = new PdfReader(sourceFileName);


                        //--------------------------------
                        if (!Directory.Exists(TargetPath + targetFolderName))
                        {
                            Directory.CreateDirectory(TargetPath + targetFolderName);
                        }
                        string filePath = TargetPath + targetFolderName + "\\" + fileName;


                        PdfDocument sourceDocument = new PdfDocument(pdfReader);

                        PdfDocument targetDocument = new PdfDocument(new PdfWriter(filePath));
                        PdfMerger   merger         = new PdfMerger(targetDocument);



                        allLog += "PageNo: " + page + "\n";
                        allLog += fileName + "作成しました。\n";

                        textBox4.AppendText("PageNo: " + page + "\r\n");
                        textBox4.AppendText(fileName + "作成しました。\r\n");



                        do
                        {
                            Console.WriteLine(invoiceCustRec.GetPreName(page));

                            merger.Merge(sourceDocument, page, page);
                            page++;
                            if (page > invoiceCustRec.pdfDoc.GetNumberOfPages())
                            {
                                break;
                            }
                        }while (invoiceCustRec.GetPreName(page - 1) == invoiceCustRec.GetPreName(page));


                        times++;

                        sourceDocument.Close();
                        merger.Close();
                        targetDocument.Close();
                    }
                    allLog += "処理完成しました。" + (times - 1) + "個PDFを処理しました。";


                    MessageBox.Show("処理完成しました。" + (times - 1) + "個PDFを処理しました。");
                }
                catch (Exception ex)
                {
                    allLog += ex.Message + "\n";
                }
                finally
                {
                    File.AppendAllText(".\\LOG\\" + dt.ToString("yyyy-MM-dd H-mm-ss") + "log.txt", "\r\n" + allLog);
                }
                // string result = text.ToString();
            }
        }
Ejemplo n.º 5
0
        private async Task MergePDFs(MainViewModel viewModel)
        {
            viewModel.BuildStatus   = "Merging PDFs...";
            viewModel.BuildProgress = 0;

            bool overwriteFile = false;

            //Check if desired output file already exists
            if (File.Exists(Path.Combine(viewModel.WorkingDirectory, viewModel.OutputName + ".pdf")))
            {
                //ask user to overwrite file
                var result = MessageBox.Show("File exists, overwrite?", "Overwrite existing file", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.Cancel)
                {
                    return;
                }
                else
                {
                    overwriteFile = true;
                }
            }

            //Copy of real file list to manipulate
            List <FileObject> tempFileList = CopyFileObjectList(viewModel.Files);


            //create a temp directory to work in
            string outputPath = Path.Combine(viewModel.WorkingDirectory, "PDFTemp", viewModel.OutputName + ".pdf");

            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            //copy all files to work in a temp directory.
            CopyTempFiles(viewModel, tempFileList, outputPath);

            PdfDocument pdf    = null;
            PdfMerger   merger = null;
            PdfDocument doc    = null;

            try
            {
                //check user option for encryption
                if (viewModel.Encrypt)
                {
                    pdf = new PdfDocument(new PdfWriter(outputPath, new WriterProperties()
                                                        .SetStandardEncryption(
                                                            Encoding.ASCII.GetBytes(viewModel.PDFPass),
                                                            null,
                                                            EncryptionConstants.ALLOW_PRINTING,
                                                            EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA)
                                                        ));
                }
                else
                {
                    pdf = new PdfDocument(new PdfWriter(outputPath));
                }
                merger = new PdfMerger(pdf);

                foreach (var file in tempFileList)
                {
                    if (!File.Exists(file.FilePath))
                    {
                        viewModel.BuildStatus = $"Failed: Temporary file({file.FileName}) no longer exists.";
                        pdf.Close();
                        merger.Close();
                        File.Delete(outputPath);
                        return;
                    }
                    try
                    {
                        //check if file is protected
                        if (file.PasswordProtected)
                        {
                            var readerProps = new ReaderProperties();
                            readerProps.SetPassword(Encoding.ASCII.GetBytes(file.Password));
                            var pdfReader = new PdfReader(file.FilePath, readerProps);
                            pdfReader.SetUnethicalReading(true);
                            doc = new PdfDocument(pdfReader);
                        }
                        else
                        {
                            var pdfReader = new PdfReader(file.FilePath);
                            doc = new PdfDocument(pdfReader);
                        }
                    }
                    catch (iText.Kernel.PdfException e)
                    {
                    }
                    //merge document
                    var numPages = doc.GetNumberOfPages();
                    merger.Merge(doc, 1, numPages);

                    doc.Close();

                    //update build progress
                    viewModel.BuildProgress += numPages;
                }
                pdf.Close();

                //move to orig location
                File.Move(outputPath, Path.Combine(viewModel.WorkingDirectory, viewModel.OutputName + ".pdf"), overwriteFile);

                //delete temp files
                foreach (var file in tempFileList)
                {
                    File.Delete(file.FilePath);
                }

                //delete temp dir
                Directory.Delete(Path.GetDirectoryName(outputPath));

                viewModel.BuildStatus = "Success: PDF Successfully Created";
            }
            //CLEAN UP THIS EXCEPTION GARBAGE EVENTUALLY
            catch (iText.IO.IOException e)
            {
                viewModel.BuildStatus = "Failed: Corrupt PDF";
            }
            //catch(iText.Signatures.)
            catch (iText.Kernel.PdfException e)
            {
                viewModel.BuildStatus = "Failed: Corrupt PDF";
            }
            catch (FileNotFoundException e)
            {
                viewModel.BuildStatus = "Failed: A PDF in the list no longer exists";
            }
            catch (IOException e)
            {
                viewModel.BuildStatus = "Failed: Attempting to modify a file in use";
            }
        }