Advertisement
Guest User

OpenOffice / BrOffice / LibreOffice Writer Manipulation

a guest
May 23rd, 2012
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 22.75 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.InputStream;
  4. import java.io.OutputStream;
  5. import java.net.URL;
  6. import java.util.ArrayList;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10.  
  11. import com.sun.star.beans.PropertyValue;
  12. import com.sun.star.beans.XPropertySet;
  13. import com.sun.star.comp.beans.NoConnectionException;
  14. import com.sun.star.comp.beans.OOoBean;
  15. import com.sun.star.comp.beans.OfficeDocument;
  16. import com.sun.star.comp.helper.Bootstrap;
  17. import com.sun.star.container.XEnumerationAccess;
  18. import com.sun.star.container.XIndexAccess;
  19. import com.sun.star.container.XNameAccess;
  20. import com.sun.star.container.XNameContainer;
  21. import com.sun.star.container.XNamed;
  22. import com.sun.star.datatransfer.XTransferable;
  23. import com.sun.star.datatransfer.XTransferableSupplier;
  24. import com.sun.star.document.XDocumentInsertable;
  25. import com.sun.star.frame.XController;
  26. import com.sun.star.frame.XDispatchHelper;
  27. import com.sun.star.frame.XDispatchProvider;
  28. import com.sun.star.frame.XFrame;
  29. import com.sun.star.graphic.XGraphic;
  30. import com.sun.star.graphic.XGraphicProvider;
  31. import com.sun.star.lang.IndexOutOfBoundsException;
  32. import com.sun.star.lang.XMultiServiceFactory;
  33. import com.sun.star.style.BreakType;
  34. import com.sun.star.style.XStyleFamiliesSupplier;
  35. import com.sun.star.text.ControlCharacter;
  36. import com.sun.star.text.TextContentAnchorType;
  37. import com.sun.star.text.XBookmarksSupplier;
  38. import com.sun.star.text.XPageCursor;
  39. import com.sun.star.text.XReferenceMarksSupplier;
  40. import com.sun.star.text.XText;
  41. import com.sun.star.text.XTextContent;
  42. import com.sun.star.text.XTextCursor;
  43. import com.sun.star.text.XTextDocument;
  44. import com.sun.star.text.XTextFieldsSupplier;
  45. import com.sun.star.text.XTextRange;
  46. import com.sun.star.text.XTextSection;
  47. import com.sun.star.text.XTextSectionsSupplier;
  48. import com.sun.star.text.XTextTable;
  49. import com.sun.star.text.XTextViewCursor;
  50. import com.sun.star.text.XTextViewCursorSupplier;
  51. import com.sun.star.uno.RuntimeException;
  52. import com.sun.star.uno.UnoRuntime;
  53. import com.sun.star.util.XRefreshable;
  54. import com.sun.star.util.XSearchDescriptor;
  55. import com.sun.star.util.XSearchable;
  56.  
  57. /**
  58.  * Classe que encapsula recursos para o tratamento de documentos Writer. Recebe como parâmetro uma instância de office
  59.  * bean do qual obtém o documento a ser tratado
  60.  */
  61. public class WriterDocument {
  62.     /**
  63.      * Posição do cursor no documento. A posição ATUAL não altera a posição do cursor no documento
  64.      */
  65.     public enum EPosicao {
  66.         INICIO,
  67.         ATUAL,
  68.         FIM
  69.     }
  70.  
  71.     public static final String MSG_ERRO_OPEN_OFFICE = "Ocorreu um erro inesperado ao manipular documento. Por favor, entre em contato com o suporte técnico.";
  72.  
  73.     private static String PREFIXO_ARQUIVO = "tce-doe";
  74.  
  75.     public static void converterParaPDF(String caminhoEntrada, String caminhoSaida) {
  76.         try {
  77.             OOoBean lWorld = LibreOfficeUtil.carregarDocumento(caminhoEntrada);
  78.             PropertyValue[] lProps = new PropertyValue[1];
  79.             lProps[0] = new PropertyValue();
  80.             lProps[0].Name = "FilterName";
  81.             lProps[0].Value = "writer_pdf_Export";
  82.             lWorld.storeToURL(caminhoSaida, lProps);
  83.         } catch (Exception pEx) {
  84.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, pEx);
  85.         }
  86.     }
  87.  
  88.     private final OOoBean bean;
  89.  
  90.     public WriterDocument(OOoBean bean) {
  91.         this.bean = bean;
  92.     }
  93.  
  94.     /**
  95.      * Criar um cursor.
  96.      * @return
  97.      * @throws Exception
  98.      */
  99.     public XTextCursor createTextCursor() {
  100.         return getText().createTextCursor();
  101.     }
  102.  
  103.     /**
  104.      * Cria uma instância de XTextTable
  105.      * @param bean
  106.      * @return
  107.      * @throws Exception
  108.      */
  109.     public XTextTable createTextTable() {
  110.         try {
  111.             return UnoRuntime.queryInterface(XTextTable.class,
  112.                     bean.getMultiServiceFactory().createInstance("com.sun.star.text.TextTable"));
  113.         } catch (Exception pEx) {
  114.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, pEx);
  115.         }
  116.     }
  117.  
  118.     public void excluirBookmark(String bookmarkName) {
  119.         try {
  120.             XTextDocument textDocument = getTextDocument();
  121.             XController xController = textDocument.getCurrentController();
  122.             XFrame xFrame = xController.getFrame();
  123.             XDispatchProvider xDispatchProvider = UnoRuntime.queryInterface(XDispatchProvider.class, xFrame);
  124.  
  125.             Object dispatchHelper = bean.getMultiServiceFactory().createInstance("com.sun.star.frame.DispatchHelper");
  126.             XDispatchHelper helper = UnoRuntime.queryInterface(XDispatchHelper.class, dispatchHelper);
  127.  
  128.             XBookmarksSupplier bookmarksSupplier = UnoRuntime.queryInterface(XBookmarksSupplier.class, textDocument);
  129.  
  130.             XRefreshable iRefreshable = UnoRuntime.queryInterface(XRefreshable.class, bookmarksSupplier);
  131.             iRefreshable.refresh(); // Do I HAVE to do that?
  132.  
  133.             Object iDeleteBookmark = bookmarksSupplier.getBookmarks().getByName(bookmarkName);
  134.             XTextContent iBookmarkContent = UnoRuntime.queryInterface(XTextContent.class, iDeleteBookmark);
  135.             XTextRange iBookmarkRange = iBookmarkContent.getAnchor();
  136.             getTextViewCursor().gotoRange(iBookmarkRange, false);
  137.             // XTextRange iRange = iBookmarkRange.getText().createTextCursorByRange(iBookmarkRange);
  138.  
  139.             helper.executeDispatch(xDispatchProvider, ".uno:Delete", "", 0, new PropertyValue[] {});
  140.         } catch (Exception e) {
  141.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, e);
  142.         }
  143.     }
  144.  
  145.     public void excluirTexto(XTextRange rangeStart, XTextRange rangeEnd) {
  146.         XTextViewCursorSupplier lSupplier = getTextViewCursorSupplier();
  147.         XTextViewCursor cursor = lSupplier.getViewCursor();
  148.         // Seleciona o texto de rangeStart até rangeEnd e exclui o texto selecionado
  149.         cursor.gotoRange(rangeStart.getStart(), false);
  150.         cursor.gotoRange(rangeEnd.getEnd(), true);
  151.         cursor.setString("");
  152.     }
  153.  
  154.     public void fecharDocumento() {
  155.         LibreOfficeUtil.fecharDocumento(bean);
  156.     }
  157.  
  158.     /**
  159.      * Obtém o conteúdo entre duas posições.
  160.      * @param pRangeInicio
  161.      * @param pRangeFim
  162.      * @return
  163.      * @throws Exception
  164.      */
  165.     public XTransferable getConteudoPorRange(XTextRange pRangeInicio, XTextRange pRangeFim) {
  166.         XTextViewCursor lCursor = getTextViewCursor();
  167.         // Seleciona o conteúdo
  168.         lCursor.gotoRange(pRangeInicio.getEnd(), false);
  169.         lCursor.gotoRange(pRangeFim.getStart(), true);
  170.         // cria o mantenedor de transferência
  171.         XTransferableSupplier lTransSupplier = getTransferableSupplier();
  172.         return lTransSupplier.getTransferable();
  173.     }
  174.  
  175.     /**
  176.      * Obtém o controller corrente.
  177.      * @return XController
  178.      * @throws Exception
  179.      */
  180.     public XController getCurrentController() {
  181.         return getTextDocument().getCurrentController();
  182.     }
  183.  
  184.     /**
  185.      * Obtém uma instância de XEnumerationAccess.
  186.      * @param bean
  187.      * @return
  188.      * @throws Exception
  189.      */
  190.     public XEnumerationAccess getEnumarationAccess() {
  191.         return UnoRuntime.queryInterface(XEnumerationAccess.class, getTextDocument());
  192.     }
  193.  
  194.     public OOoBean getOfficeBean() {
  195.         return bean;
  196.     }
  197.  
  198.     /**
  199.      * Retorna um OfficeDocument - objeto que representa a raiz de um documento do Writer/Calc/Impress/Draw.
  200.      * @return
  201.      * @throws Exception
  202.      */
  203.     private OfficeDocument getOfficeDocument() {
  204.         return LibreOfficeUtil.getOfficeDocument(bean);
  205.     }
  206.  
  207.     private XPageCursor getPageCursor(XTextViewCursor textViewCursor) {
  208.         XPageCursor pageCursor = UnoRuntime.queryInterface(XPageCursor.class, textViewCursor);
  209.         return pageCursor;
  210.     }
  211.  
  212.     public XTextRange getPosicaoBookmark(String bookmarkName) {
  213.         try {
  214.             XTextDocument textDocument = getTextDocument();
  215.  
  216.             XBookmarksSupplier bookmarksSupplier = UnoRuntime.queryInterface(XBookmarksSupplier.class, textDocument);
  217.  
  218.             XRefreshable iRefreshable = UnoRuntime.queryInterface(XRefreshable.class, bookmarksSupplier);
  219.             iRefreshable.refresh(); // Is it necessary?
  220.  
  221.             Object iDeleteBookmark = bookmarksSupplier.getBookmarks().getByName(bookmarkName);
  222.             XTextContent iBookmarkContent = UnoRuntime.queryInterface(XTextContent.class, iDeleteBookmark);
  223.             XTextRange iBookmarkRange = iBookmarkContent.getAnchor();
  224.             getTextViewCursor().gotoRange(iBookmarkRange, false);
  225.  
  226.             return iBookmarkRange;
  227.         } catch (Exception e) {
  228.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, e);
  229.         }
  230.     }
  231.  
  232.     public XTextRange getPosicaoSecao(String sectionName) {
  233.         try {
  234.             XTextSectionsSupplier xTextSectionsSupplier = UnoRuntime.queryInterface(XTextSectionsSupplier.class,
  235.                     getTextDocument());
  236.             XTextSection textSection = UnoRuntime.queryInterface(XTextSection.class, xTextSectionsSupplier.getTextSections()
  237.                     .getByName(sectionName));
  238.             return textSection.getAnchor();
  239.         } catch (Exception e) {
  240.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, e);
  241.         }
  242.     }
  243.  
  244.     public XSearchable getSearchable() {
  245.         return UnoRuntime.queryInterface(XSearchable.class, getTextDocument());
  246.     }
  247.  
  248.     public XSearchDescriptor getSearchDescriptor(XSearchable busca) {
  249.         return busca.createSearchDescriptor();
  250.     }
  251.  
  252.     /**
  253.      * Obtém uma instância de XText.
  254.      * @return
  255.      * @throws Exception
  256.      */
  257.     public XText getText() {
  258.         return getTextDocument().getText();
  259.     }
  260.  
  261.     public String getText(XTextRange rangeStart, XTextRange rangeEnd) {
  262.         XTextViewCursorSupplier lSupplier = getTextViewCursorSupplier();
  263.         XTextViewCursor cursor = lSupplier.getViewCursor();
  264.         // Seleciona o texto de rangeStart até rangeEnd e retorna o texto selecionado
  265.         cursor.gotoRange(rangeStart.getStart(), false);
  266.         cursor.gotoRange(rangeEnd.getEnd(), true);
  267.         return cursor.getString();
  268.     }
  269.  
  270.     /**
  271.      * Criar um cursor com limite definido através de um XTextRange.
  272.      * @param range
  273.      * @return
  274.      * @throws Exception
  275.      */
  276.     public XTextCursor getTextCursorPorRange(XTextRange range) {
  277.         return getText().createTextCursorByRange(range);
  278.     }
  279.  
  280.     /**
  281.      * Obtém uma instância de XTextDocument que é o topo da comunicação com o Writer. A partir dela que as demais
  282.      * interfaces são utilizadas.
  283.      * @return
  284.      * @throws Exception
  285.      */
  286.     public XTextDocument getTextDocument() {
  287.         return UnoRuntime.queryInterface(XTextDocument.class, getOfficeDocument());
  288.     }
  289.  
  290.     public XTextRange getTextRange(Object object) {
  291.         return UnoRuntime.queryInterface(XTextRange.class, object);
  292.     }
  293.  
  294.     /**
  295.      * Retorna uma instância de XTextViewCursor.
  296.      * @param bean
  297.      * @return
  298.      * @throws Exception
  299.      */
  300.     public XTextViewCursor getTextViewCursor() {
  301.         return getTextViewCursorSupplier().getViewCursor();
  302.     }
  303.  
  304.     /**
  305.      * Obtém um fornecedor de cursor de texto.
  306.      * @return
  307.      * @throws Exception
  308.      */
  309.     public XTextViewCursorSupplier getTextViewCursorSupplier() {
  310.         return UnoRuntime.queryInterface(XTextViewCursorSupplier.class, getCurrentController());
  311.     }
  312.  
  313.     /**
  314.      * Obtêm matenedor de área de transferência
  315.      * @return
  316.      */
  317.     public XTransferableSupplier getTransferableSupplier() {
  318.         return UnoRuntime.queryInterface(XTransferableSupplier.class, getCurrentController());
  319.     }
  320.  
  321.     public void inserirBookmark(String bookmarkName, XTextRange posicao) {
  322.         try {
  323.             XTextDocument textDocument = getTextDocument();
  324.             XMultiServiceFactory iMSF = UnoRuntime.queryInterface(XMultiServiceFactory.class, textDocument);
  325.             Object bookmark = iMSF.createInstance("com.sun.star.text.Bookmark");
  326.             XNamed xNamed = UnoRuntime.queryInterface(XNamed.class, bookmark);
  327.             xNamed.setName(bookmarkName);
  328.             XTextContent xTextContent = UnoRuntime.queryInterface(XTextContent.class, bookmark);
  329.             textDocument.getText().insertTextContent(posicao, xTextContent, false);
  330.         } catch (Exception e) {
  331.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, e);
  332.         }
  333.     }
  334.  
  335.     public void inserirDocumento(OOoBean bean) {
  336.         inserirDocumento(bean, true);
  337.     }
  338.  
  339.     /**
  340.      * Insere um documento. Como o LibreOffice geralmente cria uma quebra de página quando um documento é inserido
  341.      * dentro de outro, o parâmetro <code>removerQuebraPagina</code> serve para indicar quando esta quebra de página
  342.      * deve ser removida.
  343.      * @param bean
  344.      * @param removerQuebraPagina - se deve remover ou não a quebra de página gerada pelo LibreOffice
  345.      */
  346.     public void inserirDocumento(OOoBean bean, boolean removerQuebraPagina) {
  347.         try {
  348.             WriterDocument writerOrigem = new WriterDocument(bean);
  349.             XTextRange inicio = writerOrigem.getText().getStart();
  350.             XTextRange fim = writerOrigem.getText().getEnd();
  351.  
  352.             inserirParagrafo();
  353.             XTransferable transferable = writerOrigem.getConteudoPorRange(inicio, fim);
  354.             setTransferable(transferable);
  355.  
  356.             if (removerQuebraPagina) {
  357.                 // !Importante
  358.                 // Solução para remover a quebra de página inserida pelo LibreOffice:
  359.                 // 1) Guardar a posição do fim do texto e mover o cursor para o início da página criada
  360.                 XTextViewCursor textViewCursor = getTextViewCursor();
  361.                 XTextRange posicaoFimTexto = textViewCursor.getStart();
  362.                 XPageCursor pageCursor = getPageCursor(textViewCursor);
  363.                 pageCursor.jumpToStartOfPage();
  364.  
  365.                 // 2) Selecionar um caractere à esquerda e removê-lo, pois este representa a quebra de página
  366.                 textViewCursor.goLeft((short) 1, true);
  367.                 textViewCursor.setString("");
  368.  
  369.                 // 3) Mover o cursor de volta para o fim da seção
  370.                 textViewCursor.gotoRange(posicaoFimTexto, false);
  371.             }
  372.         } catch (Exception e) {
  373.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, e);
  374.         }
  375.     }
  376.  
  377.     public void inserirDocumento(String caminhoArquivo) {
  378.         try {
  379.             XTextViewCursor textViewCursor = getTextViewCursor();
  380.             XTextCursor textCursor = textViewCursor.getText().createTextCursorByRange(textViewCursor);
  381.             XDocumentInsertable documentInsertable = UnoRuntime.queryInterface(XDocumentInsertable.class, textCursor);
  382.             documentInsertable.insertDocumentFromURL(caminhoArquivo, null);
  383.         } catch (Exception e) {
  384.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, e);
  385.         }
  386.     }
  387.  
  388.     public void inserirImagem(URL imagem) {
  389.         try {
  390.             XMultiServiceFactory lMSFDoc = UnoRuntime.queryInterface(XMultiServiceFactory.class, getOfficeBean()
  391.                     .getDocument());
  392.             Object oGraphic = lMSFDoc.createInstance("com.sun.star.text.TextGraphicObject");
  393.  
  394.             Object lGraphicProviderObject = Bootstrap.bootstrap().getServiceManager()
  395.                     .createInstanceWithContext("com.sun.star.graphic.GraphicProvider", Bootstrap.bootstrap());
  396.             XGraphicProvider lGraphicProvider = UnoRuntime.queryInterface(XGraphicProvider.class, lGraphicProviderObject);
  397.  
  398.             PropertyValue[] lProperties = new PropertyValue[1];
  399.             lProperties[0] = new PropertyValue();
  400.             lProperties[0].Name = "URL";
  401.             lProperties[0].Value = imagem.getProtocol() + "://" + imagem.getPath();
  402.             XGraphic lGraphic = lGraphicProvider.queryGraphic(lProperties);
  403.  
  404.             XTextContent lImagemTextContent = UnoRuntime.queryInterface(XTextContent.class, oGraphic);
  405.             XPropertySet lPropSet = UnoRuntime.queryInterface(XPropertySet.class, oGraphic);
  406.             lPropSet.setPropertyValue("AnchorType", TextContentAnchorType.AS_CHARACTER);
  407.             lPropSet.setPropertyValue("Graphic", lGraphic);
  408.             getTextViewCursor().getText().insertTextContent(getTextViewCursor(), lImagemTextContent, true);
  409.         } catch (Exception pEx) {
  410.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, pEx);
  411.         }
  412.     }
  413.  
  414.     public void inserirMarcaDagua(InputStream inputStreamImagem) {
  415.         try {
  416.             File lTempFile = File.createTempFile(PREFIXO_ARQUIVO, "img");
  417.             lTempFile.deleteOnExit();
  418.  
  419.             OutputStream osTempFile = new FileOutputStream(lTempFile);
  420.             int i;
  421.             while ((i = inputStreamImagem.read()) != -1) {
  422.                 osTempFile.write(i);
  423.             }
  424.             inputStreamImagem.close();
  425.  
  426.             XTextDocument oDoc = UnoRuntime.queryInterface(XTextDocument.class, getOfficeBean().getDocument());
  427.  
  428.             // create a supplier to get the Style family collection
  429.             XStyleFamiliesSupplier xSupplier = UnoRuntime.queryInterface(XStyleFamiliesSupplier.class, oDoc);
  430.  
  431.             // get the NameAccess interface from the Style family collection
  432.             XNameAccess xNameAccess = xSupplier.getStyleFamilies();
  433.             XNameContainer xPageStyleCollection = UnoRuntime.queryInterface(XNameContainer.class,
  434.                     xNameAccess.getByName("PageStyles"));
  435.  
  436.             // create a PropertySet to set the properties for the new Pagestyle
  437.  
  438.             String[] styles = xPageStyleCollection.getElementNames();
  439.             for (String style : styles) {
  440.                 XPropertySet xPropertySet = UnoRuntime.queryInterface(XPropertySet.class,
  441.                         xPageStyleCollection.getByName(style));
  442.                 // XPropertySet xPropertySet = (XPropertySet)
  443.                 // UnoRuntime.queryInterface(XPropertySet.class,
  444.                 // xPageStyleCollection.getByName("Standard"));
  445.                 xPropertySet.setPropertyValue("BackGraphicURL", lTempFile.toURI().toURL().getProtocol() + "://"
  446.                         + lTempFile.toURI().toURL().getPath());
  447.                 // xPropertySet.setPropertyValue("BackGraphicURL", createUNOFileURL("watermark.jpg",
  448.                 // xRemoteContext));
  449.             }
  450.         } catch (Exception e) {
  451.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE);
  452.         }
  453.     }
  454.  
  455.     public void inserirNovaPagina() {
  456.         XTextCursor textCursor = createTextCursor();
  457.         textCursor.gotoEnd(false);
  458.         XPropertySet properties = UnoRuntime.queryInterface(XPropertySet.class, textCursor);
  459.         try {
  460.             properties.setPropertyValue("BreakType", BreakType.PAGE_AFTER);
  461.             textCursor.getText().insertControlCharacter(textCursor.getEnd(), (short) 0, false);
  462.         } catch (Exception e) {
  463.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, e);
  464.         }
  465.         textCursor.gotoEnd(true);
  466.     }
  467.  
  468.     public void inserirParagrafo() {
  469.         try {
  470.             XTextViewCursor cursor = getTextViewCursor();
  471.             cursor.getText().insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, false);
  472.         } catch (Exception e) {
  473.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, e);
  474.         }
  475.     }
  476.  
  477.     public void inserirQuebraLinha() {
  478.         try {
  479.             XTextViewCursor cursor = getTextViewCursor();
  480.             cursor.getText().insertControlCharacter(cursor, ControlCharacter.LINE_BREAK, false);
  481.         } catch (Exception e) {
  482.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, e);
  483.         }
  484.     }
  485.  
  486.     public void inserirReferencia(String referencia) {
  487.         try {
  488.             XMultiServiceFactory lMSFDoc = UnoRuntime.queryInterface(XMultiServiceFactory.class, getOfficeBean()
  489.                     .getDocument());
  490.             XNamed lRefMark = UnoRuntime.queryInterface(XNamed.class,
  491.                     lMSFDoc.createInstance("com.sun.star.text.ReferenceMark"));
  492.             lRefMark.setName(referencia);
  493.  
  494.             XTextCursor cursor = getTextViewCursor();
  495.             cursor.gotoRange(cursor.getEnd(), false);
  496.  
  497.             inserirTexto(referencia);
  498.             cursor.goLeft((short) 1, true);
  499.  
  500.             XTextRange lRange = getTextRange(cursor);
  501.             XTextContent lContent = UnoRuntime.queryInterface(XTextContent.class, lRefMark);
  502.             cursor.getText().insertTextContent(lRange, lContent, true);
  503.         } catch (Exception pEx) {
  504.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, pEx);
  505.         }
  506.     }
  507.  
  508.     public void inserirTexto(String texto) {
  509.         XTextRange viewCursor = getTextViewCursor();
  510.         XText text = viewCursor.getText();
  511.         text.insertString(viewCursor, texto, false);
  512.     }
  513.  
  514.     /**
  515.      * Verifica se a conexão com o OpenOffice está estabelicida.
  516.      * @return
  517.      * @throws Exception
  518.      */
  519.     public boolean isAberto() {
  520.         if (bean != null) {
  521.             try {
  522.                 if (bean.getOOoConnection() != null) {
  523.                     return true;
  524.                 }
  525.             } catch (NoConnectionException pEx) {
  526.                 throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, pEx);
  527.             }
  528.         }
  529.         return false;
  530.     }
  531.  
  532.     /**
  533.      * Move o cursor para o fim do documento.
  534.      * @throws Exception
  535.      */
  536.     public void moverCursorFimDocumento() {
  537.         createTextCursor().gotoEnd(false);
  538.     }
  539.  
  540.     /**
  541.      * Move o cursor para o início do documento.
  542.      * @throws Exception
  543.      */
  544.     public void moverCursorInicioDocumento() {
  545.         createTextCursor().gotoStart(false);
  546.     }
  547.  
  548.     /**
  549.      * Move o cursor para um range especificado, mas não estando selecionado.
  550.      * @param pRange
  551.      * @throws Exception
  552.      */
  553.     public void moverCursorParaRange(XTextRange pRange) {
  554.         getTextViewCursor().gotoRange(pRange, false);
  555.     }
  556.  
  557.     public String[] obterReferencias() {
  558.         try {
  559.             XReferenceMarksSupplier lRefSupplier = UnoRuntime.queryInterface(XReferenceMarksSupplier.class, getOfficeBean()
  560.                     .getDocument());
  561.             return lRefSupplier.getReferenceMarks().getElementNames();
  562.         } catch (Exception pEx) {
  563.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, pEx);
  564.         }
  565.     }
  566.  
  567.     public File salvarEmPDFTemporario() {
  568.         PropertyValue[] props = new PropertyValue[1];
  569.         props[0] = new PropertyValue();
  570.         props[0].Name = "FilterName";
  571.         props[0].Value = "writer_pdf_Export";
  572.         try {
  573.             File file = File.createTempFile(PREFIXO_ARQUIVO, ".pdf");
  574.             file.deleteOnExit();
  575.             FileOutputStream fileOS = new FileOutputStream(file);
  576.  
  577.             bean.storeToStream(fileOS, props);
  578.             fileOS.flush();
  579.             return file;
  580.         } catch (Exception pEx) {
  581.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, pEx);
  582.         }
  583.     }
  584.  
  585.     /**
  586.      * Adiciona uma lista de XTransferables para um range destino.
  587.      * @throws Exception
  588.      */
  589.     public void selecionar(XTextRange posicaoInicial, XTextRange posicaoFinal) {
  590.         XTextViewCursor cursor = getTextViewCursor();
  591.         cursor.gotoRange(posicaoInicial, false);
  592.         cursor.gotoRange(posicaoFinal, true);
  593.     }
  594.  
  595.     /**
  596.      * Seleciona um conteúdo de um XTextRange.
  597.      * @param pRange
  598.      * @throws Exception
  599.      */
  600.     public void selecionarConteudo(XTextRange pRange) {
  601.         getTextViewCursor().gotoRange(pRange, true);
  602.     }
  603.  
  604.     public void setEstiloParagrafo(String paragraphStyleName) {
  605.         XPropertySet xTextProps = UnoRuntime.queryInterface(XPropertySet.class, getTextViewCursor());
  606.         try {
  607.             xTextProps.setPropertyValue("ParaStyleName", paragraphStyleName);
  608.         } catch (Exception e) {
  609.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, e);
  610.         }
  611.     }
  612.  
  613.     public void setTransferable(XTransferable pTransferable) {
  614.         try {
  615.             getTransferableSupplier().insertTransferable(pTransferable);
  616.         } catch (Exception pEx) {
  617.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, pEx);
  618.         }
  619.     }
  620.  
  621.     public void setValorCampo(String fieldName, String fieldValue) {
  622.         try {
  623.             XTextFieldsSupplier xTextFieldsSupplier = UnoRuntime.queryInterface(XTextFieldsSupplier.class,
  624.                     getOfficeDocument());
  625.             XNameAccess xNamedFieldMasters = xTextFieldsSupplier.getTextFieldMasters();
  626.             Object fieldMaster = xNamedFieldMasters.getByName("com.sun.star.text.fieldmaster.User." + fieldName);
  627.             XPropertySet xPropertySet = UnoRuntime.queryInterface(XPropertySet.class, fieldMaster);
  628.             xPropertySet.setPropertyValue("Content", fieldValue);
  629.         } catch (Exception e) {
  630.             e.printStackTrace();
  631.             throw new RuntimeException(MSG_ERRO_OPEN_OFFICE, e);
  632.         }
  633.     }
  634.  
  635.     /**
  636.      * Substitui o conteúdo no intervalo entre pRangeInicio e pRangeFim
  637.      * @param pNovoTexto - Novo conteúdo que ficará entre os ranges
  638.      * @param pRangeInicio
  639.      * @param pRangeFim
  640.      * @throws Exception
  641.      */
  642.     public void substituirConteudoRange(String pNovoTexto, XTextRange pRangeInicio, XTextRange pRangeFim) {
  643.         // Obtém o cursor
  644.         XTextViewCursor lCursor = getTextViewCursor();
  645.         lCursor.gotoRange(pRangeInicio.getStart(), false);
  646.         lCursor.gotoRange(pRangeFim.getEnd(), true);
  647.         // Cria um cursor para o texto selecionado para permitir o funcionamento em estruturas como
  648.         // tabela:
  649.         XTextCursor lCursorTexto = lCursor.getText().createTextCursor();
  650.         lCursorTexto.gotoRange(pRangeInicio.getStart(), false);
  651.         lCursorTexto.gotoRange(pRangeFim.getEnd(), true);
  652.         lCursorTexto.setString(pNovoTexto);
  653.     }
  654.  
  655. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement