Free Support Forum - aspose.com

Footnotes and Text are overlapped after DOCX to PDF conversion using .NET

We need latest Aspose dlls to test the text overlapping issue which we are facing in templates printing.

We have old licenses, will this problem get resolved by latest Aspose dlls?

@Sashidhar

To ensure a timely and accurate response, please attach the following resources here for testing:

  • Your input Word document.
  • Please create a standalone console application ( source code without compilation errors ) that helps us to reproduce your problem on our end and attach it here for testing.

As soon as you get these pieces of information ready, we will start investigation into your issue and provide you more information. Thanks for your cooperation.

PS: To attach these resources, please zip and upload them.

Please find the attached console application to replicate the issue, attached the generated PDF with our issues as comments.

when you run the console application it will use the word document placed under “Template” folder and converts to PDF and places the file under “GeneratedDocument” folder.

@Sashidhar

Unfortunately, we have not found any document in your post. Please ZIP and attach the requested resources here for testing.

Can you please check and confirm if you can see now.

If the upload is not visible, please let us know your email address, we will send through email.

@Sashidhar

We have not found any attachment in this thread. You can also share your documents via private message. Please ZIP and attach the documents and code example.

hi Tahir,

for some reason, we are not able to upload the file, can your email address be shared to us in a private message, we share the file via Azure link.

Or, you can share any of your Shared drive locations with us, we will try placing the link.

Sashi

@Sashidhar

Please download your Word document at your end, ZIP and attach it here for testing. You can share .cs file for code example. Thanks for your cooperation.

We are unable to see the uploaded from our side, please check the below code and if document is having footnotes then text is overlapping.

using Aspose.Words;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
class Program
{
private const string CHECKED = “☒”;
private const string UNCHECKED = “☐”;
private static string appDirectory = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"…"));
static void Main(string[] args)
{
InvokePrinting();
Console.WriteLine(“App execution done”);
Console.ReadKey();
}
private static void InvokePrinting()
{
try
{
string keyValuePairs = “TestTemplate¥CurrentDate=2020/11/24‡TestTemplate¥CurrentDateHijri=1422/03/14‡TestTemplate¥LDNo=AD2025700008‡”;
keyValuePairs = keyValuePairs.Replace(“¥”, “:”);

            char[] delimiterChars = { '‡' };
            string[] keyValuePairArray = keyValuePairs.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);

            var tuples = ParsePrintoutKeyValueTuple(keyValuePairArray);
            string printoutName = string.Empty;
            foreach (var tuple in tuples)
            {
                string url = "";
                printoutName = tuple.Item1;
                if (printoutName.Contains("#"))
                {
                    printoutName = printoutName.Split('#')[0];

                }

                string templatePath = string.Format("{0}\\{1}.docx", appDirectory+"Template\\", printoutName);
                string instanceName = string.Format("{0}_{1}_{2}.docx", printoutName, "10001", DateTime.Now.ToString("yyyyMMddmmssff"));
                string instancePath = appDirectory+ "GeneratedDocument\\" + instanceName;

                string file = GenerateInstance(templatePath, instancePath, tuple.Item2);

            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error occured: " + ex.Message);
            Console.ReadKey();
        }
    }
    static List<Tuple<string, NameValueCollection>> ParsePrintoutKeyValueTuple(string[] printoutKeyValueTuple)
    {
        try
        {
            if (printoutKeyValueTuple == null || printoutKeyValueTuple.Length == 0)
            {
                return null;
            }
            List<Tuple<string, NameValueCollection>> tuples = new List<Tuple<string, NameValueCollection>>();
            foreach (string tuple in printoutKeyValueTuple)
            {
                string printout = "", key = "", value = "";
                if (tuple.Contains(":"))
                {
                    string[] parts = tuple.Split(':');
                    printout = parts[0];
                    if (parts[1].Contains("="))
                    {
                        string[] nameValue = parts[1].Split('=');
                        key = nameValue[0];
                        value = nameValue[1];
                    }
                }
                var item = tuples.Find(t => t.Item1 == printout);
                if (item == null)
                {
                    NameValueCollection nameValuePairs = new NameValueCollection();
                    nameValuePairs.Add(key, value);
                    tuples.Add(new Tuple<string, NameValueCollection>(printout, nameValuePairs));
                }
                else
                {
                    item.Item2.Add(key, value);
                }
            }
            return tuples;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.ToString());
        }
    }

    public static string GenerateInstance(string templatePath, string instancePath, NameValueCollection nameValuePairs)
    {

        try
        {
            #region Validation
            var outputMem = new MemoryStream();
            if (!File.Exists(templatePath))
            {
                throw new ArgumentException("The template file doesn't exist", "templatePath");
            }

            if (!Directory.Exists(System.IO.Path.GetDirectoryName(instancePath)))
            {
                throw new ArgumentException("The directory doesn't exist", "instancePath");
            }

            if (String.Compare(templatePath, instancePath, StringComparison.OrdinalIgnoreCase) == 0)
            {
                throw new ArgumentException("The instance path cannot be the same as the template path", "instancePath");
            }

            #endregion

            PrepareInstanceFile(templatePath, instancePath);
            InitializeAsposeLicense();

            // Open the Word document specified by instancePath
            using (WordprocessingDocument theDoc = WordprocessingDocument.Open(instancePath, true))
            {
                // Get the package part that holds the main document content
                MainDocumentPart mainPart = theDoc.MainDocumentPart;

                foreach (SdtElement sdt in mainPart.Document.Descendants<SdtElement>().ToList())
                {
                    ReplaceText(sdt, nameValuePairs);
                    //DeleteSdtElementAndKeepContent(mainPart, sdt);
                }

                foreach (var headerPart in mainPart.HeaderParts)
                {
                    foreach (SdtElement sdt in headerPart.Header.Descendants<SdtElement>().ToList())
                    {
                        ReplaceText(sdt, nameValuePairs);
                    }
                    headerPart.Header.Save();
                }

                foreach (var footerPart in mainPart.FooterParts)
                {
                    foreach (SdtElement sdt in footerPart.Footer.Descendants<SdtElement>().ToList())
                    {
                        ReplaceText(sdt, nameValuePairs);
                    }

                    footerPart.Footer.Save();
                }
                var tuplesArray = nameValuePairs.AllKeys.ToArray();

                mainPart.Document.Save();
            }

            string filePath = instancePath;
            filePath = ConvertToPdf(filePath);

            return filePath;
        }
        catch (Exception ex)
        {
            throw;
        }
    }
    private static void PrepareInstanceFile(string templatePath, string instancePath)
    {
        try
        {
            // Copy a new file name from template file
            if (File.Exists(instancePath))
            {
                File.Delete(instancePath);
            }
            File.Copy(templatePath, instancePath, true);
            // Remove read only
            FileInfo file = new FileInfo(instancePath);
            file.IsReadOnly = false;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.ToString());
        }

    }
    private static void InitializeAsposeLicense()
    {
        Console.WriteLine("InitializeAsposeLicense Method Call", "Start");
        try
        {
            var partialLicensePath = "Aspose.Total.lic";
            if (string.IsNullOrEmpty(partialLicensePath))
                return;

            var licensePath = string.Format(@"{0}\{1}", appDirectory, partialLicensePath);
            if (!File.Exists(licensePath))
                return;

            var license = new Aspose.Words.License();
            using (var licenseStream = new FileStream(licensePath, FileMode.Open, FileAccess.Read))
            {
                license.SetLicense(licenseStream);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error Occured in GenerateInstance: " + ex.ToString(), "Exception Occured");
            throw new Exception(ex.ToString());
        }
    }
    private static void ReplaceText(SdtElement sdt, NameValueCollection nameValuePairs)
    {
        Console.WriteLine("ReplaceText Method Call", "Start");
        try
        {
            SdtAlias alias = sdt.Descendants<SdtAlias>().FirstOrDefault();

            if (alias != null)
            {
                var xText = GetText(sdt);

                if (xText != null)
                {
                    // Check if this a check box or not
                    if (alias.Val.Value.Contains("_"))
                    {
                        string[] parts = alias.Val.Value.Split('_');
                        string value = GetValueByName(nameValuePairs, parts[0]);
                        if (parts[1] == value)
                        {
                            xText.Text = CHECKED;
                        }
                        else
                        {
                            xText.Text = UNCHECKED;
                        }
                    }
                    else
                    {
                        string sdtTitle = alias.Val.Value;
                        string value = GetValueByName(nameValuePairs, sdtTitle);
                        xText.Text = value;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error Occured in ReplaceText: " + ex.ToString(), "Exception Occured");
            throw new Exception(ex.ToString());
        }
    }
    private static string GetValueByName(NameValueCollection nameValuePairs, string name)
    {
        Console.WriteLine("GetValueByName Method Call", "Start");
        try
        {
            if (nameValuePairs == null || nameValuePairs.Count == 0 || nameValuePairs[name] == null || nameValuePairs[name] == "null")
            {
                return "";
            }

            if (name == "AmountText")
            {
                string amount = nameValuePairs["Amount"];

                decimal value;
                if (decimal.TryParse(amount, out value))
                {
                    return null;
                }
                else
                {
                    return nameValuePairs[name];
                }
            }
            else
            {
                return nameValuePairs[name];
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error Occured in GetValueByName: " + ex.ToString(), "Exception Occured");
            throw new Exception(ex.ToString());
        }
    }
    private static DocumentFormat.OpenXml.Wordprocessing.Text GetText(SdtElement sdt)
    {
        Console.WriteLine("GetText Method Call", "Start");
        try
        {
            DocumentFormat.OpenXml.Wordprocessing.Run run = null;

            if (sdt is SdtRun)
            {
                SdtRun xRun = (SdtRun)sdt;
                SdtContentRun xContentRun = xRun.Descendants<SdtContentRun>().FirstOrDefault();
                run = xContentRun.Descendants<DocumentFormat.OpenXml.Wordprocessing.Run>().FirstOrDefault();
            }

            if (sdt is SdtCell)
            {
                SdtCell xRun = (SdtCell)sdt;
                SdtContentCell xContentRun = xRun.Descendants<SdtContentCell>().FirstOrDefault();
                run = xContentRun.Descendants<DocumentFormat.OpenXml.Wordprocessing.Run>().FirstOrDefault();
            }

            if (sdt is SdtBlock)
            {
                SdtBlock xRun = (SdtBlock)sdt;
                SdtContentBlock xContentRun = xRun.Descendants<SdtContentBlock>().FirstOrDefault();
                run = xContentRun.Descendants<DocumentFormat.OpenXml.Wordprocessing.Run>().FirstOrDefault();
            }

            if (run != null)
            {
                return run.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault();
            }
            else
            {
                return null;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error Occured in GetText: " + ex.ToString(), "Exception Occured");
            throw new Exception(ex.ToString());
        }
    }

    public static string ConvertToPdf(string filePath)
    {
        try
        {
            InitializeAsponseWordsLicense();

            // Writing it to PDF
            Aspose.Words.Document doc = new Aspose.Words.Document(filePath);
            string outputFilePath = Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + ".pdf";
            doc.Save(outputFilePath, SaveFormat.Pdf);
            Console.WriteLine("PDF file is generated");
            return outputFilePath;
        }
        catch (Exception)
        {

            return filePath;

        }
    }
    private static void InitializeAsponseWordsLicense()
    {
        string licensePath = appDirectory+ "bin\\Aspose.Total.lic";

        if (File.Exists(licensePath))
        {
            Aspose.Words.License license = new Aspose.Words.License();
            using (FileStream licenseStream = new FileStream(licensePath, FileMode.Open))
            {
                license.SetLicense(licenseStream);
            }
        }
        else
        {
            Console.WriteLine(@"Aspose license file was not found in the location specified in config file. Using Aspose without a license", System.Diagnostics.TraceEventType.Warning);
        }
    }

    private static void InitializeAsponsePdfLicense()
    {
        string licensePath = appDirectory + "bin\\Aspose.Total.lic";

        if (File.Exists(licensePath))
        {
            Aspose.Pdf.License license = new Aspose.Pdf.License();
            using (FileStream licenseStream = new FileStream(licensePath, FileMode.Open))
            {
                license.SetLicense(licenseStream);
            }
        }
        else
        {
            Console.WriteLine(@"Aspose license file was not found in the location specified in config file. Using Aspose without a license", System.Diagnostics.TraceEventType.Warning);
        }
    }

}

}

@Sashidhar

Unfortunately, it is difficult to say what the problem is without document. Please check the attached image for document upload in ZIP file format. upload.png (6.8 KB)

You can also ZIP and attach your Visual Studio project for testing. Thanks for your cooperation.

we are unable to uploade total solution may be because of aspose dll’s size issue, Uploading the code after removing the aspose dll’s in bin folder PrintingTest.zip (2.7 MB)
Below are Aspose DLL’s version details we are using
Aspose.Pdf.dll – Product Version 2012.07.01 -->AsposePDF.PNG (18.6 KB)
Aspose.Word.dll -->Product Version 2013.04.30 -->AsposeWords.PNG (17.1 KB)

Please check with this code and help us on this issue.

@Sashidhar

We have tested the scenario and have managed to reproduce the same issue at our side. For the sake of correction, we have logged this problem in our issue tracking system as WORDSNET-21608. You will be notified via this forum thread once this issue is resolved.

We apologize for your inconvenience.

Thanks for the reply, Any Expected ETA or workaround to fix this issue.

@Sashidhar

We try our best to deal with every customer request in a timely fashion, we unfortunately cannot guarantee a delivery date to every customer issue. Our developers work on issues on a first come, first served basis. We feel this is the fairest and most appropriate way to satisfy the needs of the majority of our customers.

Currently, your issue is pending for analysis and is in the queue. Once our product team completes the analysis of your issue, we will then be able to provide you an estimate.

Dear Tahir,

Do we have any other alternatives like in the newer versions of Aspose dll’s is this already fixed or this issue exists in all newer version?

@Sashidhar

We managed to reproduce this issue using the latest version of Aspose.Words for .NET.

Please note that we do not provide support for older released versions of Aspose.Words. Moreover, we do not provide any fixes or patches for old versions of Aspose products either. All fixes and new features are always added into new versions of our products.

This is production problem in a Bank, Is there any update on when the fix will be available.

@Sashidhar

We will inform you via this forum thread once there is any update available on this issue. Thanks for your patience.

You reported this issue in free support forum and it will be treated with normal priority. To speed up the progress of issue’s resolution, we suggest you please check our paid support policies from following link.
Paid Support Policies

@Sashidhar

Your document utilizes exotic font “Frutiger LT Arabic 45 Light”. If this font is not installed on the system, MS word substitutes it to “Arial” but Aspose.Words substitutes it to “Courier New”.

Please install this font on the machine where you are converting document to PDF. If you still face problem, please ZIP and attach font “Frutiger LT Arabic 45 Light” here for further testing.

Please also convert Word document to XPS and PDF using MS Word and share them here. Thanks for your cooperation.

Thanks for your reply.

  1. Frutiger LT Arabic 45 Light is installed already in the machine, Font is attaching here Frutiger LT Arabic 45 Light.zip (74.8 KB)
  1. Saved as PDF using the Word document Original Word TestTemplate_Saved As PDF.pdf (1.0 MB)
  2. Not able to save as XPS getting error. Save as XPS failed.PNG (24.1 KB)
  3. Converted word using aspose dlls Converted PDF using Aspose words_TestTemplate.pdf (315.4 KB)
  4. Original word document. Original Word TestTemplate.zip (129.0 KB)

Thanks for your support.