I have a base 64 image that I’m fetching from the database and I want to replace some text in my docx for this generated image.
Could you show me how to do this?
@anemam you can use the Replace
method provided by the API and alter it behavior to replace the text with an image (in this case I used the InsertImage
method of DocumentBuilder
class). Please check the following example:
Document doc = new Document("C:\\Temp\\input.docx");
FileStream image = File.OpenRead("C:\\Temp\\img.png");
// You dont need this because your image is actually a byte array
byte[] byteImage = ReadFully(image);
ReplaceWithImageHandler findElem = new ReplaceWithImageHandler(byteImage);
FindReplaceOptions opt = new FindReplaceOptions()
{
ReplacingCallback = findElem,
Direction = FindReplaceDirection.Backward,
};
doc.Range.Replace("##image", string.Empty, opt);
doc.Save("C:\\Temp\\output.docx");
public class ReplaceWithImageHandler : IReplacingCallback
{
private readonly byte[] _image;
public ReplaceWithImageHandler(byte[] image)
{
_image = image;
}
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
{
DocumentBuilder builder = new DocumentBuilder((Document)args.MatchNode.Document);
builder.MoveTo((Run)args.MatchNode);
// You can use the breaks or not
//builder.InsertBreak(BreakType.ParagraphBreak);
builder.InsertImage(_image);
//builder.InsertBreak(BreakType.ParagraphBreak);
return ReplaceAction.Replace;
}
}
img.png (5.3 KB)
input.docx (14.9 KB)
output.docx (18.3 KB)
Perfect! This worked correctly for me.
One more question, this insert worked for me, but when I insert the image and save it in PDF it doesn’t bring the complete image, follow the attached examples.
What could this be?
TesteAssinatura (1).docx (19.6 KB)
TesteAssinatura (1).pdf (24.2 KB)
@anemam Sorry, could you please mark the part of the image that is missing? I am seeing the same image in the docx file and the PDF (opened with Adobe and Google Chrome).
I selected the image in Adobe for reference.
Also, make sure that you are viewing your result on a proper monitor. The color of the image is almost white and may blend with the background if your monitor doesn’t offer sufficient contrast and color accuracy. In my case, I can see the image on two of my monitors, but it is completely missed on the third one of lower quality.
@anemam This thread is turning into a copy of this one: Save in PDF aspose words not working - #7 by eduardo.canal. So, let’s please continue there to avoid duplication.
Perfect, continue there.