0

Hi I am trying to generate a PDF from my cshtml teplate files. For this I am using FreeSpire.PDF.

When I creata an instance of the PdfDocument from the stream I got the following error: Spire.Pdf.Exceptions.PdfDocumentException: 'Invalid/Unknown/Unsupported format'

Here is my code.

private async Task<IDocumentData> ConvertToPdf<TViewModel>(string templateFileName, TViewModel viewModel)
{

try
{
    var rootDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    var templateFullPath = Path.Combine(rootDir, "Infrastructure", "DocumentumGenerator");

        var engine = new RazorLightEngineBuilder().UseFileSystemProject(templateFullPath)
                                                  .UseMemoryCachingProvider()
                                                  .Build();

        var viewPath = Path.Combine("Templates", templateFileName);
        var htmlContent = await engine.CompileRenderAsync(viewPath, viewModel);

        var setting = new PdfPageSettings
        {
            Orientation = PdfPageOrientation.Portrait,
            Size = PdfPageSize.A4,
            Margins = new PdfMargins(20)
        };

        var htmlData = Encoding.UTF8.GetBytes(htmlContent);
        using var stream = new MemoryStream(htmlData);

        var document = new PdfDocument(stream);

        var outputStream = new MemoryStream();
        document.SaveToStream(stream);

        return new DocumentData
        {
            Data = outputStream.ToArray(),
            ContentType = "application/pdf"
        };
    }
    catch(Exception ex)
    { 
        throw new Exception(ex.Message); 
    }
}

For converting cshtml to html I am using the RazorLight library. In the debug mode I can se that the html is generatoed properly in the htmlContent variable.

thnx

Wasyster
  • 2,279
  • 4
  • 26
  • 58

0 Answers0