The source files are required as single page pdf file.
Example :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
namespace sampleTest
{
public partial class WebForm9 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string[] sourceFiles = new string[100];
sourceFiles[0] = @"D:\SinglePage\1.pdf";
sourceFiles[1] = @"D:\SinglePage\2.pdf";
sourceFiles[2] = @"D:\SinglePage\3.pdf";
string DestinationFile=@"D:\Single.pdf";
MergeFiles(DestinationFile, sourceFiles, 3);
}
public static bool MergeFiles(string destinationFile, string[] sourceFiles, int count)
{
try
{
int f = 0;
// we create a reader for a certain document
PdfReader reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
int n = reader.NumberOfPages;
//System.Console.WriteLine("There are " + n + " pages in the original file.");
// step 1: creation of a document-object
Document document = new Document(reader.GetPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Append));
// step 3: we open the document
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
// step 4: we add content
while (f < /*sourceFiles.Length*/ count && sourceFiles[f] != null)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
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);
}
// System.Console.WriteLine("Processed page " + i);
}
f++;
if (f < count/*sourceFiles.Length*/)
{
if (sourceFiles[f] != null)
{
reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
n = reader.NumberOfPages;
// System.Console.WriteLine("There are " + n + " pages in the original file.");
}
else
break;
}
}
document.Close();
string[] files = Directory.GetFiles(destinationFile.Substring(0, destinationFile.LastIndexOf("\\")) + "\\SinglePage");
foreach (string file in files)
File.Delete(file);
return true;
}
catch (Exception e)
{
System.Console.Error.WriteLine(e.Message);
System.Console.Error.WriteLine(e.StackTrace);
return false;
}
}
}
}
No comments:
Post a Comment