2

I am converting a .txt file to a pdf and need to display the pdf to the user. For that, I have created a temporary .pdf file and created a process to open the file. This works fine when there is adobe acrobat installed. This fails when there is no default application. For my case, the pdf is opened in internet explorer and I get No process is associated with this object exception. Is there any other way to find out when the file is being closed so that I can delete it later on.

My code is like this.

                HtmlToPdf htmlToPdf = new HtmlToPdf(pdfPrintOptions);

                string tmpFileName = "zx" + DateTime.Now.Ticks + "x.pdf";

                //Iron pdf does not handle in-memory pdf viewing
                //convert it to pdf
                htmlToPdf.RenderHTMLFileAsPdf(fileWithPath).SaveAs(tmpFileName);

                // TempFileCollection tmpFileCollection = new TempFileCollection();
                //Use windows process to open the file
                Process pdfViewerProcess = new Process
                {
                    EnableRaisingEvents = true, StartInfo = {FileName = tmpFileName}
                };
                pdfViewerProcess.Start();

                pdfViewerProcess.WaitForExit(); **Failing in this line**
                //Delete temporary file after the viewing windows is closed
                if (File.Exists(tmpFileName))
                {
                    File.Delete(tmpFileName);
                }

Similar questions do not seem to provide a workaround for this problem. Any help will be appreciated. Thanks.

Jivan Bhandari
  • 860
  • 1
  • 10
  • 32

2 Answers2

1

You have to define tmpFileName in global variable and use Event Exited like this:

try{
 Process myProcess = new Process();
 myProcess.StartInfo.FileName = tmpFileName;
 myProcess.EnableRaisingEvents = true;
 myProcess.Exited += new EventHandler(myProcess_Exited);
 myProcess.Start();
}
catch (Exception ex){
 //Handle ERROR
 return;
}


// Method Handle Exited event. 
private void myProcess_Exited(object sender, System.EventArgs e){
 if (File.Exists(tmpFileName))
    {
       File.Delete(tmpFileName);
    }
}

Hope it can help you

Update my answers: If it still not working. Try this answers

mikenlanggio
  • 1,122
  • 1
  • 7
  • 27
-1

I would just save the PDF file in the TEMP folder.

Either in Windows User TEMP folder or your App can create a TEMP folder. If you create a TEMP folder just delete every file when your app closed.

string filePath = Path.GetTempPath() + "yourfile.pdf"; 

//Writer your file to Path
//File.WriteAllBytes(filePath, content);

Process.Start(filePath);
Gubi
  • 415
  • 2
  • 10
  • 20