Using WordProcessor and DocIO library to convert file to pdf document.

I am trying to use the Blazor word processor control and DocIO library to convert docx file into pdf document.I am however getting a "Zip exception.Can't locate end of central directory record. Possible wrong file format or archive is corrupt" on the line I highlighted line below. What could I be doing wrong? 

ViewFile.razor:
protected async Task DownloadClick()
    {
      this.PrimaryButtonDisabled = true;
      try
      {
        var documentEditor = sfDocumentEditorContainer.DocumentEditor;
          var wordasblob=await documentEditor.SaveAsBlob(FormatType.Docx);
          await using var memoryStream = await WordToPDFService.WordToPDF(wordasblob);
          await JSRuntime.SaveAs("abc.pdf",memoryStream.ToArray());
      }
      catch (Exception exception)
      {
        this.logger.LogError($"{exception}");
      }
    }

WordToPDFService.cs:
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using System.IO;
using Syncfusion.DocIORenderer;
using System.Threading.Tasks;

namespace Services
{
  public class WordToPDFService
  {
    public static async Task<MemoryStream> WordToPDF(string wordasblob)
    {
      #region convert string to stream
      using var memoryStream1 = new MemoryStream();
      using var streamWriter = new StreamWriter(memoryStream1);
      await streamWriter.WriteAsync(wordasblob);
      await streamWriter.FlushAsync();
      memoryStream1.Position = 0;
      #endregion

      using var wordDocument = new WordDocument(memoryStream1, FormatType.Docx);
      using var docIORenderer = new DocIORenderer();
      docIORenderer.Settings.AutoTag = true;
      docIORenderer.Settings.PreserveFormFields = true;
      docIORenderer.Settings.ExportBookmarks = ExportBookmarkType.Headings;
      using var pdfDocument = docIORenderer.ConvertToPDF(wordDocument);
      using var memoryStream = new MemoryStream();
      pdfDocument.Save(memoryStream);
      memoryStream.Position = 0;
      return memoryStream;
    }
  }
}

5 Replies 1 reply marked as answer

SM Suriya Murugan Syncfusion Team May 10, 2021 11:37 AM UTC

Hi ajit, 

Currently, we are validating the reported scenario and will update further details by May 11,2021. 

Meantime, can you please confirm are you facing issue for all the document? if specific document, please share that document to check it in our side. 

Regards, 
Suriya M. 



AG ajit goel May 10, 2021 06:07 PM UTC

I have not checked other documents, I tested with a document with the following russian text and highlighted some characters in the text, using word processor control. 

Да. А вот раз людям Здравствуйте. А вы знаете, какой то степени это касается И меня зовут Екатерина. Сказать не могу говорить с родителями. Алексей Лианы? Да, это я. Добрый день. Еще раз скажите, пожалуйста, я вижу вас, назначенная пунктом для Анна и для Алексея пятого декабря. Да, да. Подскажите, пожалуйста, и причину визита Анны и пятого декабря. Если честно, просто я двое детей думаю, что это может быть, его увидят и для него тоже. Да, смотрите, она увидит. Просто она была в августе. У неё был А ежегодный визита осмотр. Поэтому мы Я говорю тогда, когда точно, Если что то если что то произошло Или может быть, это какие то сегодня она еще Спасибо большое. Тогда мы Оно не нужно визита. Тогда знаменитая. Ну да. Надо отменить, потому что я думаю, что в области это было ему неизвестно. Видит. Нам просто нужно были при явке в школы и все. А это сделать, как вас осматривал доктор. Всё, я понял. Спасибо большое. Тогда давайте только Алексей Постоянный. Да, только Алексей. Пятого декабря Мы живем по Сейчас я еще раз восемь пятьдесят. Супер. Спасибо Большое. Заблуждение, что все хорошо. Здание


SM Suriya Murugan Syncfusion Team May 11, 2021 05:04 AM UTC

Hi Ajit, 

Thanks for your update. 

Issue because of conversion of string to stream. Can you please use below highlighted code snippet to convert base64 string to stream and then convert based on your requirement? 

public static async Task<MemoryStream> WordToPDF(string wordasblob) 
        { 
            //#region convert string to stream 
            //using var memoryStream1 = new MemoryStream(); 
            //using var streamWriter = new StreamWriter(memoryStream1); 
            //await streamWriter.WriteAsync(wordasblob); 
            //await streamWriter.FlushAsync(); 
            //memoryStream1.Position = 0; 
            //#endregion 
            byte[] data = System.Convert.FromBase64String(wordasblob); 
            //To observe the memory go down, null out the reference of base64Data variable. 
            wordasblob = null; 
            //Word document file stream 
            Stream stream = new MemoryStream(data); 
 
            using var wordDocument = new WordDocument(stream, FormatType.Docx); 
            using var docIORenderer = new DocIORenderer(); 
            docIORenderer.Settings.AutoTag = true; 
            docIORenderer.Settings.PreserveFormFields = true; 
            docIORenderer.Settings.ExportBookmarks = ExportBookmarkType.Headings; 
            using var pdfDocument = docIORenderer.ConvertToPDF(wordDocument); 


Please try this and let us know if you still facing issue. 

Regards, 
Suriya M. 


Marked as answer

AG ajit goel May 11, 2021 06:15 AM UTC

Hello Suriya, you guys are awesome. Please close this ticket. 


SM Suriya Murugan Syncfusion Team May 11, 2021 07:28 AM UTC

Hi ajit, 

Thanks for your update. 

Regards, 
Suriya M. 


Loader.
Up arrow icon