package cn.flightfeather.supervision.docx4j.demo
|
|
import org.docx4j.dml.wordprocessingDrawing.Inline
|
import org.docx4j.openpackaging.packages.WordprocessingMLPackage
|
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage
|
import org.docx4j.wml.ObjectFactory
|
import org.docx4j.wml.P
|
import org.docx4j.wml.Tr
|
import java.io.File
|
import java.io.FileInputStream
|
|
|
class AddImage01
|
|
private val mlPackage = WordprocessingMLPackage.createPackage()
|
|
fun main(args: Array<String>) {
|
|
val wordMLPackage = mlPackage
|
// factory = Context.getWmlObjectFactory()
|
|
val table = factory.createTbl()
|
addBorders(table)
|
|
val tr = factory.createTr()
|
|
val file1 = File( "/Users/liwei/resource/supervision/src/main/resources/static/images/tutu.png")
|
val paragraphWithImage1 = addInlineImageToParagraph(createInlineImage(file1))
|
addTableCell(tr, paragraphWithImage1)
|
|
val file = File( "/Users/liwei/resource/supervision/src/main/resources/static/images/tutu2.png")
|
val paragraphWithImage = addInlineImageToParagraph(createInlineImage(file))
|
addTableCell(tr, paragraphWithImage)
|
|
table.content.add(tr)
|
|
wordMLPackage.mainDocumentPart.addObject(table)
|
val outputfilepath = File("/Users/liwei/resource/supervision/src/main/resources/public/htmltable002.docx")
|
wordMLPackage.save(outputfilepath)
|
}
|
|
@Throws(Exception::class)
|
private fun createInlineImage(file: File): Inline {
|
val bytes = convertImageToByteArray(file)
|
|
val imagePart = BinaryPartAbstractImage.createImagePart(mlPackage, bytes)
|
|
val docPrId = 1
|
val cNvPrId = 2
|
|
return imagePart.createImageInline("Filename hint", "Alternative text", docPrId, cNvPrId, false)
|
}
|
|
|
private fun addInlineImageToParagraph(inline: Inline): P {
|
// 添加内联对象到一个段落中
|
val factory = ObjectFactory()
|
val paragraph = factory.createP()
|
val run = factory.createR()
|
paragraph.getContent().add(run)
|
val drawing = factory.createDrawing()
|
run.content.add(drawing)
|
drawing.anchorOrInline.add(inline)
|
return paragraph
|
}
|
|
private fun addTableCell(tr: Tr, paragraph: P) {
|
val tc1 = factory.createTc()
|
tc1.content.add(paragraph)
|
tr.content.add(tc1)
|
}
|
|
fun convertImageToByteArray(file: File): ByteArray {
|
val input = FileInputStream(file)
|
val length = file.length()
|
// 不能使用long类型创建数组, 需要用int类型.
|
if (length > Integer.MAX_VALUE) {
|
System.out.println("File too large!!");
|
}
|
val bytes = ByteArray(length.toInt())
|
var offset = 0
|
var numRead = 0
|
//numRead = input.read(bytes, offset, bytes.size - offset)
|
while (offset < bytes.size && numRead >= 0) {
|
numRead = input.read(bytes, offset, bytes.size - offset)
|
offset += numRead
|
}
|
// 确认所有的字节都没读取
|
if (offset < bytes.size) {
|
System.out.println("Could not completely read file " + file.name);
|
}
|
println("offset:$offset bytes:${bytes.size}")
|
input.close()
|
return bytes
|
}
|