Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge PDF files

Tags:

pdf

itext

Is it possible to merge a fillable pdf file with a regular pdf file in asp.net C# using itextsharp. Any help would be greatly appreciated.

like image 430
jkjljlkjl Avatar asked Dec 27 '22 19:12

jkjljlkjl


1 Answers

Took me a long time to figure this out but here is a working example:

public static void MergeFiles(string destinationFile, string[] sourceFiles)
    {
        try 
        {
            int f = 0;
            String outFile = destinationFile;
            Document document = null;
            PdfCopy  writer = null;
            while (f < sourceFiles.Length) {
                // Create a reader for a certain document
                PdfReader reader = new PdfReader(sourceFiles[f]);

                // Retrieve the total number of pages
                int n = reader.NumberOfPages;
                //Trace.WriteLine("There are " + n + " pages in " + sourceFiles[f]);
                if (f == 0) 
                {
                    // Step 1: Creation of a document-object
                    document = new Document(reader.GetPageSizeWithRotation(1));
                    // Step 2: Create a writer that listens to the document
                    writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
                    // Step 3: Open the document
                    document.Open();
                }
                // Step 4: Add content
                PdfImportedPage page;
                for (int i = 0; i < n; ) 
                {
                    ++i;
                    page = writer.GetImportedPage(reader, i);
                    writer.AddPage(page);
                }
                PRAcroForm form = reader.AcroForm;
                if (form != null)
                    writer.CopyAcroForm(reader);
                f++;
            }
            // Step 5: Close the document
            document.Close();
        }
        catch(Exception) 
        {
            //handle exception
        }
    }

Hope this helps!

Source: http://www.ujihara.jp/iTextdotNET/examples/concat_pdf.java

like image 71
Robert Avatar answered Dec 30 '22 12:12

Robert