Reputation: 698
I have two PDF files: Pdf A
and Pdf B
. Pdf A
already exists on the computer's C:
drive and Pdf B
gets generated through the program which also lands in the C:
drive.
What I want to do is combine the two so that the Pdf A
's pages show first and then Pdf B
's pages show after that.
Here is my code that tries to combine the two given a list of PDFs (Pdf A
is the first element and Pdf B
is the second element in the files
list, and the destinationfile
is Pdf A
):
public static void MergePdfFiles(string destinationfile, List<string> files)
{
Document document = null;
try
{
List<PdfReader> readers = new List<PdfReader>();
List<int> pages = new List<int>();
foreach (string file in files)
{
readers.Add(new PdfReader(file));
}
document = new Document(readers[0].GetPageSizeWithRotation(1));
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationfile, FileMode.Create));
document.Open();
foreach (PdfReader reader in readers)
{
pages.Add(reader.NumberOfPages);
WritePage(reader, document, writer);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
//being used by another process
document.Close();
}
}
The issue appears when the document object tries to close. It says it is being used another process.
What 'other' process is using it?
Upvotes: 1
Views: 1464
Reputation: 5449
try to change this line:
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationfile, FileMode.Create));
to this line :
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationfile, FileMode.Create,FileAccess.Write,FileShare.ReadWrite));
Upvotes: 3