0

rtf ドキュメントに画像を追加しようとしています。ドキュメントに画像を追加できますが、画像を追加できません。これは、2 番目の画像が追加されると、最初の画像が削除されることを意味します。コードが実行されるたびに、新しい rtf ドキュメントが作成されると思います。

public class InsertToWord {

    com.lowagie.text.Document doc = null;
    FileOutputStream evidenceDocument;
    String fileName = "evidenceDocument.rtf";
    settings obj = null;

    InsertToWord() {
        obj = new settings();
        doc = new com.lowagie.text.Document();

    }

    public void insertImage(File saveLocation) {

        try {
            evidenceDocument = new FileOutputStream(obj.getFileLocation() + fileName);
            RtfWriter2.getInstance(doc, evidenceDocument);
            doc.open();
            com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(saveLocation.toString());
            image.scaleAbsolute(400, 300);
            doc.add(image);
            doc.close();
        } catch (Exception e) {
        }
    }
}
4

2 に答える 2

1

insertImage() メソッドでは、実際に新しいファイルを作成し、古いファイルを上書きしています。

この行は新しいファイルを作成しています:

evidenceDocument = new FileOutputStream(obj.getFileLocation()+fileName);

FileOutputStream をパラメーターとしてメソッドに渡してから、行をまとめて削除できます。

public void insertImage( FileOutputStream evidenceDocument , File saveLocation )
于 2012-05-05T06:04:55.580 に答える
0

このコードは、画像をRTF形式に追加するために使用しているコードであり、正常に機能します。

public void actionPerformed(ActionEvent arg0) {

        JFileChooser fileChooser = new JFileChooser();
        int option = fileChooser.showOpenDialog(null);
        File file = fileChooser.getSelectedFile();

        if (option == JFileChooser.APPROVE_OPTION) {

            try {

                BufferedImage image = ImageIO.read(file);
                image = Scalr.resize(image, 200);
                document = (StyledDocument) textPane.getDocument();
                javax.swing.text.Style style = document.addStyle("StyleName", null);
                StyleConstants.setIcon(style, new ImageIcon(image));
                document.insertString(document.getLength(), "ignored text", style);


            }

            catch (Exception e) {
                e.printStackTrace();
            }

        }

        if (option == JFileChooser.CANCEL_OPTION) {

            fileChooser.setVisible(false);

        }

    }// End of Method

textPane変数はJTextPaneです。

于 2013-03-12T09:05:16.040 に答える