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

Free Support Forum - aspose.com

Document format is not correct

After generating document using Aspose. Random pages of documents are not in correct format. Text of the section is coming out of word document.

Please find attached document.Issue is at page number: 4 (8.4 Market Practices Risk section)
SampleDoc.docx (37.1 KB)

  1. How to fix marging of left and right of all the page.

@rs43733 The problem is not in document margins, but in the tables’ widths. You can auto fit the tables to window to make them fit the page width. For example see the following code:

Document doc = new Document(@"C:\Temp\in.docx");

// Get all tables in the document.
NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);
// Fit the table to window.
foreach (Table t in tables)
{
    t.AutoFit(AutoFitBehavior.AutoFitToWindow);
}

doc.Save(@"C:\Temp\out.docx");

Above solution is not working. I found the problem when any column has long answers. this issue occur. Please find attached file. As RelevantActivity column has long text and becuase of that this issue occur

ExpectedResult.JPG (47.0 KB)

@rs43733 Could you please elaborate how the document is generated? It looks like you generated it from some kind of HTML, right? Could you please attach the source HTML here for testing? We will check the issue and provide you more information.

Yes. We are generating document from HTML. We saved data as blob in database. We get the data and pass to html page. This we render this html in Aspose to generate the document. check code for table in “que.ControlType == Table”.

Below is the HTML Code:

using Models;
using System.Text;
using System.Web;

namespace Services
{
    public static class HtmlHelper
    {
        public static async Task<string> CreateHtmlAsync(SectionControl sectionControl)
        {
            // Convert to html
            //Tobe implemented 
            var task = await Task.Run(() =>
            {
                var strHTML = new StringBuilder();
                strHTML.Append("<table style='width:100%; font-family:Overpass,sans-serif!important; padding-right: 10px; padding-left:10px;'>");
                 var queGrp = sectionControl.QuestionGroups.OrderBy(x => x.QuestionGroupOrder);
                foreach (var grp in queGrp)
                {
                    strHTML.AppendFormat("<tr><td style='color:#002d72; font-size:24px !important; line-height:1.25; font-weight:400; padding-bottom:5px; padding-top:10px; font-style:normal;'>{0}</td></tr>", grp.QuestionGroupTitle);
                    if (!string.IsNullOrEmpty(grp.QuestionGroupDescription))
                    {
                        strHTML.AppendFormat("<tr><td style='font-size:16px!important; color:#000000; font-weight:400; line-height:1.25; padding-bottom: 3px; text-align:left;'>{0}</td></tr>", grp.QuestionGroupDescription);
                    }

                    var questions = grp.Questions.OrderBy(q => q.QuestionOrder);
                    if (questions.Count() > 0)
                    {
                        foreach (var que in questions)
                        {
                            if (que.ControlType != "Radio")
                            {
                                if (!string.IsNullOrEmpty(que.QuestionContent))
                                {
                                    strHTML.AppendFormat("<tr><td style='font-size:16px!important; color:#000000; line-height:1.25; padding-top:15px; padding-bottom:5px; text-align:left;'> <b> {0} </b></tr>", que.QuestionContent);
                                }
                            }
                            if (que.ControlType == "Radio" && que.Options != null)
                            {
                                Console.WriteLine();
                                strHTML.AppendFormat("<tr><td style='padding-top:15px; padding-bottom:30px; padding-left:5px; padding-right:5px;'>" +
                                    "<table style='width: 100%'> <tr><td style='width: 80%; font-size:16px!important; color:#000000; line-height:1.25; text-align:left;'> <b> {0} ({1}) </b> </td>" +
                                    "<td style='width: 20%; text-align: center; font-size:14px!important; color:#000000; font-weight:400; line-height:1.25;'>{2}</td></tr> </table>"
                                    + "</td> </tr>",que.QuestionContent, String.Join("/ ", que.Options.Select(p => p.Value)), HttpUtility.HtmlEncode(que.Answers.FirstOrDefault()?.Answer));
                            }
                            else if (que.ControlType == "CKEditor")
                            {
                                strHTML.AppendFormat("<tr><td style='padding-bottom:30px;'>{0}<td></tr>", que.Answers.FirstOrDefault()?.AnswerFormattedData);
                            }
                            else if (que.ControlType == "Table")
                            {
                                strHTML.AppendFormat("<tr><td style='padding-top:5px; padding-bottom:3px;'>");
                                strHTML.AppendFormat("<table style='border-collapse:collapse; table-layout:fixed; width: 80%; align:center;'>");
                                strHTML.AppendFormat("<tr>");
                                foreach (var item in que.SubQuestions)
                                {
                                    strHTML.AppendFormat("<th style='color:#FFFFFF; background-color:#507CD1; font-weight:bold; font-size:14px; height:30px; padding-left:5px;  padding-right:5px; text-align:center;'>{0}</th>", item.QuestionContent);
                                }
                                strHTML.AppendFormat("</tr>");
                                var answerList = new List<AnswerData>();
                                if (que.SubQuestions.Any(x => x.Answers != null && x.Answers.Any()))
                                {
                                    que.SubQuestions.ForEach(x => answerList.AddRange(x.Answers));
                                    if (answerList.Count > 0)
                                    {
                                        var rowCount = answerList.Max(x => x.RowNumber) + 1;
                                        for (int rows = 0; rows < rowCount; rows++)
                                        {
                                            if (rows % 2 == 0) {
                                                strHTML.AppendFormat("<tr style='background-color: #f1f1f1;'>");
                                            }
                                            else { 
                                            strHTML.AppendFormat("<tr style='background-color: #DDDDDD;'>");
                                            }

                                            for (var col = 0; col < que.SubQuestions.Count(); col++)
                                            {
                                                if (que.SubQuestions[col].Answers.Count > rows)
                                                {
                                                    var SubQuestionAnswer = que.SubQuestions[col].Answers[rows]?.Answer ?? que.SubQuestions[col].Answers[rows]?.AnswerFormattedData;
                                                    if (que.SubQuestions[col].ControlType == "DropDown")
                                                    {
                                                        if (string.IsNullOrWhiteSpace(SubQuestionAnswer))
                                                        {
                                                            SubQuestionAnswer = string.Empty;
                                                        }
                                                        else
                                                        {
                                                            SubQuestionAnswer = string.Join(", ", SubQuestionAnswer.Split(',').Select(key => que.SubQuestions[col].Options?.First(x => x.Id == key).Value));
                                                        }
                                                    }
                                                    strHTML.AppendFormat("<td style='text-align:left; font-size:14px; color:#000000; height:30px; padding-left:15px; padding-right:5px; white-space:nowrap;'>{0}</td>", SubQuestionAnswer);
                                                }
                                                else
                                                {
                                                    strHTML.AppendFormat("<td style='text-align:left; font-size:14px; color:#000000; padding-right:15px; padding-left:15px; white-space:nowrap;'></td>");
                                                }
                                            }
                                            strHTML.AppendFormat("</tr>");
                                        }
                                    }

                                }

                                strHTML.AppendFormat("</table></td></tr>");
                            }
                            else if (que.ControlType == "DropDown")
                            {
                                var ddlAnswer = que.Answers.FirstOrDefault()?.Answer;
                                if (string.IsNullOrWhiteSpace(ddlAnswer))
                                {
                                    ddlAnswer = string.Empty;
                                }
                                else
                                {
                                    ddlAnswer = string.Join(", ", ddlAnswer.Split(',').Select(key => que.Options?.First(x => x.Id == key).Value));
                                }

                                strHTML.AppendFormat("<tr><td style='font-size:14px!important; color:#000000; font-weight:400; line-height:1.25; padding-bottom:30px;'>{0}<td></tr>", ddlAnswer);
                            }
                            else
                            {
                                strHTML.AppendFormat("<tr><td style='font-size:14px!important; color:#000000; font-weight:400; line-height:1.25; padding-bottom:30px;'>{0}<td></tr>", que.Answers.FirstOrDefault()?.Answer);

                            }
                        }
                    }
                }
                strHTML.AppendFormat("</table>");
                return strHTML.ToString();
            });

            return task;
        }
    }
}

below is the code for writing the data in word file using Aspose:

private async Task WriteData(DataTable SecData, DocumentBuilder builder, string localReviewType = null, string Request_Number = null, string soeid = null)
{
    int i = 0;
    int displaySectionIdTemp = 1;
    string displaySectionId = "";

    ePAPEditorBLL editorBLL = new ePAPEditorBLL();
    int papBaseRequestNumberLength = Convert.ToInt32(editorBLL.GetPathFromAppLOV(AppConstant.PAPBaseRequestNumberLength));
    var reqNumbers = Request_Number.Split(',');
    var mainReqNumber = reqNumbers[0].Substring(0, papBaseRequestNumberLength);
    bool isDisplayOverviewTab = WriteOverviewTab(builder, mainReqNumber, SecData.Rows[i]["Template_Name"].ToString());

    if (SecData.Rows.Count > 0)
    {
        while (i <= SecData.Rows.Count - 1 && SecData.Rows[i]["PARENTID"] == DBNull.Value)
        {
            if (i > 0 && localReviewType == null)
                builder.InsertBreak(BreakType.PageBreak);
            displaySectionId = SecData.Rows[i]["DISP_SEQ"].ToString();

            //Adjust sequence number when overview tab displays
            if (isDisplayOverviewTab)
            {
                displaySectionId = (Convert.ToInt16(displaySectionId) + 1).ToString();
            }

            if (SecData.Rows[i]["SECTION_NAME"].ToString() == "Appendices")
            {
                displaySectionIdTemp = Convert.ToInt16(displaySectionId);
                //Add the excluded and included  Country List 
                WriteDocAssignedGeographies(builder, ref displaySectionIdTemp, Request_Number);
                //Add Assigned Products Section
                WriteDocAssignedProducts(builder, ref displaySectionIdTemp, Request_Number);
                //Appendices section
                displaySectionId = displaySectionIdTemp.ToString();
                WriteDoc(SecData, (int)SecData.Rows[i]["SECID"], 1, builder, displaySectionId, localReviewType);
                SearchAndWriteChild(SecData, (int)SecData.Rows[i]["SECID"], 1, builder, ref displaySectionId, localReviewType);

            }
            else
            {
                //Call refresh html method/api
                var lockedBy = SecData.Rows[i]["Locked_by"];
                if (lockedBy != null && soeid != null && lockedBy.ToString().ToUpper() == soeid.ToUpper())
                {
                    var secData = await new ePAPsWebApi().RefreshSectionDataAsHTMLAsync(
                        lockedBy.ToString(), (int)SecData.Rows[i]["SECID"], Request_Number);

                    if (secData != null)
                    {
                        SecData.Rows[0]["Sec_Data"] = secData;
                    }
                }

                WriteDoc(SecData, (int)SecData.Rows[i]["SECID"], 1, builder, displaySectionId, localReviewType);
                SearchAndWriteChild(SecData, (int)SecData.Rows[i]["SECID"], 1, builder, ref displaySectionId, localReviewType);

            }

            i++;
        }

    }
}

@rs43733 Could you please provide HTML string built by CreateHtmlAsync on your side? This will simplify testing and provide us the input closer to your real data. Or alternatively please create a simple console application that can be run on our side and demonstrate the problem.

from what I see in your code, you have control over the HTML creation process, so you can specify fixed column widths in your HTML to avoid the problem.

  1. Please find attached HTML string built by CreateHtmlAsync.
    please check section 8.4 Market Practices Risk and 8.8 Fraud & Theft Risk (Excluding Technology)

SampleDoc.docx (79.0 KB)

  1. Text are coming out of page because of long text in table and CKEditor also.

Please find attached HTML string built by CreateHtmlAsync for CKEditor issue. Check Executive Summary section.
SampleDocCKEditor.docx (98.1 KB)

@rs43733 You have attached the output DOCX documents produced by Aspose.Words. But for testing we need your input documents - before processing them using Aspose.Words.
Also, you are using quite old 17.4 version of Aspose.Words, I would recommend to update to the latest 23.3 version.