2017-05-11 18 views
0

docxファイルのXML構造の画像でテキストを置き換える必要があります。 私はそのようなものを試してみた: まず私はXMLでいいテキストを検索し、私は描画オブジェクトを作成した後に画像を置くために、私は引き分けに入れたのか分からない今Docx4jはXMLの画像でテキストを置き換えます

List<Object> list = this.getDocumentPart().getJAXBNodesViaXPath(xpath, false); 
org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory(); 
org.docx4j.wml.P para = factory.createP(); 
org.docx4j.wml.Drawing draw = factory.createDrawing(); 
((R)list.get(0)).getContent().clear(); 
((R)list.get(0)).getContent().add(draw); 
para.getContent().add(((R)list.get(0))); 
try { 
    this.getWordMLPackage().save(new java.io.File("C:\\user\\result.docx")); 
} catch (Docx4JException e) { 
    e.printStackTrace(); 
} 

。私の画像を追加するには、このステップで私はdocxを開くには問題があります。何か案が ?

答えて

1

私は解決策を投稿するので、多分それが誰かを助ける問題を修正します。

まず、描画にインラインを追加して2つの機能が必要になることを知っておく必要があります。 最初にByteArrayで画像を変換します。その後

private static byte[] convertImageToByteArray(File file) throws FileNotFoundException, IOException { 
    InputStream is = new FileInputStream(file); 
    long length = file.length(); 
    if (length > Integer.MAX_VALUE) { 
     System.out.println("Fichier trop volumineux."); 
    } 
    byte[] bytes = new byte[(int)length]; 
    int offset = 0; 
    int numRead = 0; 
    while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { 
     offset += numRead; 
    } 
    if (offset < bytes.length) { 
     System.out.println("Impossible de lire en entier le fichier: " + file.getName()); 
    } 
    is.close(); 
    return bytes; 
} 

あなたはインラインを作成する必要があります。

public Inline createInline(File filePict) throws Exception{ 
    byte[] bytes = convertImageToByteArray(filePict); 
    BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(this.getWordMLPackage(), bytes); 
    int id1 = 1; 
    int id2 = 2; 
    Inline inline = imagePart.createImageInline("Filename hint", filePict.getName(), id1, id2, false); 
    return inline; 
} 

、描画にインラインを追加で:

File fileLogo = new File(this.cusDir+mappings.get("logo")); 
org.docx4j.wml.Drawing draw = factory.createDrawing(); 
((R)list.get(i)).getContent().clear(); 
((R)list.get(i)).getContent().add(draw); 
draw.getAnchorOrInline().add(createInline(fileLogo)); 
関連する問題