Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

On desktop Word file is corrupted, but I can open it online or with Libre Office or WPS... #1851

Open
Kezzya opened this issue Dec 20, 2024 · 1 comment

Comments

@Kezzya
Copy link

Kezzya commented Dec 20, 2024

Describe the bug
Hello, I create generation of word file from dotx template. But in desktop Word Office app I can't open file, but with another ways, I can open (WPS, Libre Office, Google Docs, Online Office)
What the problem? Is this because I clone dotx file and generate docx?

public ActionResult GenerateDocument(int reportViewId, int rid)
{

    string templatePath = Server.MapPath("~/Content/templates/word/Template.dotx");
    if (RepView.WordTemplateFileName != null)
    {
        templatePath = Server.MapPath("\\UserFiles\\ReportViewWordTemplates\\" + RepView.WordTemplateFileId);
    }
    string outputPath = Server.MapPath("~/generated.docx");

    using (MemoryStream memoryStream = new MemoryStream())
    {
        try
        {
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(templatePath, false))
            {
                wordDoc.Clone(memoryStream);
            }

        }
        catch
        {
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(templatePath, false))
            {
                wordDoc.Clone(memoryStream);
            }
        }

        using (WordprocessingDocument generatedDoc = WordprocessingDocument.Open(memoryStream, true))
        {
            memoryStream.Position = 0;
            var mainDocumentPart = generatedDoc.MainDocumentPart;

            var body = mainDocumentPart.Document.Body;

            var headerParts = generatedDoc.MainDocumentPart.HeaderParts;
            var footerParts = generatedDoc.MainDocumentPart.FooterParts;

            foreach (var parts in headerParts)
            {
                foreach (var currentText in parts.RootElement.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>())
                {
                    currentText.Text = currentText.Text.Replace("Header", header);
                }
            }
            foreach (var parts in footerParts)
            {
                foreach (var currentText in parts.RootElement.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>())
                {
                    currentText.Text = currentText.Text.Replace("Bottom", bottom);
                }
            }

            ImagePart imgp = mainDocumentPart.AddImagePart(ImagePartType.Png);
            var textElements = body.Descendants<Text>()
          .Where(t => t.Text.Contains("text"))
          .FirstOrDefault();
   
            var run = new Run(new Text());
            if (textElements != null)
            {
                run = textElements.Parent as Run;
            }
           
            foreach (var item in headers)
            {
                if (blocks.Where(p => p.DocumentConstructorHeaderId == item.DocumentConstructorHeaderId).Count() != 0)
                {
                    
                    if (item.SizeTitle > 1)
                    {
                        AddHeading(body, item.Title, 1, mainDocumentPart.StyleDefinitionsPart);
                    }
                    else
                    {
                        AddHeading(body, item.Title, 2, mainDocumentPart.StyleDefinitionsPart);
                    }
                }

                foreach (var list in newBlocks.Where(p => p.DocumentConstructorHeaderId == item.DocumentConstructorHeaderId).OrderBy(p => p.Npp).ToList())
                {
                    if (list.ImageData != null)
                    {
                        using (var imageStream = new MemoryStream(list.ImageData))
                        {
                            imgp.FeedData(imageStream);
                        }

                        AddImageToBody(mainDocumentPart, list.ImageData);
                    }
                    /*if (list.Content != null)
                    {
                        AddHeading(body, item.Title, 1, mainDocumentPart.StyleDefinitionsPart);
                    }*/

                    Paragraph para = body.AppendChild(new Paragraph());

                    if (textElements != null)
                    {
                        // Извлекаем свойства Run
                        var runProperties = run.RunProperties?.CloneNode(true);
                        var newRun = new Run(new Text(list.Content));
                        newRun.PrependChild(runProperties);
                        para.AppendChild(newRun);
                    }
                    else
                    {
                        para.AppendChild(new Run(new Text(list.Content)));
                    }
                    ReplaceText(body, "text", "");
                }
            }
            generatedDoc.Close();
        }
        return File(memoryStream.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "generated.docx");
    }
}
@twsouthwick
Copy link
Member

A couple things for you to try:

  • Does the dotx have the same issue?
  • The try/catch block doesn't really do anything useful - can you just load it up into memory without doing the cloning? Does that affect anything?
  • Can you comment out the logic of the manipulations your doing and enable things incrementally to see which part of it is causing the problem?
  • What is the actual error you're seeing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants