作者:DomincLiu | 来源:互联网 | 2023-01-06 09:35
1> Axel Richter..:
尽管您已经找到了适合使用的类-CTAnchor和后继者-但也需要考虑锚的XML Schema定义。这表明,除了定义包装的职责元素以外,还需要更多的职责元素。因此,按类使用 org.openxmlformats.schemas.drawingml.x2006
您可能正在编写页面明智代码。对于此类问题,我的首选解决方案是XML
通过一些变量来更新所有需要的元素。这XML
然后可以分析来得到所需的对象。
例:
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.util.Units;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
public class WordInsertPictures {
private static CTAnchor getAnchorWithGraphic(CTGraphicalObject graphicalobject,
String drawingDescr, int width, int height,
int left, int top) throws Exception {
String anchorXML =
""
+""
+""+left+""
+""+top+""
+""
+""
+""
+""
+""
+"" //Square polygon 21600 x 21600 leads to wrap points in fully width x height
+""// Why? I don't know. Try & error ;-).
+""
+""
+""
+""
+""
+"";
CTDrawing drawing = CTDrawing.Factory.parse(anchorXML);
CTAnchor anchor = drawing.getAnchorArray(0);
anchor.setGraphic(graphicalobject);
return anchor;
}
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The picture in line: ");
InputStream in = new FileInputStream("samplePict.jpeg");
run.addPicture(in, Document.PICTURE_TYPE_JPEG, "samplePict.jpeg", Units.toEMU(100), Units.toEMU(30));
in.close();
run.setText(" text after the picture.");
paragraph = document.createParagraph();
run = paragraph.createRun();
in = new FileInputStream("samplePict.jpeg");
run.addPicture(in, Document.PICTURE_TYPE_JPEG, "samplePict.jpeg", Units.toEMU(100), Units.toEMU(30));
in.close();
CTDrawing drawing = run.getCTR().getDrawingArray(0);
CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "samplePict.jpeg",
Units.toEMU(100), Units.toEMU(30),
Units.toEMU(30), Units.toEMU(0));
drawing.setAnchorArray(new CTAnchor[]{anchor});
drawing.removeInline(0);
run = paragraph.createRun();
run.setText("The previous picture is anchored wrapTight. The previous picture is anchored wrapTight. The previous picture is anchored wrapTight. The previous picture is anchored wrapTight. The previous picture is anchored wrapTight. The previous picture is anchored wrapTight.");
document.write(new FileOutputStream("WordInsertPictures.docx"));
document.close();
}
}