I am merging a directory of pdf files into one file. The solution I have works 99.9% of the time except I have come across several pdf files that causes issues. The error is a System.NullReferenceException 'Object reference not set to an instance of an object.' Below is the code I am using to merge the pdfs.
public byte[] MergeDocs(string directory)
{
using var ms = new MemoryStream();
var doc = new Document(PageSize.A4);
var pdf = new PdfCopy(doc, ms);
doc.Open();
var files = Directory.GetFiles(directory);
foreach (var file in files)
{
var pdfReader = new PdfReader(file);
pdf.AddDocument(pdfReader);//this is where the error is thrown
pdfReader.Close();
pdfReader.Dispose();
}
doc.Close();
return ms.ToArray();
}
The file is not password protected. The file is able to be opened without issue. The issue is not with the naming scheme either. The way we get around this issue is copy the file to our local machine. Print that pdf to pdf again and then run the program with the newly printed pdf.
I have no idea where to begin to try and figure out what is the issue with the few pdf files that are causing this issue.