My aim is to convert an Outlook msg email file with attachments to a single PDF document. I want to convert the attachments to PDF and append them to the PDF version of the email.
I do NOT want to write to the file system - in memory only.
I get a 0kb corrupted file as the result. Aspose throws exception: [Aspose.Pdf.Exceptions.InvalidPdfFileFormatException] = {“Incorect file format”}
In my test case, the attachments convert individually just fine - so that is not the problem.
The email by itself also converts just fine - so that is also no the problem.
Here is my code setting the licence. I set the licence in a static method in a referenced assembly.
public void SaveAsPdf(Stream targetStream)
{
//Email proper
var streamForEmail = new MemoryStream();
_mailMessage.Save(streamForEmail,MailMessageSaveType.MHtmlFromat);
streamForEmail.Position = 0;
var options = new Aspose.Words.LoadOptions() {LoadFormat = LoadFormat.Mhtml};
var doc = new Aspose.Words.Document(streamForEmail, options);
var streamForConvertedEmail = new MemoryStream();
doc.Save(streamForConvertedEmail, SaveFormat.Pdf);
streamForConvertedEmail.Position = 0;
Queue streamsToConcatenate = new Queue();
streamsToConcatenate.Enqueue(streamForConvertedEmail);
//attachments
foreach (var attachment in _attachments)
{
using (var attachmentstream = new MemoryStream())
{
attachment.SaveAsPdf(attachmentstream);
streamsToConcatenate.Enqueue(attachmentstream);
attachmentstream.Position = 0;
}
}
// Now the concatenation
var pdfFileEditor = new Aspose.Pdf.Facades.PdfFileEditor();
bool concatenatedSuccessfullyWithSideEffect = true;
var buffer = new MemoryStream();
try
{
concatenatedSuccessfullyWithSideEffect = pdfFileEditor.Concatenate(streamsToConcatenate.ToArray(),
buffer);
var completeDoc = new Aspose.Pdf.Document(buffer);
completeDoc.Save(targetStream);
}
catch (Exception e)
{
if (!concatenatedSuccessfullyWithSideEffect)
{
throw new FailedToCreateEmailAndAttachmentsCombinedPdfException(
String.Format("’{0}’ with attachments: {1}", _subject,
String.Join(",", _attachments.Select(a => a.ShortFileName))), e);
}
throw e;
}
}