locked
Merging two pdf pages into one using itextsharp RRS feed

  • Question

  • User-1346512353 posted

    Hi, I have two pdf files of widht 8 inch & height 5 inch in landscape mode.

    I am familier with merging pages using itextsharp but my method merges these two pdf into a single pdf with two pages.

    What I want to do is merge these two pages into a single page in resultant pdf.

    Here is my code which merges pdfs into two pages.

    public bool MergeFiles(string destinationFile, string[] sourceFiles)
            {
                bool bSucess = true;
    
                if (System.IO.File.Exists(destinationFile))
                    System.IO.File.Delete(destinationFile);
    
                string[] sSrcFile;
                sSrcFile = new string[2];
    
    
                string[] arr = new string[2];
                for (int i = 0; i <= sourceFiles.Length - 1; i++)
                {
                    if (sourceFiles[i] != null)
                    {
                        if (sourceFiles[i].Trim() != "")
                            arr[i] = sourceFiles[i].ToString();
                    }
                }
    
                if (arr != null)
                {
    
                    sSrcFile = new string[2];
    
                    for (int ic = 0; ic <= arr.Length - 1; ic++)
                    {
                        sSrcFile[ic] = arr[ic].ToString();
                    }
                }
    
                string sPDFPath = Server.MapPath(@"pdftemp/");
                Scripting.FileSystemObject fso = new Scripting.FileSystemObjectClass();
    
              
                try
                {
                    int f = 0;
    
                    PdfReader reader = new PdfReader(sSrcFile[f]);
                    int n = reader.NumberOfPages;
                    Console.WriteLine("There are " + n + " pages in the original file.");
                    Document document = new Document(PageSize.A4);
    
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
                    PdfDate st = new PdfDate(DateTime.Today);
    
    
                    document.Open();
                    PdfContentByte cb = writer.DirectContent;
                    PdfImportedPage page;
    
                    int rotation;
                    while (f < sSrcFile.Length)
                    {
                        int i = 0;
                        while (i < n)
                        {
                            i++;
    
                            document.SetPageSize(PageSize.A4);
                            document.NewPage();
                            page = writer.GetImportedPage(reader, i);
    
                            rotation = reader.GetPageRotation(i);
                            if (rotation == 90 || rotation == 270)
                            {
                                cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                            }
                            else
                            {
                                cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                            }
                            Console.WriteLine("Processed page " + i);
                        }
    
                        f++;
                        if (f < sSrcFile.Length)
                        {
                            reader = new PdfReader(sSrcFile[f]);
                            n = reader.NumberOfPages;
                            Console.WriteLine("There are " + n + " pages in the original file.");
                        }
                    }
                    
                    document.Close();
    
                }
                catch (Exception e)
                {
                    bSucess = false;
                }
    
                return bSucess;
            }
    Tuesday, June 21, 2011 2:07 AM

Answers

  • User1640016736 posted

    PdfReader reader = new PdfReader(@"f:\temp\prueba.pdf");

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

    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"f:\temp\libreta.pdf", FileMode.Create));

    document.Open();

    PdfImportedPage page;

    PdfPTable table = new PdfPTable(2);

    table.WidthPercentage = 100;

    for (inti = 1; i <= reader.NumberOfPages; i++)

    {

    page = writer.GetImportedPage(reader, i);

    table.AddCell(iTextSharp.text.

    Image.GetInstance(page));

    document.Add(table);

    }

    document.Close();

    MessageBox.Show("Se grabo con exito");

     

    Envio un codigo espero que te ayude.

    En este ejemplo mi archivo pdf tienes 2 paginas y creo uno nuevo de una sola pagina.

    Saludos

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 24, 2011 7:27 PM

All replies

  • User-269404413 posted

    siteslayer,

    you didnt specified what was your problem.

    here is the complete source code

    Merge PDF files with iText# and .NET

    I’ve made a simple class to merge PDF files using iText#:

    csharp:
    using System;
    using System.Collections.Generic;
    using System.IO;
    using iTextSharp.text;
    using iTextSharp.text.pdf;

    public class PdfMerge
    {
        private BaseFont baseFont;
        private bool enablePagination = false;
        private readonly List<PdfReader> documents;
        private int totalPages;

        public BaseFont BaseFont
        {
            get { return baseFont; }
            set { baseFont = value; }
        }

        public bool EnablePagination
        {
            get { return enablePagination; }
            set
            {
                enablePagination = value;
                if (value && baseFont == null)
                    baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            }
        }

        public List<PdfReader> Documents
        {
            get { return documents; }
        }

        public void AddDocument(string filename)
        {
            documents.Add(new PdfReader(filename));
        }
        public void AddDocument(Stream pdfStream)
        {
            documents.Add(new PdfReader(pdfStream));
        }
        public void AddDocument(byte[] pdfContents)
        {
            documents.Add(new PdfReader(pdfContents));
        }
        public void AddDocument(PdfReader pdfDocument)
        {
            documents.Add(pdfDocument);
        }

        public void Merge(string outputFilename)
        {
            Merge(new FileStream(outputFilename, FileMode.Create));
        }
        public void Merge(Stream outputStream)
        {
            if (outputStream == null || !outputStream.CanWrite)
                throw new Exception("OutputStream es nulo o no se puede escribir en éste.");

            Document newDocument = null;
            try
            {
                newDocument = new Document();
                PdfWriter pdfWriter = PdfWriter.GetInstance(newDocument, outputStream);

                newDocument.Open();
                PdfContentByte pdfContentByte = pdfWriter.DirectContent;

                if (EnablePagination)
                    documents.ForEach(delegate(PdfReader doc)
                                      {
                                          totalPages += doc.NumberOfPages;
                                      });

                int currentPage = 1;
                foreach (PdfReader pdfReader in documents)
                {
                    for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                    {
                        newDocument.NewPage();
                        PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader, page);
                        pdfContentByte.AddTemplate(importedPage, 0, 0);

                        if (EnablePagination)
                        {
                            pdfContentByte.BeginText();
                            pdfContentByte.SetFontAndSize(baseFont, 9);
                            pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER,
                                string.Format("{0} de {1}", currentPage++, totalPages), 520, 5, 0);
                            pdfContentByte.EndText();
                        }
                    }
                }
            }
            finally
            {
                outputStream.Flush();
                if (newDocument != null)
                    newDocument.Close();
                outputStream.Close();
            }
        }

        public PdfMerge()
        {
            documents = new List<PdfReader>();
        }
    }

    Usage:

    csharp:
    string basePath = "c:\\pdf";

    PdfMerge demo = new PdfMerge();

    demo.AddDocument(Path.Combine(basePath, "static-dynamic-typing-meijer.pdf"));
    demo.AddDocument(Path.Combine(basePath, "composable-memory-transactions.pdf"));

    demo.Merge("mergedPapers.pdf");

    Console.WriteLine("Archivo generado en: {0}", Path.GetFullPath("mergedPapers.pdf"));
     
    and refer this page
    Tuesday, June 21, 2011 3:14 AM
  • User-1346512353 posted

    Thanks for you example Jayaseelan but this line of code

    newDocument.NewPage();



    will create a new page in PDF document which I do not want.
    What I want to do is take two pdf documents & merge them into a single page pdf document.
    Also is there a way in itextsharp to make the merging samarter? Suppose if bothe the pdfs which are to be merged can be contained in one page
    then then the code should generate only a single page pdf otherwise if say for example the height of 1st pdf page occupies 3/4th of pdf page then
    code should decide weather page 2 can be adjusted in remaining 1/4th of the new page otherwise it should create a new page for second page in merger pdf.

    Thanks & Regards
    Roy

    Tuesday, June 21, 2011 10:29 AM
  • User1640016736 posted

    PdfReader reader = new PdfReader(@"f:\temp\prueba.pdf");

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

    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"f:\temp\libreta.pdf", FileMode.Create));

    document.Open();

    PdfImportedPage page;

    PdfPTable table = new PdfPTable(2);

    table.WidthPercentage = 100;

    for (inti = 1; i <= reader.NumberOfPages; i++)

    {

    page = writer.GetImportedPage(reader, i);

    table.AddCell(iTextSharp.text.

    Image.GetInstance(page));

    document.Add(table);

    }

    document.Close();

    MessageBox.Show("Se grabo con exito");

     

    Envio un codigo espero que te ayude.

    En este ejemplo mi archivo pdf tienes 2 paginas y creo uno nuevo de una sola pagina.

    Saludos

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 24, 2011 7:27 PM
  • User1670492946 posted

    I'm having an issue where the first two pages of the imported pdf keep repeating.  Know of a fix?

    Thursday, July 26, 2012 3:27 PM
  • User-726393421 posted

    Hi Jeyaseelan,

    Thanks for the code,

    I have a quesion here like

    when we give print to pdf on any document one of the page is getting missed and error triggers like below

    "An error exist on this page.Acrobat may not display the page correctly .please contact the person who created the pdf document to correct the problem".

    when we upload we do have all the page displayed after uploading we are getting above error and also for some of the documents it is upside down

    could you please let me know how to solve this 2 issues

    Wednesday, July 3, 2013 8:06 AM