Prevent unintended dateformat conversion

We have field in the word template, that is converting text which is simillarly looking like date.
For example, 31-12-289 becomes: Mon Dec 30 19:00:00 EST 289

we would like to avoid that for this specific field. Any suggestions please.

To prevent unintended date format conversion in your Word template, you can control how fields are updated by setting the culture source for field updates. This allows you to specify whether the culture is derived from the field code or the document itself.

Here are the steps you can follow:

  1. Set the Field Update Culture Source: You can set the FieldUpdateCultureSource property of the FieldOptions class. This property allows you to choose between using the culture from the field code or the document’s culture settings.

  2. Use a Specific Locale: When inserting fields, you can specify a locale that does not interpret your text as a date. For example, if you are inserting a field that should not be treated as a date, ensure that the locale you set does not format it as such.

  3. Example Code:
    Here’s a simple example in C# to illustrate how to set the culture source:

    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);
    
    // Insert a field with a specific locale
    builder.InsertField("MERGEFIELD MyField \\@ \"dd-MM-yyyy\"", "31-12-289");
    
    // Set the field update culture source to use the document's culture
    doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.Document;
    
    // Save the document
    doc.Save("output.docx");
    

By following these steps, you can ensure that the specific field in your template does not get converted into an unintended date format. This approach gives you control over how fields are processed and displayed in your Word documents.

If you need further assistance or examples, feel free to ask!

@adueeoc Could you please attach your input and output documents here for testing? We will check the issue and provide you more information.

We don’t want to convert field to date, just want to keep it as a string
…in your example it seems be trying to conver to dateformat

builder.InsertField("MERGEFIELD MyField \\@ \"dd-MM-yyyy\"", "31-12-289");

Attched the template we are using field we are referring <<fepanumber>> on the right top.

see the PDF with convered value.

ChargeOfDiscrimination-draft.docx (60.6 KB)

Form 5 Charge of Discrimination.pdf (87.2 KB)

@adueeoc Could you please provide code that will allow us to reproduce the problem? We will check the issue and provide you more information. You can try disabling field updating upon saving to PDF:

PdfSaveOptions opt = new PdfSaveOptions();
opt.setUpdateFields(false);
doc.save("C:\\Temp\\out.pdf", opt);

We tried with the code below, but no change! Also, below is the java method code

@SuppressWarnings("resource")
@Override
public ByteArrayOutputStream transform(MergeRequest request) throws ImsDocumentTransformationException {
        
    TemplateData templateData = request.getTemplateData();
    Template template = request.getTemplate();
    String templateName = template.getTemplateName();
    ObjectMapper objectMapper = new ObjectMapper();
    log.info("Executing AdvancedMergeService transform on {} template.", templateName);
    Document documentTemplate = null;
    ByteArrayOutputStream documentOutputStream = null;
        
    try {
        documentTemplate = documentManager.instantiateWordDocument(template);
        documentOutputStream = new ByteArrayOutputStream();
        log.info("Made document Template");
            
        ReportingEngine engine = new ReportingEngine();
            
        engine.setOptions(ReportBuildOptions.REMOVE_EMPTY_PARAGRAPHS);
        Map<String, Object> mergeFields = templateData.getMergeFields();
            
        DocumentBuilder builder = new DocumentBuilder(documentTemplate);
        boolean isBookmarkFound = builder.moveToBookmark(CP_LEGAL_REP_DIGITAL_IMAGE);
        if (isBookmarkFound) {
            builder.insertImage(templateData.getSignatureBlob(), 200, 20);
        }
            
        mergeFields.replaceAll((key, oldValue) -> oldValue instanceof String ? cleanTextContent(oldValue.toString()) : oldValue);
        mergeFields.replaceAll((key, oldValue) -> oldValue instanceof ArrayList ? cleanTextContent((ArrayList<Object>) oldValue) : oldValue);
            
        byte[] templateDataJson = objectMapper.writeValueAsBytes(mergeFields);
            
        JsonDataSource jsonDataSource = new JsonDataSource(new ByteArrayInputStream(templateDataJson));
        engine.buildReport(documentTemplate, jsonDataSource);
        log.info("Executed merge operation");
        //OrderedKeyValueListDataSource dataSource = new OrderedKeyValueListDataSource(templateData.getMergeFields());
        //engine.buildReport(documentTemplate, dataSource.getValues(), dataSource.getKeyNames());
        //log.info("Executed merge operation");
            
        Integer saveFormat = saveFormatLookup.getSaveFormatForMediaType(request.getTemplateOutputContentType());
        Integer saveFormatPdf = saveFormatLookup.getSaveFormatForMediaType(pdfDocumentType);
        //Make the converted pdf as read only when the type is pdf
        if (saveFormatPdf == saveFormat) {
            PdfSaveOptions saveOptions = pdfSaveOptionsUtilityService.getSaveOptions(pdfDocumentType);
            saveOptions.setUpdateFields(false);
            //saveOptions = pdfSaveOptionsUtilityService.digitalSignature(saveOptions);
            // Render the document to PDF format with the specified permissions
            documentTemplate.save(documentOutputStream, saveOptions);
        } else {
            documentTemplate.save(documentOutputStream, saveFormat);
        }
            
    } catch (IllegalStateException stateException) {
        String errorMessage = "Please correct the data. Invalid values has been provided for one or more template data fields.";
        String exceptionMessage = stateException.getMessage();
        if (StringUtils.isNotBlank(exceptionMessage)) {
            int missingFieldMessage = exceptionMessage.indexOf("Can not get the value of member ");
            if (missingFieldMessage != -1) {
                String[] missingFields = StringUtils.substringsBetween(exceptionMessage.substring(missingFieldMessage), "'", "'");
                if (Objects.nonNull(missingFields) && missingFields.length > 0) {
                    errorMessage = "There are missing template data field values that are required. FieldName: " + missingFields[0];
                }
            }
        }
        log.error(errorMessage, stateException);
        throw new MissingTemplateDataException(errorMessage);
    } catch (Exception mergeException) {
        String errorMessage = "There was an error merging data to the template " + templateName;
        log.error(errorMessage, mergeException);
        throw new MergeOperationException(errorMessage);
    }
    return documentOutputStream;
}

Also, we need the solution to be field specifc (not the setting at the document level), not affect formatting for other fields in the document.

@adueeoc As I can see you are using LINQ Reporting Engine to fill your template with data and JSON as a datasource. In your case you can specify JsonDataLoadOptions.ExactDateTimeParseFormats to prevent the value in your JSON to be parsed and formatted as date.
Alternative, you can specify date format in your template, please see our documentation for more information:
https://docs.aspose.com/words/java/outputting-expression-results/

not sure if i understand the solution below, as the you seem to suggest on how to convert to a specific date format.
In our case, we don’t want the input string to be conveted to date, just keep it as a string itself and no conversion required for this field.

thanks,
Praveen

@adueeoc For example if you have the following data:

{
  "data": {
    "value": "31-12-289"
  }
}

you can specify ExactDateTimeParseFormats to empty string, in this case "31-12-289" will not be parsed as date:

JsonDataLoadOptions opt = new JsonDataLoadOptions();
opt.setExactDateTimeParseFormats(Arrays.asList(new String[] {""}));
JsonDataSource data = new JsonDataSource("C:\\Temp\\data.json", opt);
        
Document doc = new Document("C:\\Temp\\in.docx");
ReportingEngine engine = new ReportingEngine();
engine.buildReport(doc, data, "data");
doc.save("C:\\Temp\\out.docx");

data.zip (200 Bytes)
in.docx (12.6 KB)
out.docx (10.1 KB)

We can’t find JsonDataLoadOptions in the aspose package

Also, in the same JSON, we have few other fields which are dates and one field which is not a date, which has value simillar to date!

@adueeoc Which version of Aspose.Words do you use? Using JsonDataLoadOptions.ExactDateTimeParseFormats you can specify an exact date format that Aspose.Words will recognize as date. Other values that does not match the specified format will not be considered as simple string. For demonstration purposes I have used an empty string as date format, in this case none of the value are parsed as date.

we are using 20.3 version

@adueeoc Thank you for additional information. The above mentioned property has been introduced in 23.4 version of Aspose.Words as a replacement of obsolete JsonDataLoadOptions.ExactDateTimeParseFormat.