【问题标题】:I'm trying to add image to new word doc with docx4j我正在尝试使用 docx4j 将图像添加到新单词文档
【发布时间】:2014-02-19 07:10:23
【问题描述】:

我正在尝试使用 docx4j 将图像添加到新的 word 文档。我从网上获取了这段代码并为我的程序修改了它,但是我收到一个奇怪的错误,我不确定是什么导致它或如何调试它......

这是我的代码

private static void test()
{
    WordprocessingMLPackage wordMLPackage = null;
    try {
        wordMLPackage = WordprocessingMLPackage.createPackage();
    } catch (InvalidFormatException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        javax.swing.JOptionPane.showMessageDialog(panel, "Cannnot create package.");
    }
    wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Title", "Hello Word! \n\t" + "Try This!");

    byte[] bytes = null;
    try {
        bytes = convertImageToByteArray();
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        javax.swing.JOptionPane.showMessageDialog(panel, "Image file not found.");
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        javax.swing.JOptionPane.showMessageDialog(panel, "Image file exception: " + e1.toString());
    }
    try {
        addImageToPackage(wordMLPackage, bytes);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        javax.swing.JOptionPane.showMessageDialog(panel, "Cannot add image to package: " + e.toString());
    }

    try {
        wordMLPackage.save(new java.io.File("HelloWord7.docx"));
    } catch (Docx4JException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        javax.swing.JOptionPane.showMessageDialog(panel, "Cannot save image to file.");
    }
}

private static void addImageToPackage(WordprocessingMLPackage wordMLPackage,
        byte[] bytes) throws Exception {
    BinaryPartAbstractImage imagePart =
            BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);

    int docPrId = 1;
    int cNvPrId = 2;
    Inline inline = imagePart.createImageInline("Filename hint",
            "Alternative text", docPrId, cNvPrId, false);

    P paragraph = addInlineImageToParagraph(inline);
    wordMLPackage.getMainDocumentPart().addObject(paragraph);
}

private static P addInlineImageToParagraph(Inline inline) {
    // Now add the in-line image to a paragraph
    ObjectFactory factory = new ObjectFactory();
    P paragraph = factory.createP();
    R run = factory.createR();
    paragraph.getContent().add(run);
    Drawing drawing = (Drawing) factory.createDrawing();
    run.getContent().add(drawing);
    ((org.docx4j.wml.Drawing) drawing).getAnchorOrInline().add(inline);
    return paragraph;
}


private static byte[] convertImageToByteArray() throws IOException {
    // get DataBufferBytes from Raster
    WritableRaster raster = logo.getRaster();
    DataBufferByte data = (DataBufferByte)raster.getDataBuffer();

    return (data.getData());
}

我收到以下错误

BinaryPartAbstractImage imagePart =
            BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);

返回的错误是:Docx4JException:检查图像格式时出错。

这是“徽标”的加载方式,

try {
        BufferedImage logo = ImageIO.read(getClass().getResourceAsStream("/logo.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        javax.swing.JOptionPane.showMessageDialog(panel, "Cannot load logo for word doc");
    }

感谢任何帮助,谢谢

新信息


我正在将应用程序作为可运行的 jar 运行,并且对于各种图像类型(例如:png、jpg)收到与上述相同的错误。我尝试通过从 main() 调用 test() 在 eclipse 中运行应用程序,但应用程序卡住了,为什么?如何调试?

我稍微修改了代码,我将文件传递给 createImagePart 而不是 byte[] 数组。

public static P newImage(WordprocessingMLPackage wordMLPackage, File file, 
        String filenameHint, String altText, int id1, int id2) throws Exception {
    BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, file);
    //.createImagePart(wordMLPackage, bytes);
    javax.swing.JOptionPane.showMessageDialog(panel, "Created image part");
    Inline inline = imagePart.createImageInline(filenameHint, altText, id1, id2, false);

    ObjectFactory factory = new ObjectFactory();

    P  p = factory.createP();
    R  run = factory.createR();

    p.getContent().add(run);        
    Drawing drawing = (Drawing) factory.createDrawing();      
    run.getContent().add(drawing);       
    ((org.docx4j.wml.Drawing) drawing).getAnchorOrInline().add(inline);

    return p;
}

private static void test() throws Exception
{
    File file = new File("logo.png" );
    if (!file.canRead())
        javax.swing.JOptionPane.showMessageDialog(panel, "Cannot read file");
    if (!file.exists())
        javax.swing.JOptionPane.showMessageDialog(panel, "File does not exist");
    javax.swing.JOptionPane.showMessageDialog(panel, file.getAbsolutePath());

    String filenameHint = null;
    String altText = null;

    int id1 = 0;
    int id2 = 1;

    P p = newImage(wordMLPackage, file, filenameHint, altText, id1, id2);

    wordMLPackage.getMainDocumentPart().addObject(p);
    wordMLPackage.save(new File("Example.docx"));
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                wordMLPackage = WordprocessingMLPackage.createPackage();
            } catch (InvalidFormatException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
                javax.swing.JOptionPane.showMessageDialog(panel, "Could not create wordMLPackage: " + e2.toString());
            }
            new Calculator().setVisible(true);
        }
    });
}

【问题讨论】:

    标签: java image docx4j


    【解决方案1】:

    这里是一个简单的例子,你可以以此为基础。

    import java.io.*;
    
    import org.docx4j.dml.wordprocessingDrawing.Inline;
    import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
    import org.docx4j.wml.*;
    import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
    
    public class Example {
        public static void main(String[] args) throws Exception {
            WordprocessingMLPackage wordprocessingMLPackage = WordprocessingMLPackage.createPackage();
            File file = new File("C://java-duke-logo.jpg" );
    
            InputStream inputStream = new java.io.FileInputStream(file );
            long fileLength = file.length();    
    
            byte[] bytes = new byte[(int)fileLength];
    
            int offset = 0;
            int numRead = 0;
    
            while(offset < bytes.length
                   && (numRead = inputStream.read(bytes, offset, bytes.length-offset)) >= 0) {
                offset += numRead;
            }
    
            inputStream.close();
    
            String filenameHint = null;
            String altText = null;
    
            int id1 = 0;
            int id2 = 1;
    
            P p = newImage(wordprocessingMLPackage, bytes, filenameHint, altText, id1, id2);
    
            wordprocessingMLPackage.getMainDocumentPart().addObject(p);
            wordprocessingMLPackage.save(new File("C://Example.docx"));
        }
    
        public static P newImage( WordprocessingMLPackage wordMLPackage, byte[] bytes, 
                String filenameHint, String altText, int id1, int id2) throws Exception {
            BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);
            Inline inline = imagePart.createImageInline( filenameHint, altText, id1, id2);
    
            ObjectFactory factory = new ObjectFactory();
    
            P  p = factory.createP();
            R  run = factory.createR();
    
            p.getParagraphContent().add(run);        
            Drawing drawing = factory.createDrawing();      
            run.getRunContent().add(drawing);       
            drawing.getAnchorOrInline().add(inline);
    
            return p;
        }   
    }
    

    Example.docx:

    【讨论】:

    • 感谢您的回复...我收到同样的错误:Docx4JException: Error checks image format 此错误从 BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);
    • 我已经尝试过 png、jpg 图像......但仍然是同样的错误。我修改了代码,请看原帖。您对我如何尝试调试问题有任何想法吗?
    • 这应该可行,但我认为改用样式更改模板会容易得多。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-10-03
    • 2016-08-21
    • 2014-06-13
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 2011-02-13
    相关资源
    最近更新 更多