Как уже было сказано, интерфейс text::XTextDocument не имеет сервиса "com.sun.star.chart2.DiagramProvider". Если вы хотите добавить диаграмму в текстовый документ, то это можно сделать с помощью одного из следующих методов:
-
Вставить диаграмму в качестве OLE-объекта.
-
Создать изображение диаграммы и вставить его в качестве изображения.
Вариант 1: Вставить диаграмму в качестве OLE-объекта
Для этого нужно создать документ для работы с диаграммами, например, spreadsheet::XSpreadsheetDocument или drawing::XDrawPage. Затем создать и настроить диаграмму, скопировать ее в буфер обмена и вставить как OLE-объект в текстовый документ.
Пример кода:
// create new document for chart
Reference<XComponentContext> xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
Reference<XComponent> xSpreadsheetDoc = (Reference<XComponent>) UnoRuntime.queryInterface(XComponent.class, xContext.getServiceManager().createInstanceWithContext("com.sun.star.sheet.SpreadsheetDocument", xContext));
Reference<XSpreadsheetDocument> xNewSpreadsheetDoc = (Reference<XSpreadsheetDocument>) UnoRuntime.queryInterface(XSpreadsheetDocument.class, xSpreadsheetDoc);
// create chart
Reference<XSpreadsheet> xSheet = xNewSpreadsheetDoc.getSheets().getByIndex(0);
Reference<XCellRangeAddressable> xRange = (Reference<XCellRangeAddressable>) UnoRuntime.queryInterface(XCellRangeAddressable.class, xSheet.getCellRangeByName("A1:C4"));
Reference<XChartDocument> xChartDoc = (Reference<XChartDocument>) UnoRuntime.queryInterface(XChartDocument.class, xContext.getServiceManager().createInstanceWithContext("com.sun.star.chart2.ChartDocument", xContext));
Reference<XDiagram> xDiagram = xChartDoc.createDiagram(ChartType.COLUMN, xRange.getCellRangeAddress(), new ChartData());
Reference<XChart> xChart = UnoRuntime.queryInterface(XChart.class, xDiagram);
xChart.setTitle("My Column Chart");
// copy chart to clipboard
Reference<XTransferableSupplier> xTransferSupplier = (Reference<XTransferableSupplier>) UnoRuntime.queryInterface(XTransferableSupplier.class, xChartDoc);
Reference<XTransferable> xTransferable = xTransferSupplier.getTransferable();
Reference<XClipboard> xClipboard = (Reference<XClipboard>) UnoRuntime.queryInterface(XClipboard.class, xContext.getServiceManager().createInstanceWithContext("com.sun.star.datatransfer.clipboard.SystemClipboard", xContext));
xClipboard.setContents(xTransferable, null);
// insert chart as OLE object
Reference<XTextContent> xContent = (Reference<XTextContent>) UnoRuntime.queryInterface(XTextContent.class, xDoc.createInstance("com.sun.star.text.TextGraphicObject"));
xContent.setGraphicURL("private:factory/swriter");
xContent.setCLSID("com.sun.star.chart2.ChartDocument");
Reference<XTextCursor> xCursor = xText.createTextCursor();
xCursor.gotoEnd(false);
Reference<XTextContentInsertion> xInsertion = (Reference<XTextContentInsertion>) UnoRuntime.queryInterface(XTextContentInsertion.class, xText);
xInsertion.insertContent(xContent, xCursor);
Этот пример создает столбчатую диаграмму на основе данных в листе "Sheet1" документа с таблицей Calc и добавляет ее в качестве OLE-объекта на текущую страницу документа Writer. Параметры диаграммы можно настроить через свойства xChart.
Вариант 2: Вставить изображение диаграммы
Для этого нужно создать и настроить диаграмму в документе для работы с диаграммами, затем сохранить ее в файл и вставить этот файл в качестве изображения в текстовый документ.
Пример кода:
// create new document for chart
Reference<XComponentContext> xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
Reference<XComponent> xSpreadsheetDoc = (Reference<XComponent>) UnoRuntime.queryInterface(XComponent.class, xContext.getServiceManager().createInstanceWithContext("com.sun.star.sheet.SpreadsheetDocument", xContext));
Reference<XSpreadsheetDocument> xNewSpreadsheetDoc = (Reference<XSpreadsheetDocument>) UnoRuntime.queryInterface(XSpreadsheetDocument.class, xSpreadsheetDoc);
// create chart
Reference<XSpreadsheet> xSheet = xNewSpreadsheetDoc.getSheets().getByIndex(0);
Reference<XCellRangeAddressable> xRange = (Reference<XCellRangeAddressable>) UnoRuntime.queryInterface(XCellRangeAddressable.class, xSheet.getCellRangeByName("A1:C4"));
Reference<XChartDocument> xChartDoc = (Reference<XChartDocument>) UnoRuntime.queryInterface(XChartDocument.class, xContext.getServiceManager().createInstanceWithContext("com.sun.star.chart2.ChartDocument", xContext));
Reference<XDiagram> xDiagram = xChartDoc.createDiagram(ChartType.COLUMN, xRange.getCellRangeAddress(), new ChartData());
Reference<XChart> xChart = UnoRuntime.queryInterface(XChart.class, xDiagram);
xChart.setTitle("My Column Chart");
// create temporary file for chart image
File tempFile = new File(System.getProperty("java.io.tmpdir"), "chart.png");
XStorable xStorable = UnoRuntime.queryInterface(XStorable.class, xChartDoc);
PropertyValue[] aProps = new PropertyValue[] { new PropertyValue() };
aProps[0].Name = "FilterName";
aProps[0].Value = "PNG - Portable Network Graphics";
xStorable.storeToURL("file:///" + tempFile.getAbsolutePath().replaceAll("\\\\", "/"), aProps);
// insert chart as image
Reference<XTextContent> xGraphic = (Reference<XTextContent>) UnoRuntime.queryInterface(XTextContent.class, xDoc.createInstance("com.sun.star.text.GraphicObject"));
Reference<XPropertySet> xPropSet = (Reference<XPropertySet>) UnoRuntime.queryInterface(XPropertySet.class, xGraphic);
xPropSet.setPropertyValue("AnchorType", TextContentAnchorType.AS_CHARACTER);
xPropSet.setPropertyValue("GraphicURL", "file:///" + tempFile.getAbsolutePath().replaceAll("\\\\", "/"));
Reference<XTextCursor> xCursor = xText.createTextCursor();
xCursor.gotoEnd(false);
Reference<XTextContentInsertion> xInsertion = (Reference<XTextContentInsertion>) UnoRuntime.queryInterface(XTextContentInsertion.class, xText);
xInsertion.insertContent(xGraphic, xCursor);
Этот пример создает столбчатую диаграмму на основе данных в листе "Sheet1" документа с таблицей Calc, сохраняет ее в файл и вставляет как изображение на текущую страницу документа Writer. Параметры диаграммы можно настроить через свойства xChart.