How can I convert files in memory?

Q: How can I convert files in memory?

A: You can use the StreamingPDFConversion class to convert the file in memory. Here is a C# example using the memoryStream API.

public static void ConvertToPDF(MemoryStream file, string extension)
{
    using (var memoryFilter = new pdftron.Filters.MemoryFilter((int)file.Length, false))
    {
        var writer = new pdftron.Filters.FilterWriter(memoryFilter);
        writer.WriteBuffer(file.ToArray()); writer.Flush();
        memoryFilter.SetAsInputFilter();
        var options = new ConversionOptions(); options.SetFileExtension(extension);
        var documentConversion = pdftron.PDF.Convert.StreamingPDFConversion(memoryFilter, options);
        while (documentConversion.GetConversionStatus() == DocumentConversionResult.e_document_conversion_incomplete)
        {
            documentConversion.ConvertNextPage();
        }
        if (documentConversion.GetConversionStatus() == DocumentConversionResult.e_document_conversion_success)
        {
            var pdfFile = documentConversion.GetDoc().Save(SDFDoc.SaveOptions.e_linearized);
        }
        else
        {
            Console.WriteLine("Conversion failed");
        }
                
    }
}

Hi,

can we show a sample of how to use this with RecyclableMemoryStream? RecyclableMemoryStream.ToArray method has been deprecated but switching to the recommended RecyclableMemoryStream.GetBuffer sometimes fails conversions (looks like this happens when the word document has comments in it.

Error thrown:
"LogLevel": "Error", "Message": "Exception: \n\t Message: document layout failed: Unable to convert this document from binary to OOXML form. File is not a valid zip archive.\n\t Conditional expression: \n\t Version : 11.5.0-49a59f2782\n\t Platform : .Net Framework\n\t Architecture : AMD64\n\t Filename : FlowToPDFConversion.cpp\n\t Function : PDF::DocxConversion::Convert()\n\t Linenumber : 201\n (Error Id: b7f354b2-8f8a-4767-acf4-95860639f658) \npdftron.Common.PDFNetException: Exception: \n\t Message: document layout failed: Unable to convert this document from binary to OOXML form. File is not a valid zip archive.\n\t Conditional expression: \n\t Version : 11.5.0-49a59f2782\n\t Platform : .Net Framework\n\t Architecture : AMD64\n\t Filename : FlowToPDFConversion.cpp\n\t Function : PDF::DocxConversion::Convert()\n\t Linenumber : 201\n\n at pdftron.Common.PDFNetException.REX(IntPtr result)\n at pdftron.PDF.Convert.OfficeToPDF(PDFDoc inDoc, Filter inData, ConversionOptions options)\n...

1 Like