2
我們正在嘗試使用ITextSharp合併三個PDF。問題出在合併之後,我們只能從第一個PDF獲取數據,而其他兩個PDF不保留它們的值。pdf在ItextSharp中合併問題(合併後的PDF不保留其值)
所有這些PDF都具有相同的結構(即它們使用具有不同數據的相同模板),所以我的假設是它們具有相同的字段(AcroFields),可能會在合併時創建此問題。
以下是合併代碼:
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
}
}
這被稱爲如下:
string[] sourcenames = { @"D:\1.pdf", @"D:\2.pdf", @"D:\3.pdf" };
string destinationname = @"D:\pdf\mergeall\merge3.pdf";
MergeFiles(destinationname, sourcenames);
這解決了我的問題,合併太。不知道try/catch的意義。而變量f可以用作計數器而不是靜態變量(參數renameFields) – Daniel