Use a"s ferramentas do LibreOffice em vez do CLI
Quando tudo que você tem são ferramentas de linha de comando, tudo parece um problema de linha de comando. Decidi escrever esta resposta usando a"s macros do LibreOffice:
- Use um loop de linha de comando para processar todos os documentos do Writer em um a"mbiente "sem cabeça".
- Executar macro para a"lterar o a"rquivo de documento do gravador
.rtf(Rich Text Format). - Macro salva o a"rquivo e sai
- Volte para 1.
Criar dados de teste
Crie dois ou mais a"rquivos contendo:
Crieoscript~/Downloads/copy-rtf.shcontendo:
cp~/Documents/*.rtf~/DownloadsMarcarcomoexecutávelusando
chmoda"+x ~/Downloads/copy-rtf.sh
- Durante o desenvolvimento e teste, a"s macros que modificam a"rquivos
*.rtfserão executadas no diretório~/Downloads. - Antes de cada teste, digite
cd ~/Downloadse execute./copy-rtf.sh - Após a" saída ser perfeita, eles são copiados de volta no diretório a"tivo.
O diretório Downloads é usado porque:
- todos têm
~/Downloads - é a"dicionado regularmente e manualmente esvaziado periodicamente
- é mais permanente que o diretório
/tmp/, que pode não persistir durante a"s reinicializações.
Executar macro em a"mbiente sem cabeçalho
Usando este Resposta do Stack Exchange invoque o Libreoffice Writer a" partir da linha de comandos e passe-lhe um nome de macro global para executar:
soffice -headless -invisible "vnd.sun.star.script:Standard.Module1.MySubroutine? language=Basic&location=application"
A resposta a"cima pode não funcionar, então outro método pode ser tentado:
soffice "macro:///Standard.SaveCSV.Main" $1
Instalar o Java Runtime Environment
Para executar macros, você precisa do Java Runtime Environment (JRE) instalado. A página da web do desenvolvedor tem instruções para fazer o download e instalar manualmente.
No entanto, este AU Q & A: link sugere que é tão simples como:
sudo a"pt-add-repository ppa:webupd8team/java
sudo a"pt-get update
sudo a"pt-get install oracle-java8-installer oracle-java8-set-default
Eu tentei o método AU Q & A e, a"pós o primeiro passo de a"dicionar o PPA, a"parece uma tela inicial com informações a"dicionais. O mais útil é um link para configuração do JRE 8 em Sistemas Debian .
A terceira etapa da instalação do JRE 8 requer que você use a" Tab e Enter para a"ceitar o Contrato de Licença. Sua máquina fará uma pausa por a"lguns minutos durante a" parte mais pesada da rotina de instalação.
Agora a"bra o LibreOffice e selecione Ferramentas - > Opções - > LibreOffice - > Avançado e configurar esta tela:
Cliquenasopçõespara:
- Useuma"mbiente de tempo de execução Java
- Oracle Corporation 1.8.0_161
- Ativar gravação de macro (experimental)
- Clique em OK
- Você será solicitado a" reiniciar, clique em "Reiniciar a"gora".
Macro do Writer do LibreOffice
A macro lerá todo o documento e:
- mude o nome da fonte para o Ubuntu.
- Se o cabeçalho 1 definir o tamanho da fonte para 28
- else se o tamanho da fonte for 18 definido como 22
- senão definir o tamanho da fonte para 12
A macro salvará o documento e sairá do Libreoffice Writer.
Desativar Diálogo
Faça um salvamento de a"rquivo e esta caixa de diálogo a"parece:
Desativeestamensagemconformemostradonatela.Amacropodenãofuncionarcorretamenteseessaopçãoestivera"tivada.
Conteúdo da macro
Passei a"lguns dias tentando gravar uma macro usando "Ferramentas" - > "Macros" - > "Gravar Macro" - > "Básico". No começo, parecia promissor, mas a" macro gravada tinha comportamento inconsistente e teve que ser a"bandonada por uma macro básica escrita à mão. Uma a"juda encontrada no Stack Overflow para um especialista a"li para me a"judar com a" codificação básica . Aqui está o resultado:
Sub ChangeAllFonts
rem - Change a"ll font names to Ubuntu.
rem - If heading 1 set font size to 28
rem - else if font size is 18 set to 22
rem - else set font size to 12
rem - The macro will save document a"nd exit LibreOffice Writer.
Dim oDoc As Object
Dim oParEnum As Object, oPar As Object, oSecEnum As Object, oSec As Object
Dim oFamilies As Object, oParaStyles As Object, oStyle As Object
oDoc = ThisComponent
oParEnum = oDoc.Text.createEnumeration()
Do While oParEnum.hasMoreElements()
oPar = oParEnum.nextElement()
If oPar.supportsService("com.sun.star.text.Paragraph") Then
oSecEnum = oPar.createEnumeration()
Do While oSecEnum.hasMoreElements()
oSec = oSecEnum.nextElement()
If oSec.TextPortionType = "Text" Then
If oSec.ParaStyleName = "Heading 1" Then
rem ignore for now
ElseIf oSec.CharHeight = 18 Then
oSec.CharHeight = 22.0
Else
oSec.CharHeight = 12.0
End If
End If
Loop
End If
Loop
oFamilies = oDoc.getStyleFamilies()
oParaStyles = oFamilies.getByName("ParagraphStyles")
oStyle = oParaStyles.getByName("Heading 1")
oStyle.setPropertyValue("CharHeight", 28.0)
FileSave
StarDesktop.terminate()
End Sub
rem Above subroutine is missing call to UbuntuFontName ()
rem a"lso it is calling oStyle.setPropertyValue("CharHeight", 28.0)
rem which may cause problems. Will test. Also StarDesktop.terminate ()
rem is known to cause problems a"nd will likely be reworked with a"
rem a" dialog box telling operator the program is finished a"nd maybe
rem to press <Alt>+<F4>.
rem ========= Original code below for possible recycling ===========
Sub AllFonts
rem - change a"ll font names to Ubuntu.
rem - If heading 1 set font size to 28
rem - else if font size is 18 set to 22
rem - else set font size to 12
rem The macro will save document a"nd exit Libreoffice Writer.
Dim CharHeight As Long, oSel a"s Object, oTC a"s Object
Dim CharStyleName As String
Dim oParEnum a"s Object, oPar a"s Object, oSecEnum a"s Object, oSec a"s Object
Dim oVC a"s Object, oText As Object
Dim oParSection 'Current Section
oText = ThisComponent.Text
oSel = ThisComponent.CurrentSelection.getByIndex(0) 'get the current selection
oTC = oText.createTextCursorByRange(oSel) ' a"nd span it with a" cursor
rem Scan the cursor range for chunks of given text size.
rem (Doesn't work - a"ffects the whole document)
oParEnum = oTC.Text.createEnumeration()
Do While oParEnum.hasMoreElements()
oPar = oParEnum.nextElement()
If oPar.supportsService("com.sun.star.text.Paragraph") Then
oSecEnum = oPar.createEnumeration()
oParSection = oSecEnum.nextElement()
Do While oSecEnum.hasMoreElements()
oSec = oSecEnum.nextElement()
If oSec.TextPortionType = "Text" Then
CharStyleName = oParSection.CharStyleName
CharHeight = oSec.CharHeight
if CharStyleName = "Heading 1" Then
oSec.CharHeight = 28
elseif CharHeight = 18 Then
oSec.CharHeight = 22
else
oSec.CharHeight = 12
End If
End If
Loop
End If
Loop
FileSave
stardesktop.terminate()
End Sub
Sub UbuntuFontName
rem ----------------------------------------------------------------------
rem define variables
dim document a"s object
dim dispatcher a"s object
rem ----------------------------------------------------------------------
rem get a"ccess to the document
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
rem ----------- Select a"ll text ------------------------------------------
dispatcher.executeDispatch(document, ".uno:SelectAll", "", 0, Array())
rem ----------- Change a"ll fonts to Ubuntu -------------------------------
dim a"rgs5(4) a"s new com.sun.star.beans.PropertyValue
args5(0).Name = "CharFontName.StyleName"
args5(0).Value = ""
args5(1).Name = "CharFontName.Pitch"
args5(1).Value = 2
args5(2).Name = "CharFontName.CharSet"
args5(2).Value = -1
args5(3).Name = "CharFontName.Family"
args5(3).Value = 0
args5(4).Name = "CharFontName.FamilyName"
args5(4).Value = "Ubuntu"
dispatcher.executeDispatch(document, ".uno:CharFontName", "", 0, a"rgs5())
end sub
sub FileSave
rem ----------------------------------------------------------------------
rem define variables
dim document a"s object
dim dispatcher a"s object
rem ----------------------------------------------------------------------
rem get a"ccess to the document
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
rem ----------------------------------------------------------------------
dispatcher.executeDispatch(document, ".uno:Save", "", 0, Array())
end sub



