3

In my ASP.NET application (.NET Framework 4.7) I'm using OpenHtmlToPdf for creating PDF based on the pages in the website.

It is working locally but not in the server production: I have the following error:

Exception type: System.ComponentModel.Win32Exception Exception message: Access is denied

Stack trace: at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) at System.Diagnostics.Process.Start() at System.Diagnostics.Process.Start(ProcessStartInfo startInfo) at OpenHtmlToPdf.HtmlToPdfConverterProcess.Convert(ConversionSource conversionSource) at OpenHtmlToPdf.Pdf.DocumentBuilder.ReadContentUsingTemporaryFile(String temporaryFilename)

I think the problem is related to wkhtmltopdf because OpenHtmlToPdf is using this library to generate the PDF. The code is pretty simple.

    var pdf = Pdf.From(html)
                 .WithGlobalSetting("orientation", "Landscape")
                 .WithObjectSetting("web.defaultEncoding", "utf-8")
                 .Content();

    return File(pdf, System.Net.Mime.MediaTypeNames.Application.Octet, "Reference.pdf");

Then, how can I generate the PDF?

Omid Nazifi
  • 5,235
  • 8
  • 30
  • 56
Enrico
  • 3,592
  • 6
  • 45
  • 102

1 Answers1

1

OpenHTMLToPDF use Path.GetTempPath() and Guid.NewGuid() to create a temp file. Make sure your running process has sufficient privelegdes to write to the path returned by Path.GetTempPath();

For reference here is the source code responsible for creating the temp file name, and writing it.

//inside TemporaryPdf class
public static string TemporaryFilePath() 
{
  return Path.Combine(Path.GetTempPath(), "OpenHtmlToPdf", TemporaryPdf.TemporaryFilename());
}

private static string TemporaryFilename()
{
  return Guid.NewGuid().ToString("N") + ".pdf";
}

And then it is used when calling Content

  // inside the Pdf class
  public byte[] Content()
  {
    return this.ReadContentUsingTemporaryFile(TemporaryPdf.TemporaryFilePath());
  }

  private byte[] ReadContentUsingTemporaryFile(string temporaryFilename)
  {
    this._globalSettings["out"] = temporaryFilename;
    HtmlToPdfConverterProcess.ConvertToPdf(this._html, this._globalSettings, this._objectSettings);
    byte[] numArray = TemporaryPdf.ReadTemporaryFileContent(temporaryFilename);
    TemporaryPdf.DeleteTemporaryFile(temporaryFilename);
    return numArray;
  }

The rest of the code can be found on GitHub here: OpenHTMLToPDF

Espen
  • 2,456
  • 1
  • 16
  • 25