Hello I want insert image to word document. Below code inserts the image in its original size:
private def writePhotosToDoc(model: WordReportModel, doc: XWPFDocument): Unit = {
val paragraphIndex = detectVariable(Variables.PHOTO_APPLICATION, doc)
if (!paragraphIndex.exists(_ == ("idx", -1))) {
val taskParagraph = doc.getParagraphs.asScala(
paragraphIndex("idx")
)
taskParagraph.removeRun(
paragraphIndex("irx")
)
model.attachments.foreach{
case(key, value) =>
val p = doc.createParagraph()
p.getCTP.setPPr(taskParagraph.getCTP.getPPr)
p.setAlignment(ParagraphAlignment.CENTER)
val r = p.createRun()
r.addBreak()
val bi = ImageIO.read(value.head)
val width = bi.getWidth
val height = bi.getHeight
r.addPicture(
new FileInputStream(value.head),
Document.PICTURE_TYPE_PNG,
value.head.getName,
Units.toEMU(width),
Units.toEMU(height)
)
}
}
}
How to insert image and set scale.
I saw this thread and tried to insert with different sizes and it seems to be working fine.
This is where the execution starts. Note that you have to first create a plain docx file and then edit and add the image (otherwise the file is not created properly):
And this is the CustomXWPFDocument class (taken from the question):