试试这个代码,需要添加spire.doc jar依赖
import com.spire.doc.Documentimport com.spire.doc.FileFormat
import com.spire.doc.Section
import com.spire.doc.documents.*
import com.spire.doc.fields.DocPicture
public class InsertImage {
public static void main(String[] args) {
//实例化Document对象
Document doc = new Document()
//加载文档
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\test.docx")
//获取第一个section
Section section = doc.getSections().get(0)
//添加一个段落
Paragraph para = section.addParagraph()
//添加图片到段落
DocPicture picture = para.appendPicture("C:\\Users\\Administrator\\Desktop\\Cartoon.png")
//设置文字环绕方式(居于文字上方)
picture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text)
//指定图片的相对位置
picture.setHorizontalOrigin(HorizontalOrigin.Page)
picture.setHorizontalPosition(250f)
picture.setVerticalOrigin(VerticalOrigin.Top_Margin_Area)
picture.setVerticalPosition(150f)
//设置图片大小
picture.setWidth(80f)
picture.setHeight(80f)
//保存到文档
doc.saveToFile("output/InsertImage.docx", FileFormat.Docx)
}
}
生成的Word:
试试下面的代码,需要添加spire.doc.jar为依赖
import com.spire.doc.Document
import com.spire.doc.FileFormat
import com.spire.doc.Section
import com.spire.doc.documents.Paragraph
import com.spire.doc.fields.DocPicture
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.InputStream
public class AppendImage {
public static void main(String[] args) throws FileNotFoundException {
//创建Document对象
Document doc = new Document()
//加载Word文档
doc.loadFromFile("G:\\360MoveData\\Users\\Administrator\\Desktop\\Test.docx")
//获取最后一节
Section lastSection = doc.getLastSection()
//添加段落
Paragraph paragraph = lastSection.addParagraph()
//添加图片到段落
InputStream inputStream = new FileInputStream(new File("G:\\360MoveData\\Users\\Administrator\\Desktop\\image.jpg"))
DocPicture picture = paragraph.appendPicture(inputStream)
//设置图片高宽
picture.setWidth(120f)
picture.setHeight(120f)
//保存文档
doc.saveToFile("AppendImage.docx", FileFormat.Docx_2013)
}
}
可以用wordapi组件来完成import com.heavenlake.wordapi.Document
public class test {
public test() {
Document doc = null
try {
doc = new Document()
doc.open("e:/test.doc")//打开文件
doc.insert("第一章:嘻嘻哈哈","biaoti")//插入文字
doc.insertAtBookmark("testbookm","第一章:嘻嘻哈哈","标题")
doc.insertAtBookmark("testbookm",
new java.io.File("E:/照片/DSC236.JPG"))//插入图片
}
catch (Exception e) {
e.printStackTrace()
}
finally {
try {
if(doc!=null) doc.close(true)
}
catch (Exception e) {
e.printStackTrace()
}
}
}
public static void main(String[] args) {
test test1 = new test()
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)