We are trying to merge three PDFs using ITextSharp. The problem is after merging we are able to get Data from the first PDF only, while the other two PDFs don't retain their values.
All these PDFs have the same structure (ie they use the same templates with different data), so my assumption is they are having same fields (AcroFields) which may be creating this problem while merging.
Here is the merge code :
public 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;
if (writer != null)
{
page = writer.GetImportedPage(reader, i);
writer.AddPage(page);
}
}
PRAcroForm form = reader.AcroForm;
if (form != null)
{
if (writer != null)
{
writer.CopyAcroForm(reader);
}
}
f++;
}
// Step 5: Close the document
if (document != null)
{
document.Close();
}
}
catch (Exception)
{
//handle exception
}
}
This is called as follows :
string[] sourcenames = { @"D:\1.pdf", @"D:\2.pdf", @"D:\3.pdf" };
string destinationname = @"D:\pdf\mergeall\merge3.pdf";
MergeFiles(destinationname, sourcenames);
I figured it out myself after little searching...Following is the solution...
I have created the function to rename the Fields in the PDF,so that after merging the fields will be renamed.
private static int counter = 0;
private void renameFields(PdfReader pdfReader)
{
try
{
string prepend = String.Format("_{0}", counter++);
foreach (DictionaryEntry de in pdfReader.AcroFields.Fields)
{
pdfReader.AcroFields.RenameField(de.Key.ToString(), prepend + de.Key.ToString());
}
}
catch (Exception ex)
{
throw ex;
}
}
This function is called in "MergeFiles" function as follow...
// Create a reader for a certain document
PdfReader reader = new PdfReader(sourceFiles[f]);
renameFields(reader);
// Retrieve the total number of pages
int n = reader.NumberOfPages;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.