E ae galera do mal,
estou procurando uma forma de inserir imagem em um documento word utilizando a biblioteca POI
Porem não estou tendo sucesso.
Alguém já passou por isso?
E ae galera do mal,
estou procurando uma forma de inserir imagem em um documento word utilizando a biblioteca POI
Porem não estou tendo sucesso.
Alguém já passou por isso?
Boa tarde,
Se alguém tiver essa solução em docx4j ou outra biblioteca também é bem vindo.
Obrigado!
E ae galera, ainda não desisti!
só quero inserir uma imagem dentro de um documento, só isso!
kkkkkkkkkkkkkkkkkkkkkkkk
Valeu galera!
Consegui com a biblioteca docx4j
segue o código abaixo:
funciona direitinho (obs: deve inserir todas as bibliotecas do zip)
a String imagem é o caminho da imagem a ser inserida
public void inserirImagem(WordprocessingMLPackage doc, String imagem) {
try {
File file = new File(imagem);
java.io.InputStream is = new java.io.FileInputStream(file);
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File too large!!");
}
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;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
System.out.println("Could not completely read file "
+ file.getName());
}
is.close();
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage
.createImagePart(doc, bytes);
Relationship relImageObject = doc.getMainDocumentPart()
.addTargetPart(imagePart);
String ml = "<w:p w:rsidR=\"001563A4\" w:rsidRDefault=\"007223E2\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" "
+ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" "
+ "xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
+ "xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\">"
+ "<w:r>"
+ "<w:object w:dxaOrig=\"1543\" w:dyaOrig=\"993\">"
+ "<v:shapetype id=\"_x0000_t75\" coordsize=\"21600,21600\" o:spt=\"75\" o:preferrelative=\"t\" path=\"m@4@5l@4@11@9@11@9@5xe\" filled=\"f\" stroked=\"f\">"
+ "<v:stroke joinstyle=\"miter\"/><v:formulas><v:f eqn=\"if lineDrawn pixelLineWidth 0\"/>"
+ "<v:f eqn=\"sum @0 1 0\"/><v:f eqn=\"sum 0 0 @1\"/>"
+ "<v:f eqn=\"prod @2 1 2\"/>"
+ "<v:f eqn=\"prod @3 21600 pixelWidth\"/>"
+ "<v:f eqn=\"prod @3 21600 pixelHeight\"/>"
+ "<v:f eqn=\"sum @0 0 1\"/>"
+ "<v:f eqn=\"prod @6 1 2\"/>"
+ "<v:f eqn=\"prod @7 21600 pixelWidth\"/>"
+ "<v:f eqn=\"sum @8 21600 0\"/>"
+ "<v:f eqn=\"prod @7 21600 pixelHeight\"/>"
+ "<v:f eqn=\"sum @10 21600 0\"/>"
+ "</v:formulas>"
+ "<v:path o:extrusionok=\"f\" gradientshapeok=\"t\" o:connecttype=\"rect\"/>"
+ "<o:lock v:ext=\"edit\" aspectratio=\"t\"/>"
+ "</v:shapetype>"
+
// "<v:shape id=\"_x0000_i1025\" type=\"#_x0000_t75\" style=\"width:"+imagePart.getImageInfo().getSize().getWidthPx()+"pt;height:"+imagePart.getImageInfo().getSize().getHeightPx()+"pt\" o:ole=\"\">"
// +
"<v:shape id=\"_x0000_i1025\" type=\"#_x0000_t75\" style=\"width:500pt;height:500pt\" o:ole=\"\">"
+ "<v:imagedata r:id=\"${ImageObjectRid}\" o:title=\"\"/>"
+ "</v:shape>"
+ "<o:OLEObject Type=\"Embed\" ProgID=\"Excel.Sheet.12\" ShapeID=\"_x0000_i1025\" DrawAspect=\"Content\" ObjectID=\"_1355911853\" r:id=\"${OLEObjectRid}\"/>"
+ "</w:object>" + "</w:r>" + "</w:p>";
HashMap<String, String> mappings = new HashMap<String, String>();
mappings.put("ImageObjectRid", relImageObject.getId());
doc.getMainDocumentPart().addObject(
org.docx4j.XmlUtils.unmarshallFromTemplate(ml, mappings));
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (Docx4JException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Falou galera, um abraço!
Parabéns. Depois de quase 1 ano, fazendo jus a frase do teu rodapé
Valeu!
Ola amigos, em relação Cl?ber Jos, estou tentando fazer a mesma coisa, mas infelizmente não esta dando certo da um erro nessa linha :
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(doc, bytes);
e não inseri a imagem, poderia me ajudar ?
Cara, vc colocou todas as bibliotecas?
mesmo não apresentando erros no código, todas as bibliotecas devem estar apontadas
valeu!
Sim, fiz assim:
public class testex {
public static void main(String[] args) throws Docx4JException{
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(“c:/a/rtf_word.docx”));
inserirImagem XX = new inserirImagem();
XX.inserirImagem(wordMLPackage, “c:/a/1.jpg”);
}
}
e usando a classe que vc criou, mas infelizmente não deu certo, coloca texto e normal só imagem que e complicado , se tiver mais uma dica aceito com carinho.
Amanhã eu vejo direitinho,
caso necessário eu passo a relação de bibliotecas para vc.
falou, um abraço!
Oi , poderia postar a lista de import que vc usou ?
Opa, desculpe a demora
estou meio enrolado esses dias
Eu baixei as bibliotecas do docx4j com suas dependências no seguinte link:
http://www.docx4java.org/docx4j/docx4j-2.8.0.zip
Segue uma classe com esse exemplo funcionando:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import javax.xml.bind.JAXBException;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.exceptions.InvalidFormatException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.relationships.Relationship;
public class Word {
public static void main(String[] args) throws Docx4JException{
Word word= new Word();
WordprocessingMLPackage doc= WordprocessingMLPackage.load(new File("e:\\Teste.docx"));
word.inserirImagem(doc, "e:\\imagem.jpg");
doc.save(new File("e:\\Teste2.docx"));
}
public void inserirImagem(WordprocessingMLPackage doc, String imagem) {
try {
File file = new File(imagem);
java.io.InputStream is = new java.io.FileInputStream(file);
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File too large!!");
}
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;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
System.out.println("Could not completely read file "
+ file.getName());
}
is.close();
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage
.createImagePart(doc, bytes);
Relationship relImageObject = doc.getMainDocumentPart()
.addTargetPart(imagePart);
String ml = "<w:p w:rsidR=\"001563A4\" w:rsidRDefault=\"007223E2\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" "
+ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" "
+ "xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
+ "xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\">"
+ "<w:r>"
+ "<w:object w:dxaOrig=\"1543\" w:dyaOrig=\"993\">"
+ "<v:shapetype id=\"_x0000_t75\" coordsize=\"21600,21600\" o:spt=\"75\" o:preferrelative=\"t\" path=\"m@4@5l@4@11@9@11@9@5xe\" filled=\"f\" stroked=\"f\">"
+ "<v:stroke joinstyle=\"miter\"/><v:formulas><v:f eqn=\"if lineDrawn pixelLineWidth 0\"/>"
+ "<v:f eqn=\"sum @0 1 0\"/><v:f eqn=\"sum 0 0 @1\"/>"
+ "<v:f eqn=\"prod @2 1 2\"/>"
+ "<v:f eqn=\"prod @3 21600 pixelWidth\"/>"
+ "<v:f eqn=\"prod @3 21600 pixelHeight\"/>"
+ "<v:f eqn=\"sum @0 0 1\"/>"
+ "<v:f eqn=\"prod @6 1 2\"/>"
+ "<v:f eqn=\"prod @7 21600 pixelWidth\"/>"
+ "<v:f eqn=\"sum @8 21600 0\"/>"
+ "<v:f eqn=\"prod @7 21600 pixelHeight\"/>"
+ "<v:f eqn=\"sum @10 21600 0\"/>"
+ "</v:formulas>"
+ "<v:path o:extrusionok=\"f\" gradientshapeok=\"t\" o:connecttype=\"rect\"/>"
+ "<o:lock v:ext=\"edit\" aspectratio=\"t\"/>"
+ "</v:shapetype>"
+
// "<v:shape id=\"_x0000_i1025\" type=\"#_x0000_t75\" style=\"width:"+imagePart.getImageInfo().getSize().getWidthPx()+"pt;height:"+imagePart.getImageInfo().getSize().getHeightPx()+"pt\" o:ole=\"\">"
// +
"<v:shape id=\"_x0000_i1025\" type=\"#_x0000_t75\" style=\"width:500pt;height:320pt\" o:ole=\"\">"
+ "<v:imagedata r:id=\"${ImageObjectRid}\" o:title=\"\"/>"
+ "</v:shape>"
+ "<o:OLEObject Type=\"Embed\" ProgID=\"Excel.Sheet.12\" ShapeID=\"_x0000_i1025\" DrawAspect=\"Content\" ObjectID=\"_1355911853\" r:id=\"${OLEObjectRid}\"/>"
+ "</w:object>" + "</w:r>" + "</w:p>";
HashMap<String, String> mappings = new HashMap<String, String>();
mappings.put("ImageObjectRid", relImageObject.getId());
doc.getMainDocumentPart().addObject(
org.docx4j.XmlUtils.unmarshallFromTemplate(ml, mappings));
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (Docx4JException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Observação: É apresentado uma mensagem de erro durante a abertura do documento gerado, não tive tempo de ver isso ainda, pois estou em outro projeto
caso alguém consiga resolver esse problema, poste ai para nós!
Mesmo com a mensagem, o documento mantém a formatação e as imagens são inseridas, é só abrir o mesmo e salvar que dá tudo certo
Um abraço!
String ml = "<w:p w:rsidR=\"001563A4\" w:rsidRDefault=\"007223E2\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" "
+ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" "
+ "xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
+ "xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\">"
+ "<w:r>"
+ "<w:object w:dxaOrig=\"1543\" w:dyaOrig=\"993\">"
+ "<v:shapetype id=\"_x0000_t75\" coordsize=\"21600,21600\" o:spt=\"75\" o:preferrelative=\"t\" path=\"m@4@5l@4@11@9@11@9@5xe\" filled=\"f\" stroked=\"f\">"
+ "<v:stroke joinstyle=\"miter\"/><v:formulas><v:f eqn=\"if lineDrawn pixelLineWidth 0\"/>"
+ "<v:f eqn=\"sum @0 1 0\"/><v:f eqn=\"sum 0 0 @1\"/>"
+ "<v:f eqn=\"prod @2 1 2\"/>"
+ "<v:f eqn=\"prod @3 21600 pixelWidth\"/>"
+ "<v:f eqn=\"prod @3 21600 pixelHeight\"/>"
+ "<v:f eqn=\"sum @0 0 1\"/>"
+ "<v:f eqn=\"prod @6 1 2\"/>"
+ "<v:f eqn=\"prod @7 21600 pixelWidth\"/>"
+ "<v:f eqn=\"sum @8 21600 0\"/>"
+ "<v:f eqn=\"prod @7 21600 pixelHeight\"/>"
+ "<v:f eqn=\"sum @10 21600 0\"/>"
+ "</v:formulas>"
+ "<v:path o:extrusionok=\"f\" gradientshapeok=\"t\" o:connecttype=\"rect\"/>"
+ "<o:lock v:ext=\"edit\" aspectratio=\"t\"/>"
+ "</v:shapetype>"
+ "<v:shape id=\"_x0000_i1025\" type=\"#_x0000_t75\" style=\"width:50pt;height:50pt\" o:ole=\"\">"
+ "<v:imagedata r:id=\"${ImageObjectRid}\" o:title=\"\"/>"
+ "</v:shape>"
+ "<o:OLEObject Type=\"Embed\" ProgID=\"Excel.Sheet.12\" ShapeID=\"_x0000_i1025\" DrawAspect=\"Content\" ObjectID=\"_1355911853\" r:id=\"${OLEObjectRid}\"/>"
+ "</w:object>" + "</w:r>" + "</w:p>";
Opa, bão demais da conta
Valeu!