0

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.

smuldr
  • 297
  • 1
  • 12
  • the pdf.AddDocument(pdfReader) line inside the foreach. I put a comment in the code provided where the exception occurs. – smuldr Oct 20 '21 at 14:34
  • The file is probably corrupt and the reader can't read it – GH DevOps Oct 20 '21 at 14:35
  • Maybe this helps: https://stackoverflow.com/questions/14442158/itextsharp-pdfcopy-throwing-null-reference-exception – Manu Oct 20 '21 at 14:36
  • I am able to open it in a browser and Adobe Acrobat no issue. – smuldr Oct 20 '21 at 14:36
  • 1
    *"I am able to open it in a browser and Adobe Acrobat no issue."* - That doesn't mean anything, PDF viewers often are trimmed to show something even for severely damaged PDFs. PDF libraries are not (at least not to the same degree). Thus, please share the PDF in question for analysis. – mkl Oct 20 '21 at 14:42
  • Unfortunately the document contains sensitive data so I am unable to share the file itself. – smuldr Oct 20 '21 at 14:47

0 Answers0