iText7 Filestream Null Reference Error in C#

Viewed 47

I'm attempting to convert a html file to a pdf file. This is my code:

using iText.Html2pdf
.
.
.
public bool HtmlToPDF(string folderName, string htmlFilePath, string otherNum)
        {
            Console.WriteLine("Running HtmltoPDF\n");

            string outputPath = new Uri(folderName + "\\" + otherNum.pdf).LocalPath;

            try
            {
                FileStream htmlSource = File.Open(htmlFilePath, FileMode.Open);
                FileStream pdfDest = File.Open(outputPath, FileMode.Create);

                ConverterProperties converterProperties = new ConverterProperties();
                HtmlConverter.ConvertToPdf(htmlSource, pdfDest, converterProperties);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }

            Console.WriteLine("Successfully completed HtmltoPDF and returned true\n");
            return true;
        }

Running the code "HtmlConverter.ConvertToPdf(htmlSource, pdfDest, converterProperties);" causes the following error to be thrown:

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=itext.io
  StackTrace:
   at iText.IO.Font.FontCache..cctor()

I'm really at a loss as this seems to be a simple operation. Any help would be greatly appreciated.

1 Answers

You need a using statement in your FileStream objects. If you don't use using, they're not disposed.

using FileStream htmlSource = File.Open(htmlFilePath, FileMode.Open);
using FileStream pdfDest = File.Open(outputPath, FileMode.Create);

After C# 8.0 using statements can be single line.

Related