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

Free Support Forum - aspose.com

Insert dynamic images [Replace] to the word document- Aspose java

Hello everyone I have the following method:


static void InsertImageDynamicallyAsposeToDoc()throws Exception{
//instance doc File
Document doc = new Document(“C:/documents/template.doc”);
//read json File
Map<String,Object> parameters = getFromJson().getParameters();
for (Entry<String, Object> entry : parameters.entrySet())
{
DocumentBuilder builder = new DocumentBuilder(doc);
builder.startBookmark("[key]");
Bookmark bm = doc.getRange().getBookmarks().get("[key]");
builder.endBookmark("[key]");
builder.moveTo(bm.getBookmarkStart());
builder.insertImage(“D:/imgage.jpg”);
bm.setText("");
}
doc.save(“D:/documents/valuesReplaced.doc”);
}

This run correctly, but not replace the variable of document template.

Thanks for your help

Hi,


Thanks for your inquiry. Please see attached sample input/output Word documents and try executing the following code:
Document doc = new Document(getMyDir() + “template.docx”);
DocumentBuilder builder = new DocumentBuilder(doc);

Shape img = builder.insertImage(getMyDir() + “Aspose.Words.jpg”);

Bookmark bm = doc.getRange().getBookmarks().get(“bm”);
bm.setText("");

BookmarkStart start = bm.getBookmarkStart();
start.getParentNode().insertAfter(img, start);

doc.save(getMyDir() + “awjava-15.9.0.docx”);

Hope, this helps.

In case the problem still remains, please attach your input Word document and expected document here for our reference. We will investigate the structure of your expected document as to how you want your final output be generated like. You can create expected document using Microsoft Word. We will then provide you code to achieve the same using Aspose.Words.

Best regards,

Thank so much! for response, my problem was my template document, you know other ways by insert image, when i want replace a string text into my template document? for example replace the image where found the string text = [image1].I do not want to use Bookmark


Thanks for your help.


Hi,


Thanks for your inquiry. Please find attached couple of input/output Word documents and try executing the following code:
Document doc = new Document(getMyDir() + “template.docx”);

Pattern regex = Pattern.compile("\[image1\]", Pattern.CASE_INSENSITIVE);
doc.getRange().replace(regex, new ReplaceEvaluator(), false);

doc.save(getMyDir() + “awjava-15.9.0.docx”);


static class ReplaceEvaluator implements IReplacingCallback
{
/**
* This method is called by the Aspose.Words find and replace engine for each match.
* This method highlights the match string, even if it spans multiple runs.
*/

public int replacing(ReplacingArgs e) throws Exception
{
// This is a Run node that contains either the beginning or the complete match.
Node currentNode = e.getMatchNode();
    <font color="GREEN"><i>// The first (and may be the only) run can contain text before the match,

// in this case it is necessary to split the run.
if (e.getMatchOffset() > 0)
currentNode = splitRun((Run)currentNode, e.getMatchOffset());

    <font color="GREEN"><i>// This array is used to store all nodes of the match for further highlighting.

ArrayList runs = new ArrayList();

    <font color="GREEN"><i>// Find all runs that contain parts of the match string.

int remainingLength = e.getMatch().group().length();
while (
(remainingLength > 0) &&
(currentNode != null) &&
(currentNode.getText().length() <= remainingLength))
{
runs.add(currentNode);
remainingLength = remainingLength - currentNode.getText().length();

        <font color="GREEN"><i>// Select the next Run node.

// Have to loop because there could be other nodes such as BookmarkStart etc.
do
{
currentNode = currentNode.getNextSibling();
}
while ((currentNode != null) && (currentNode.getNodeType() != NodeType.RUN));
}

    <font color="GREEN"><i>// Split the last run that contains the match if there is any text left.

if ((currentNode != null) && (remainingLength > 0))
{
splitRun((Run)currentNode, remainingLength);
runs.add(currentNode);
}

    DocumentBuilder builder <font color="BLUE">=</font> <font color="RED"><b>new</b></font> DocumentBuilder<font color="BLUE"><b>(</b></font><font color="BLUE"><b>(</b></font>Document<font color="BLUE"><b>)</b></font> e<font color="BLUE"><b>.</b></font>getMatchNode<font color="BLUE"><b>(</b></font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>.</b></font>getDocument<font color="BLUE"><b>(</b></font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>;</b></font>
    builder<font color="BLUE"><b>.</b></font>moveTo<font color="BLUE"><b>(</b></font><font color="BLUE"><b>(</b></font>Run<font color="BLUE"><b>)</b></font> runs<font color="BLUE"><b>.</b></font>get<font color="BLUE"><b>(</b></font>runs<font color="BLUE"><b>.</b></font>size<font color="BLUE"><b>(</b></font><font color="BLUE"><b>)</b></font> <font color="BLUE">-</font> <font color="BROWN">1</font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>;</b></font>
    builder<font color="BLUE"><b>.</b></font>insertImage<font color="BLUE"><b>(</b></font><font color="PURPLE">"D:\\Temp\\Aspose.Words.jpg"</font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>;</b></font>

    <font color="RED"><b>for</b></font> <font color="BLUE"><b>(</b></font>Run run <font color="BLUE">:</font> <font color="BLUE"><b>(</b></font>Iterable<font color="BLUE"><</font>Run<font color="BLUE">></font><font color="BLUE"><b>)</b></font> runs<font color="BLUE"><b>)</b></font>
        run<font color="BLUE"><b>.</b></font>remove<font color="BLUE"><b>(</b></font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>;</b></font>

    <font color="GREEN"><i>// Signal to the replace engine to do nothing because we have already done all what we wanted.

return ReplaceAction.SKIP;
}

<font color="GREEN"><i>/**
    * Splits text of the specified run into two runs.
    * Inserts the new run just after the specified run.
    */</i></font>
<font color="RED"><b>private</b></font> Run splitRun<font color="BLUE"><b>(</b></font>Run run<font color="BLUE"><b>,</b></font> <font color="RED"><b>int</b></font> position<font color="BLUE"><b>)</b></font> <font color="RED"><b>throws</b></font> Exception
<font color="BLUE"><b>{</b></font>
    Run afterRun <font color="BLUE">=</font> <font color="BLUE"><b>(</b></font>Run<font color="BLUE"><b>)</b></font>run<font color="BLUE"><b>.</b></font>deepClone<font color="BLUE"><b>(</b></font>true<font color="BLUE"><b>)</b></font><font color="BLUE"><b>;</b></font>
    afterRun<font color="BLUE"><b>.</b></font>setText<font color="BLUE"><b>(</b></font>run<font color="BLUE"><b>.</b></font>getText<font color="BLUE"><b>(</b></font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>.</b></font>substring<font color="BLUE"><b>(</b></font>position<font color="BLUE"><b>)</b></font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>;</b></font>
    run<font color="BLUE"><b>.</b></font>setText<font color="BLUE"><b>(</b></font>run<font color="BLUE"><b>.</b></font>getText<font color="BLUE"><b>(</b></font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>.</b></font>substring<font color="BLUE"><b>(</b></font><font color="BLUE"><b>(</b></font><font color="BROWN">0</font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>,</b></font> <font color="BLUE"><b>(</b></font><font color="BROWN">0</font><font color="BLUE"><b>)</b></font> <font color="BLUE">+</font> <font color="BLUE"><b>(</b></font>position<font color="BLUE"><b>)</b></font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>;</b></font>
    run<font color="BLUE"><b>.</b></font>getParentNode<font color="BLUE"><b>(</b></font><font color="BLUE"><b>)</b></font><font color="BLUE"><b>.</b></font>insertAfter<font color="BLUE"><b>(</b></font>afterRun<font color="BLUE"><b>,</b></font> run<font color="BLUE"><b>)</b></font><font color="BLUE"><b>;</b></font>
    <font color="RED"><b>return</b></font> afterRun<font color="BLUE"><b>;</b></font>
<font color="BLUE"><b>}</b></font>

}

Hope, this helps.

Best regards,
Thanks so much! the problem is resolved.

I have other question, then of insert the image into document, I can't convert the document to Pdf.

My method is the following:

public void generate(){
File fileTargetFile = new File("/document/doc001.pdf");
int saveFormat = SaveFormat.PDF;
InputStream stream = super.getDoc("/doc005.doc");
Document doc = new Document(stream);
renderDocument(insertImg(doc));
OutputStream finalGeneratedFileOut = new BufferedOutputStream(new FileOutputStream(fileTargetFile));
doc.save(finalGeneratedFileOut, saveFormat);
}
The before problem is resolved.

I have other problem when I deploy my project in mule

Log Error:

********************************************************************************
1. null (java.lang.NullPointerException)
javax.imageio.spi.IIORegistry:-1 (null)
2. null (java.lang.ExceptionInInitializerError)
asposewobfuscated.zzLQ:1300 (null)
3. Component that caused exception is: DefaultJavaComponent{flowBuildDocument.component.1362062272}. Message payload is of type: DMDocument (org.mule.component.ComponentException)
org.mule.component.DefaultComponentLifecycleAdapter:348 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/component/ComponentException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
java.lang.NullPointerException
at javax.imageio.spi.IIORegistry.getDefaultInstance(Unknown Source)
at javax.imageio.ImageIO.(Unknown Source)
at asposewobfuscated.zzLQ.zzWD(Unknown Source)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************
Hi,

Thanks for your inquiry. It seems you're missing a necessary JAR file in the classpath. Aspose.Words for Java depends upon the Java Advanced Imaging (JAI) package from Sun in order to process images. In order to write to different image formats you are expected to have the appropriate image reader and writers installed on your development machine. I suggest you please download and install the JAI codec onto your machine. You can find jai 1.1.3 and jai-imageio 1.1 in the following links:

http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-java-client-419417.html

Please also check the following article:
http://www.aspose.com/docs/display/wordsjava/System+Requirements

Hope, this helps.

Best regards,

Thanks! by response, but I don’t can resolve the issue.


My artifact is deployed on Mule 3.6 and java-7 (JDK 1.7 - win-64bits)

Test:
I opened the jar (aspose-words-15.7.0), then i copy to mule in the directory mule \ lib \ opt the file: asposewobfuscated, but error :

I attached the logs.

But when I run it as a .jar on java 7(JDK 1.7 - win-64bits) , it run Ok.

C:\Program Files\Java\jdk1.7.0_79\bin> java -jar asposeTest001.jar

Thanks for your help.

Hi,


Thanks for your inquiry. Please try commenting/removng Aspose.Words related code and see if the problem goes away on your system configuration. It may be that the paths to input/output documents or license file are not resolving correctly. For example, Aspose.Words will throw exception if it cannot find the license. I suggest you please debug into your code to find the exact cause of this problem on your end.

Best regards,