Copy & paste without clipboard using API


When processing contents in a document via API you sometimes need to copy & paste contents between documents or duplicate contents of one document.

To do this, you can use the standard copy&paste functionality of the UI. But this has some disatvantages:

  • existing contents of the clipboard are lost
  • parallel usage of copy&paste by the user can cause unexpected results
  • forgotten contents in the clipboard can be a security problem

Because of this it’s preferable to copy&paste by bypassing the clipboard. This is possible using the API as the following example shows.

The implementation

To use copy&paste, you need a XTransferableSupplier that you can get from your document’s controller:

XTextDocument xTextDocument = ... ;
XController xController = document.getCurrentController();
XTransferableSupplier xTransferableSupplier = UnoRuntime.queryInterface(XTransferableSupplier.class, xController);

The next step is to select the content that should be copied using the XSelectionSupplier:

XSelectionSupplier xSelectionSupplier = UnoRuntime.queryInterface(XSelectionSupplier.class, xController);;

The contentToSelect is for example a XTextCursor to copy a part of a text document or a XCellRange to copy contents of a table.

To copy the contents use the getTransferable method of the xTransferableSupplier:

XTransferable transferable = xTransferableSupplier.getTransferable();

The XTransferable contains the copied contents that can be pasted to another part of your document. To do that, move the selection using the xSelectionSupplier and paste using the xSelectionSupplier:;

Short URL for this post:
This entry was posted in Did you know? and tagged , , , , , . Bookmark the permalink.