[Solved] View cursor not jumping to correct positions

Creating a macro - Writing a Script - Using the API (OpenOffice Basic, Python, BeanShell, JavaScript)
Post Reply
sureanem
Posts: 3
Joined: Fri Nov 23, 2018 7:31 pm

[Solved] View cursor not jumping to correct positions

Post by sureanem »

Hello all,
I'm trying to break up an .odt in multiple .pdfs by specifying with markers where one pdf should end and the next one should start. The trouble is, I can't seem to make them to start and end at the correct locations. The first pdf exports just fine, but the second one overshoots and exports some of the text after the marker. Tried searching for similar macros to no avail.

I suspect the reason is somewhere in this part of the code:

Code: Select all

Sub exportSectionToPDF(startMarker, endMarker, suffix, doctextarg)
	if len(ThisComponent.getURL())=0 then
		msgbox "Please save first"
		exit sub
	end if
	If (Not GlobalScope.BasicLibraries.isLibraryLoaded("Tools")) Then GlobalScope.BasicLibraries.LoadLibrary("Tools")
	sPath = convertfromurl(DirectoryNameoutofPath(ThisComponent.getURL(),"/"))
	sName = convertfromurl(GetFileNameWithoutExtension(ThisComponent.getURL(),"/"))
	
	dim oVC as Object
	oVC = ThisComponent.CurrentController.getViewCursor()
	dim startpdf, endpdf
	startpdf = InStr(doctextarg, startMarker) - 1
	endpdf = InStr(doctextarg, endMarker) '- len(endMarker)

	oVC.JumpToFirstPage(false)
	oVC.gotoStart(false)
	oVC.goRight(startpdf, false)
	oVC.goRight(endpdf - startpdf, true)
	doctext = oVC.String
	msgbox("3 first page, start " & doctext)
	
	saveaspdf(sPath,sName & suffix)
End Sub
And here's all the code just in case:

Code: Select all

Sub testExport
	dim oVC as Object
	dim doctext
	oVC = ThisComponent.CurrentController.getViewCursor()
	oVC.JumpToFirstPage(false)
	oVC.JumpToStartOfPage(false)
	oVC.gotoStart(false)
	oVC.gotoEnd(true) 
	doctext = oVC.String
	exportSectionToPDF("@p1m", "@p2m", " - first part", doctext)
	exportSectionToPDF("@p2m", "@p3m", " - second part", doctext)
End Sub

Sub exportSectionToPDF(startMarker, endMarker, suffix, doctextarg)
	if len(ThisComponent.getURL())=0 then
		msgbox "Please save first"
		exit sub
	end if
	If (Not GlobalScope.BasicLibraries.isLibraryLoaded("Tools")) Then GlobalScope.BasicLibraries.LoadLibrary("Tools")
	sPath = convertfromurl(DirectoryNameoutofPath(ThisComponent.getURL(),"/"))
	sName = convertfromurl(GetFileNameWithoutExtension(ThisComponent.getURL(),"/"))
	
	dim oVC as Object
	oVC = ThisComponent.CurrentController.getViewCursor()
	dim startpdf, endpdf
	startpdf = InStr(doctextarg, startMarker) - 1
	endpdf = InStr(doctextarg, endMarker) '- len(endMarker)

	oVC.JumpToFirstPage(false)
	oVC.gotoStart(false)
	oVC.goRight(startpdf, false)
	oVC.goRight(endpdf - startpdf, true)
	doctext = oVC.String
	msgbox("3 first page, start " & doctext)
	
	saveaspdf(sPath,sName & suffix)
End Sub

Sub saveaspdf(sPath,sName)
	oselection=thiscomponent.getcurrentselection
	Dim aFilterData(0) as new com.sun.star.beans.PropertyValue
	aFilterData(0).Name = "Selection"
	aFilterData(0).Value = oselection

	Dim args3(1) as new com.sun.star.beans.PropertyValue
	args3(0).Name = "FilterName"
	args3(0).Value = "writer_pdf_Export"
	args3(1).Name = "FilterData"
	args3(1).Value = aFilterData

	thiscomponent.storeToURL(converttourl(sPath & getpathseparator & sName & ".pdf"),args3())
End Sub
OO Version and OS:

Code: Select all

OpenOffice 4.1.5
AOO415m1(Build:9789) - Rev. 1817496
2017-12-11 15:46 - Linux x86_64
Ubuntu 16.04 LTS
Last edited by sureanem on Sat Nov 24, 2018 9:48 pm, edited 2 times in total.
OpenOffice 4.1.5
AOO415m1(Build:9789) - Rev. 1817496
2017-12-11 15:46 - Linux x86_64

Ubuntu 16.04 LTS
John_Ha
Volunteer
Posts: 9584
Joined: Fri Sep 18, 2009 5:51 pm
Location: UK

Re: View cursor not jumping to correct positions (odt to pdf

Post by John_Ha »

If you can put page breaks in where you want the document to be split you can use something like PDFSAM (PDF Split and Merge) to chop the PDF as required.
LO 6.4.4.2, Windows 10 Home 64 bit

See the Writer Guide, the Writer FAQ, the Writer Tutorials and Writer for students.

Remember: Always save your Writer files as .odt files. - see here for the many reasons why.
sureanem
Posts: 3
Joined: Fri Nov 23, 2018 7:31 pm

Re: View cursor not jumping to correct positions (odt to pdf

Post by sureanem »

I can and was doing something similar. The issue is that there are a few patterns of exports to around 10 ~ 20 pdfs and instead of taking 20-something minutes to manually set up the conversion, I could do that with the click of a button. It's a process ripe for automation.
OpenOffice 4.1.5
AOO415m1(Build:9789) - Rev. 1817496
2017-12-11 15:46 - Linux x86_64

Ubuntu 16.04 LTS
musikai
Volunteer
Posts: 294
Joined: Wed Nov 11, 2015 12:19 am

Re: View cursor not jumping to correct positions (odt to pdf

Post by musikai »

The problem may be that the value you get from instr() can't be used for goRight() because if you have fields like "Author" the cursor jumps over them with 1 goRight.
Here is an alternative. Only "exportSectionToPDF" is edited and "save_as_pdf" is renamed to "save_selection_as_pdf":

Code: Select all

Sub testExport
   dim oVC as Object
   dim doctext
   oVC = ThisComponent.CurrentController.getViewCursor()
   oVC.JumpToFirstPage(false)
   oVC.JumpToStartOfPage(false)
   oVC.gotoStart(false)
   oVC.gotoEnd(true)
   doctext = oVC.String
   exportSectionToPDF("@p1m", "@p2m", " - first part", doctext)
   exportSectionToPDF("@p2m", "@p3m", " - second part", doctext)
End Sub

Sub exportSectionToPDF(startMarker, endMarker, suffix, doctextarg)
   if len(ThisComponent.getURL())=0 then
      msgbox "Please save first"
      exit sub
   end if
   If (Not GlobalScope.BasicLibraries.isLibraryLoaded("Tools")) Then GlobalScope.BasicLibraries.LoadLibrary("Tools")
   sPath = convertfromurl(DirectoryNameoutofPath(ThisComponent.getURL(),"/"))
   sName = convertfromurl(GetFileNameWithoutExtension(ThisComponent.getURL(),"/"))
   
oViewCursor = ThisComponent.CurrentController.getViewCursor()

 	oCurs = ThisComponent.getText().createTextCursor()
	oCurs.GoToStart(False)

	Do 
	oCurs.goright(len(startMarker),true)
	if oCurs.string=startMarker then exit do
	oCurs.collapseToStart()
	loop while oCurs.goright(1,False)
	oCurs.collapseToEnd()
	oViewCursor.gotoRange(oCurs, false)
	
	Do 
	oCurs.goright(len(endMarker),true)
	if oCurs.string=endMarker then exit do
	oCurs.collapseToStart()
	loop while oCurs.goright(1,False)
	oCurs.collapseToStart()
	oViewCursor.gotoRange(oCurs, true)

   
   save_selection_as_pdf(sPath,sName & suffix)
End Sub


Sub save_selection_as_pdf(sPath,sName)
oselection=thiscomponent.getcurrentselection
Dim aFilterData(0) as new com.sun.star.beans.PropertyValue
aFilterData(0).Name = "Selection"
aFilterData(0).Value = oselection

Dim args3(1) as new com.sun.star.beans.PropertyValue
args3(0).Name = "FilterName"
args3(0).Value = "writer_pdf_Export"
args3(1).Name = "FilterData"
args3(1).Value = aFilterData
thiscomponent.storeToURL(converttourl(sPath & getpathseparator & sName & ".pdf"),args3())

End Sub
Win7 Pro, Lubuntu 15.10, LO 4.4.7, OO 4.1.3
Free Project: LibreOffice Songbook Architect (LOSA)
http://struckkai.blogspot.de/2015/04/li ... itect.html
John_Ha
Volunteer
Posts: 9584
Joined: Fri Sep 18, 2009 5:51 pm
Location: UK

Re: View cursor not jumping to correct positions (odt to pdf

Post by John_Ha »

sureanem wrote:I'm trying to break up an .odt in multiple .pdfs by specifying with markers where one pdf should end and the next one should start.
Or break the .odt into several .odt files as required, and export each of the full documents to a PDF.

Or make a selection and print it to a PDF Virtual Printer like PrimoPDF.
LO 6.4.4.2, Windows 10 Home 64 bit

See the Writer Guide, the Writer FAQ, the Writer Tutorials and Writer for students.

Remember: Always save your Writer files as .odt files. - see here for the many reasons why.
User avatar
Lupp
Volunteer
Posts: 3549
Joined: Sat May 31, 2014 7:05 pm
Location: München, Germany

Re: View cursor not jumping to correct positions (odt to pdf

Post by Lupp »

Don't tamper with Text.String. (It is limited to 65535 characters in AOO anyway.) Use bookmarks instead of inserted text.
Rough sketch:

Code: Select all

Sub exportAllBookmarkedPartsToPdf()
doc0         = ThisComponent
bkms         = doc0.BookMarks
For k = 0 To bkms.Count - 1 REM The bookmarks container is not enumerable.
  suppBkmStart = bkms(k)
  If NOT (suppBkmStart.Anchor.Text.ImplementationName="SwXBodyText") Then Goto next_k
  bkmNameS     = suppBkmStart.Name 
  If Instr(bkmNameS, "pdfStart")=1 Then
    pdfStart     = suppBkmStart.Anchor
    num          = Mid(bkmNameS, Len("pdfStart") + 1, 99)
    bkmNameE     = "pdfEnd" & num
    If foundByName(bkms, bkmNameE, bkmEnd) Then
      pdfEnd       = bkmEnd.Anchor
      REM Now we have two TextRange objects delimiting the range to export.
      REM For both these ranges .Start=.End should hold.
      ExportToPdf(pdfStart, pdfEnd)
    End If
  End If
next_k:
Next k
End Sub

Sub exportToPdf(p1, p2)
REM Dummy! Only for visualisation in an example.
tC = ThisComponent.Text.CreateTextCursorByRange(p1.Start)
tC.GotoRange(p2.End, True)
ThisComponent.CurrentController.Select(tC)
End Sub

Function foundByName(ByRef pContainer As Object, pName As String, ByRef pFound) As Boolean
foundByName  = False
On local Error Goto lErrorExit
pFound = pContainer.GetByName(pName)
foundByName  = True
lErrorExit:
End Function
===Adding my test file===
Attachments
aoo95992ExportPortions_1.odt
(30.64 KiB) Downloaded 112 times
On Windows 10: LibreOffice 24.2 (new numbering) and older versions, PortableOpenOffice 4.1.7 and older, StarOffice 5.2
---
Lupp from München
sureanem
Posts: 3
Joined: Fri Nov 23, 2018 7:31 pm

Re: View cursor not jumping to correct positions (odt to pdf

Post by sureanem »

Thank you all. Decided to use the bookmark approach, just in case I deal with longer documents. I needed to add only little modifications to the code provided to suit my needs.

I wished I could see the bookmarks in the text, but that's not a deal breaker.
OpenOffice 4.1.5
AOO415m1(Build:9789) - Rev. 1817496
2017-12-11 15:46 - Linux x86_64

Ubuntu 16.04 LTS
User avatar
RoryOF
Moderator
Posts: 34613
Joined: Sat Jan 31, 2009 9:30 pm
Location: Ireland

Re: [Solved] View cursor not jumping to correct positions

Post by RoryOF »

There is an extension to make bookmarks visible at
Visible Bookmarks

In spite of the not updated warning, it worked for me on recent versions of OIO.
Apache OpenOffice 4.1.15 on Xubuntu 22.04.4 LTS
musikai
Volunteer
Posts: 294
Joined: Wed Nov 11, 2015 12:19 am

Re: View cursor not jumping to correct positions (odt to pdf

Post by musikai »

sureanem wrote:Thank you all. Decided to use the bookmark approach, just in case I deal with longer documents. I needed to add only little modifications to the code provided to suit my needs.

I wished I could see the bookmarks in the text, but that's not a deal breaker.
The warning by Lupp doesn't apply to my code (in case you want to use your system with the "@p1m"-markers)
Win7 Pro, Lubuntu 15.10, LO 4.4.7, OO 4.1.3
Free Project: LibreOffice Songbook Architect (LOSA)
http://struckkai.blogspot.de/2015/04/li ... itect.html
JeJe
Volunteer
Posts: 2780
Joined: Wed Mar 09, 2016 2:40 pm

Re: [Solved] View cursor not jumping to correct positions

Post by JeJe »

If you used Text Sections you could see where each part was.
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
User avatar
RoryOF
Moderator
Posts: 34613
Joined: Sat Jan 31, 2009 9:30 pm
Location: Ireland

Re: [Solved] View cursor not jumping to correct positions

Post by RoryOF »

I use many OpenOffice sections; I find it helpful, when defining a section to add a unique background colour for each section (/Format /Sections : Options: Background)
Apache OpenOffice 4.1.15 on Xubuntu 22.04.4 LTS
User avatar
Lupp
Volunteer
Posts: 3549
Joined: Sat May 31, 2014 7:05 pm
Location: München, Germany

Re: [Solved] View cursor not jumping to correct positions

Post by Lupp »

@musikai:
musikai wrote:The warning by Lupp doesn't apply to my code (in case you want to use your system with the "@p1m"-markers)
Well, I may have failed to study the code thoroughly enough. However, it works with a variably getting the assignment
doctext = oVC.String
I was not sure for what reason the VC was used (by the OP and then by you), but if the viewcursor includes sufficiently large ranges the oVC.String can have arbitrary length. AOO API returns an empty string in such a case if there are more than 2^16-1 characters.
In addition the oVC.String is empty if the VC is based on a multiselection. In this case the .Text property of the VC is the text object of the last selected part, and can thus be the text of a TextFrame.

@sureanem
sureanem wrote:I wished I could see the bookmarks in the text, but that's not a deal breaker.
I hesitated if I should work with zero-length-ranges for the bookmarks, and then decided to do so. You can also set your bookmarks to include the marking text pieces you want. They will not be highlighted by default.
The new demo includes a (just sketched) macro for setting a bookmark on a single selection and using the string of the selected range as name of the bookmark. Type "@p1m" e.g., doubleclick on the 'word' and call the macro via a shortcut - if you need that really often.
Attachments
aoo95992ExportPortions_2.odt
(31.57 KiB) Downloaded 124 times
On Windows 10: LibreOffice 24.2 (new numbering) and older versions, PortableOpenOffice 4.1.7 and older, StarOffice 5.2
---
Lupp from München
musikai
Volunteer
Posts: 294
Joined: Wed Nov 11, 2015 12:19 am

Re: [Solved] View cursor not jumping to correct positions

Post by musikai »

Lupp wrote:@musikai:
musikai wrote:The warning by Lupp doesn't apply to my code (in case you want to use your system with the "@p1m"-markers)
Well, I may have failed to study the code thoroughly enough. However, it works with a variably getting the assignment
doctext = oVC.String
I was not sure for what reason the VC was used (by the OP and then by you), ...
Ah, ok. My code-modification doesn't make use of that passed "doctext", but I was too lazy to tidy up all OP's code.
Win7 Pro, Lubuntu 15.10, LO 4.4.7, OO 4.1.3
Free Project: LibreOffice Songbook Architect (LOSA)
http://struckkai.blogspot.de/2015/04/li ... itect.html
Post Reply