Page 1 of 1

how to create a image when inserting an excel to docx

PostPosted: Fri Jul 15, 2011 2:26 pm
by tosswang
hi ,all:
i want to insert an excel to docx,i meet a problem , i can't achieve the same effect that there is a dynamically generated image that represents an inserted excel by manually in a docx . the content of dynamically generated image is identical with the content of inserted excel file.

below is my code ,i merely can insert a fixed image,how can i create a dynamically generated image that represents an inserted excel?
Code: Select all
package org;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;

import javax.xml.bind.JAXBContext;

import org.docx4j.openpackaging.contenttype.ContentTypes;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.WordprocessingML.OleObjectBinaryPart;
import org.docx4j.relationships.Relationship;

public class SampleOLE
{
   public static JAXBContext context = org.docx4j.jaxb.Context.jc;

    public static void main(String[] args) throws Exception
    {
       String outputfilepath = "c:\\workspace\\test_OLE.docx";   

       // 1. Load the Package
       WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();     
       wordMLPackage.getContentTypeManager().addDefaultContentType("bin", ContentTypes.OFFICEDOCUMENT_OLE_OBJECT);

       
       // 2. creating Image Part
       File file = new File("c:\\workspace\\image1.jpg" );//也可以是image1.emf
       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());
       }
       System.out.println(bytes.length);
       is.close();
       BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);     
       Relationship relImageObject = wordMLPackage.getMainDocumentPart().addTargetPart(imagePart);
           
       // 3. creating OLE part
       Part olePart = new OleObjectBinaryPart();
       FileInputStream oleFile = new FileInputStream("c:\\workspace\\Book1.xls");
       ((BinaryPart)olePart).setBinaryData(oleFile);
       ((OleObjectBinaryPart)olePart).initPOIFSFileSystem();
       ((OleObjectBinaryPart)olePart).writePOIFSFileSystem();
       ((OleObjectBinaryPart)olePart).viewFile(true);
       Relationship relOleObject = wordMLPackage.getMainDocumentPart().addTargetPart(olePart);
       

       // 3. contains $OLEObjectRid     
       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: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());
       mappings.put("OLEObjectRid", relOleObject.getId());
       //XmlUtils.unmarshall*()方法用于将xml转为object对象,参见TblFactory.java
       wordMLPackage.getMainDocumentPart().addObject(org.docx4j.XmlUtils.unmarshallFromTemplate(ml, mappings));

       
       // 4. Save it     
       wordMLPackage.save(new java.io.File(outputfilepath));
       System.out.println( "Saved output to:" + outputfilepath );
    }
}

Re: how to create a image when inserting an excel to docx

PostPosted: Mon Jul 18, 2011 1:25 pm
by tosswang
who can help me ?

thanks in advance!

tosswang

Re: how to create a image when inserting an excel to docx

PostPosted: Tue Jul 19, 2011 8:45 pm
by tinne
Hello tosswang,

Your task is kind of special. I tried to read the code diagonally and had to admit that my Japanese is a bit, ahem, unavailable.

Let me suggest you create a very simple document with an embedded spreadsheet by hand and then try to understand the structure, posting questions about the nasty details that the specification does not explain. Finally, this should lead you to a way to automate the task.

Re: how to create a image when inserting an excel to docx

PostPosted: Wed Jul 20, 2011 1:40 pm
by tosswang
hi,tinne:

thanks your rely ,i understand the structure of a document with an embedded spreadsheet now, an embedded picture present an excel spreadsheet,but i don't know how create a dynamical image that can present an excel which is inserted into a word document :oops:

by the way,i am chinese :) ,my enlish level is poor……

tosswang

Re: how to create a image when inserting an excel to docx

PostPosted: Thu Jul 21, 2011 6:28 am
by tinne
Sorry for mixing up Chinese with Japanese; this shall not happen again. Might be as my German is better than any other language either way.

The answer stays the same:
  • Try creating a static sample document for your task at hand.
  • Examine the structure by unpacking and reading it. If you do not understand it, post the document and your questions.

This is what translate.google com made from my answer. No guarantee it makes any sense at all:

对不起,混合了中国与日本,这不应当再次发生。可能是我的德国是比任何其他语言的任何一种方式更好。
答案保持不变:
  • 尝试创建一个静态示例文档,你手头的任务。
  • 检查拆包和阅读结构。如果你不理解,后的文件和您的问题。

Re: how to create a image when inserting an excel to docx

PostPosted: Thu Jul 21, 2011 9:51 am
by jason
You are able to embed the spreadsheet OK, right?

The user can click on it to open it, right?

Your only problem is that what they click on is not an image of the contents of the spreadsheet, but some generic embedded spreadsheet icon.

How do you create the image?

I assume you want to do that dynamically on-the-fly (because creating it ahead of time is easy: take a screenshot, or extract it from an existing embedding done in Word).

Creating it dynamically will be harder. If you wanted to do it using xlsx4j, you'll need to write the code to render a worksheet as an image. First you'll need to devise your strategy:
- use XSL FO
- convert it to HTML, and make an image of that
- go straight to jpeg or png or whatever
- DrawingML?
You can probably research that by googling "spreadsheet to image" etc. Have a look at POI to see whether/how it prints/outputs xlsx.

Then as Tinne said, its a matter of understanding the xlsx format and making a start.

Keep us updated..

Re: how to create a image when inserting an excel to docx

PostPosted: Thu Jul 21, 2011 3:03 pm
by tosswang
hi,all
at first, thanks tinne and jason,below is our solution, i use poi and itext
the attachment's function is xls->pdf->image
please view Main.java


i insert the image into documnet
Code: Select all
   package org;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;

import javax.xml.bind.JAXBContext;

import org.docx4j.openpackaging.contenttype.ContentTypes;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.WordprocessingML.OleObjectBinaryPart;
import org.docx4j.relationships.Relationship;

public class SampleOLE
{
   public static JAXBContext context = org.docx4j.jaxb.Context.jc;

    public static void main(String[] args) throws Exception
    {
       String outputfilepath = "c:\\workspace\\test_OLE.docx";   

       // 1. Load the Package
       WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();     
       wordMLPackage.getContentTypeManager().addDefaultContentType("bin", ContentTypes.OFFICEDOCUMENT_OLE_OBJECT);

       
       // 2. creating Image Part
       File file = new File("c:\\workspace\\test.png" );//
       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());
       }
       System.out.println(bytes.length);
       is.close();
       BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);     
       Relationship relImageObject = wordMLPackage.getMainDocumentPart().addTargetPart(imagePart);
           
       // 3. creating OLE part
       Part olePart = new OleObjectBinaryPart();
       FileInputStream oleFile = new FileInputStream("c:\\workspace\\Book1.xls");
       ((BinaryPart)olePart).setBinaryData(oleFile);
       ((OleObjectBinaryPart)olePart).initPOIFSFileSystem();
       ((OleObjectBinaryPart)olePart).writePOIFSFileSystem();
       ((OleObjectBinaryPart)olePart).viewFile(true);
       Relationship relOleObject = wordMLPackage.getMainDocumentPart().addTargetPart(olePart);
       

       // 3. contains $OLEObjectRid     
       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: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());
       mappings.put("OLEObjectRid", relOleObject.getId());
       //XmlUtils.unmarshall*()方法用于将xml转为object对象,参见TblFactory.java
       wordMLPackage.getMainDocumentPart().addObject(org.docx4j.XmlUtils.unmarshallFromTemplate(ml, mappings));

       
       // 4. Save it     
       wordMLPackage.save(new java.io.File(outputfilepath));
       System.out.println( "Saved output to:" + outputfilepath );
    }
}
   


jars of attachment are more large ,i can't upload

thanks again!

tosswang