How can I replace a word in the header with an image

Hello!
I have set up a function using .NET and C# with the free version of Aspose.Words. It works very well, but now I want to convert to Aspose.Words Cloud. Can I use the same code, or do I have to modify it. I realize I have to change the “Document” and “HeaderFooter” parts, as they are an ambiguous reference between the Aspose.Words.Cloud.Sdk and the Aspose.Words sdk. Are there anything else I have to keep in mind or change?

//Aspose - Replace word with image
var tempDir = Path.GetTempPath();
var tempProj = Path.Combine(tempDir, "myproject");
Document doc = new Document(tempProj + "/" + trimmedName);
DocumentBuilder builder = new DocumentBuilder(doc);
FindReplaceOptions options = new FindReplaceOptions();
options.MatchCase = false;
HeaderFooterCollection headersFooters = doc.FirstSection.HeadersFooters;
HeaderFooter header = headersFooters[HeaderFooterType.HeaderPrimary];

header.Range.Replace("logo", "", options);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

builder.InsertImage("https://myproject/assets/logos/" + logoPath); //Fetch logo
var filePath = Path.Combine(tempProj, trimmedName);
doc.Save(filePath, SaveFormat.Docx);
await _dcFileBlobService.UploadDocWithLogo(copyRequest.FileId, copyRequest.FolderId.ToString(), copyRequest.FileId, filePath, copyRequest.DestinationId.ToString());

@protektitadm

Yes, you need to modify your Aspose.Words on-premise code to replace text in a Word document and insert an image in the header using Aspose.Words Cloud API. Following are the API methods you will use to accomplish the task. First, find the text and replace it with empty text, find the paragraph node path of the empty text in the headerfooter of the document and insert an image in the headerfooter using the paragraph node path. Please feel free to contact us for any further assistance.

ReplaceText
GetParagraphs
InsertDrawingObject

I have managed to modify the code, using the documentation you included, in order to replace text and insert an image individually. I don’t quite understand how I am supposed to insert the image in the header. This is the code I am currently working with for the header and insert image part:

// Path to the temp directory and specific folder where the file is located
var tempDir = Path.GetTempPath();
var tempArgus = Path.Combine(tempDir, "argus");

//Get the header element
using var requestDocumentHeader = System.IO.File.OpenRead(tempArgus + "/" + trimmedName);
var request = new GetHeaderFooterOnlineRequest(requestDocumentHeader, 0);
var respHeader = await wordsApi.GetHeaderFooterOnline(request);

var paragraphLink = respHeader.HeaderFooter.Link.Href;

requestDocumentHeader.Close();

//Insert logo
using var requestDocumentImage = System.IO.File.OpenRead(tempArgus + "/" + trimmedName);
var requestDrawingObject = new DrawingObjectInsert() {
    Height = 0f,
    Left = 0f,
    Top = 0f,
    Width = 0f,
    RelativeHorizontalPosition = DrawingObjectInsert.RelativeHorizontalPositionEnum.Margin,
    RelativeVerticalPosition = DrawingObjectInsert.RelativeVerticalPositionEnum.Margin,
    WrapType = DrawingObjectInsert.WrapTypeEnum.Inline
};

using var requestImageFile = System.IO.File.OpenRead("C:\\Users\\USERNAME\\Pictures\\test.png");
var insertRequest = new InsertDrawingObjectOnlineRequest(requestDocumentImage, requestDrawingObject, requestImageFile, nodePath: paragraphLink);

var responseImg = await wordsApi.InsertDrawingObjectOnline(insertRequest);

The API endpoint it is trying to call on the InsertDrawingObjectOnlineRequest() is: http://api.aspose.cloud/v4.0/words/online/post/http:/api.aspose.cloud/v4.0/words/2cfcdc57-db28-47f7-b0cc-1a2222f1b74d/sections/0/headersfooters/0/drawingObjects

This gives me a NotFound exception. I guess the nodePath is wrong, but I don’t exactly know the value I am looking for.

Also, is it not beneficial to use the GetParagraphs to get the header before replacing the word in the header as well? In my case, I have documents with a header, and that header includes the word “logo”. That is the only word in the header. That is also the only word I want to replace. I don’t want other instances of the word “logo” elsewhere in the document to be replaced.

@protektitadm

Please share your sample input document with us as well. We will test the scenario and guide you accordingly.

82-070 - Brøyting og snørydding.docx (32.5 KB)

This is an example of a document that could be passed through. Every document is set up in the same way. A header with the word logo, a body with text, and a footer with document information. I don’t ever want the body or footer to be touched. The only change I will ever want to do is swap the word “logo” in the header with an image.

@protektitadm

Thanks for sharing the input document. We are looking into your requirements and will update you soon accordingly.

@protektitadm

You may get the word paragraph index using the search method and then insert an image into that paragraph using the insertdrawingobject method. Please check the sample code, you can amend it as per your requirements.

string localFile = @"C:\Temp\82-070 - Brøyting og snørydding.docx";
FileStream requestDocument;
requestDocument = File.OpenRead(localFile);
var request = new SearchOnlineRequest();
request.Document = requestDocument;
request.Pattern = "logo";
var actual = await wordsApi.SearchOnline(request);
var paragraphLink = actual.SearchResults.ResultsList[0].RangeStart.Node.Link.Href.Substring(72,40);

requestDocument = File.OpenRead(localFile);

var requestDrawingObject = new DrawingObjectInsert()
{
    Height = 0f,
    Left = 0f,
    Top = 0f,
    Width = 0f,
    RelativeHorizontalPosition = DrawingObjectInsert.RelativeHorizontalPositionEnum.Margin,
    RelativeVerticalPosition = DrawingObjectInsert.RelativeVerticalPositionEnum.Margin,
    WrapType = DrawingObjectInsert.WrapTypeEnum.Inline
};

var requestImageFile = System.IO.File.OpenRead("C:\\Temp\\test.png");
var insertRequest = new InsertDrawingObjectOnlineRequest(requestDocument, requestDrawingObject, requestImageFile, nodePath: paragraphLink);

var responseImg = await wordsApi.InsertDrawingObjectOnline(insertRequest);
var fileStream = System.IO.File.Create(@"C:\Temp\replaceText.docx");
responseImg.Document.First().Value.CopyTo(fileStream);
fileStream.Close();

I tried implementing the code you provided, but the word “logo” was still present in the header. It might be a difference in the way my files are saved and worked with in the background, and that the “replaceText” change didn’t get saved properly.

I ended up taking the two lines of code where you find the header and “paragraphLink”, and baked them into my existing code, as I kind of only needed the correct nodePath in the code I gave you. The nodePath I got from those two lines worked perfectly, and the image now gets inserted in the header.

I have a feeling it will replace all other instances of the word “logo” though, albeit I haven’t tested that case yet.

Also, is there a possibility to just set a max height on the image, and let the image adjust its width accordingly? I tried setting a height, but the image got distorted, because the width stayed the same.

@protektitadm

I am afraid there is no direct method available to replace a word with an image. So you can remove it either using the ReplaceText method or the DeleteRun method.

WordsApi wordsApi = new WordsApi(config);
// Search Word
string localFile = @"C:\Temp\82-070 - Brøyting og snørydding.docx";
FileStream requestDocument;
requestDocument = File.OpenRead(localFile);
var request = new SearchOnlineRequest();
request.Document = requestDocument;
request.Pattern = "logo";
var actual = await wordsApi.SearchOnline(request);
var paragraphLink = actual.SearchResults.ResultsList[0].RangeStart.Node.Link.Href.Substring(72,40);
            
// Delete Run
var requestDeleteRun = new DeleteRunOnlineRequest();
requestDocument = File.OpenRead(localFile);
requestDeleteRun.Document = requestDocument;
requestDeleteRun.ParagraphPath = paragraphLink;
requestDeleteRun.Index = 0;
var deleteRunResponse = await wordsApi.DeleteRunOnline(requestDeleteRun);          

// Insert Image
var requestDrawingObject = new DrawingObjectInsert()
{
    Height = 0f,
    Left = 0f,
    Top = 0f,
    Width = 0f,
    RelativeHorizontalPosition = DrawingObjectInsert.RelativeHorizontalPositionEnum.Margin,
    RelativeVerticalPosition = DrawingObjectInsert.RelativeVerticalPositionEnum.Margin,
    WrapType = DrawingObjectInsert.WrapTypeEnum.Inline
};

var requestImageFile = System.IO.File.OpenRead("C:\\Temp\\test.png");
var insertRequest = new InsertDrawingObjectOnlineRequest(deleteRunResponse.First().Value, requestDrawingObject, requestImageFile, nodePath: paragraphLink);

var responseImg = await wordsApi.InsertDrawingObjectOnline(insertRequest);
var fileStream = System.IO.File.Create(@"C:\Temp\replaceText.docx");
responseImg.Document.First().Value.CopyTo(fileStream);
fileStream.Close();

Currently, the feature is not available. Please share how you can achieve this in MS Word. We will investigate it and try to implement it.

I am satisfied with the way my image is inserted for now, and will experiment a bit more if that is necessary at a later stage. Thank you very much for the assistance!

When I insert an image in MS Word, and adjust its size, the aspect ratio is locked by default.
image.png (1.3 KB)

This is an image of the size section under the “Picture Format” tab. If I adjust the height here, or pull on the image itself, the width follows.
If you press the expand button in the lower right hand corner of that section, a little layout window will pop up:
image.png (10 KB)

Here you can see the “Lock aspect ratio”-checkbox. This is checked by default. By unchecking it, I can adjust the height and width separately. My suggestion is to add a property such as “LockAspectRatio = true/false”, and then set the height and/or width like you do already. I don’t know if it is possible of course, and if it is, there are probably other ways to implement it, but I would assume more users like me would like a feature like this.

Thank you again for the support, it was really helpful!

@protektitadm

We have logged a feature request(WORDSCLOUD-2578) in our internal issue tracking system. We will keep you updated about the issue resolution progress in this forum thread.

The issues you have found earlier (filed as WORDSCLOUD-2578) have been fixed in this update. This message was posted using Bugs notification tool by Ivanov_John

2 Likes