We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Saveformat changing type

Hi! I see that SaveFormat.Pdf is using Enums. Does anyone know if it’s possible to choose saveformat’s format with userinput ? I would like to make one methods that can encompass all types of input and output for the Document class.

PS: Could ofc use If tests, but just checking if there’s a better way.

@henrikJohansen93 Your question is not quite clear. But it seems you can use FileFormatUtil.ExtensionToSaveFormat method to get SaveFormat from the string file extension get from user input. Is this what you are looking for?

Example code:
Document doc = new Document(docStream);
       using (MemoryStream pdfStream = new MemoryStream())
                     {
                         
                         doc.Save(pdfStream, SaveFormat.Pdf);
     }

The doc.Save function uses an Enum to convert the pdfStream to a Pdf, which is fine if the Method only converts documents to pdf. But I’d like to convert any type to any type of document using the same code. To put it simply, I wonder if there is some way I could use a variable in doc.Save instead of an enum, so the savetype could get the type from parameter instead of being static to .pdf

@henrikJohansen93 You can use code like the following:

private static void Convert(Stream inputStream, Stream outputStream, string format)
{
    SaveFormat sf = FileFormatUtil.ExtensionToSaveFormat(format);
    if (sf == SaveFormat.Unknown)
        throw new ArgumentException("Specified save format is not supported.");

    Document doc = new Document(inputStream);
    doc.Save(outputStream, sf);
}

And call the method like this:

Convert(inputStream, outputStream, "pdf");
Convert(inputStream, outputStream, "xps");
Convert(inputStream, outputStream, "docx");

etc.

1 Like