Извличане на вградени изображения от Lotus Notes с помощта на lotusscript

Имам някакъв NotesDocument, където някои полета RichText имат както текст, така и вградени изображения. Мога да получа текстова част от тези елементи, но не мога да извлека вградени изображения с помощта на lotusscript. Може ли някой да ми предложи начин за извличане на вградени изображения от тези документи. LotusScript код:

Sub Click(Source As Button)
    Dim session As New NotesSession   
    Dim db As NotesDatabase   
    Dim mainDoc As NotesDocument
    Dim v As NotesView   
    Set db = session.CurrentDatabase   

    Dim fileName As String
    Dim fileNum As Integer
    fileNum% = Freefile()
    fileName$ = "D:\data.txt"
    Open FileName$ For Append As fileNum%

    Set v = db.GetView("MyView")
    Set mainDoc = v.GetFirstDocument       

    While Not ( mainDoc Is Nothing )              
        Forall i In mainDoc.Items
            If i.Type = RICHTEXT Then
                 Write #fileNum% ,    i.Name & ":" & i.text  'how the images??
            End If
        End Forall              
        Set mainDoc = v.GetNextDocument( mainDoc )  
    Wend
End Sub

Благодаря.


person Nazrul    schedule 24.10.2010    source източник
comment
Един от начините, по които успях да го направя навремето, беше като отворя документа чрез HTTP задачата (като уеб страница) и след това можех да изтегля изображенията. Мръсно, но изпълнимо и може би по-лесно от други хакове, в зависимост от вашия опит.   -  person Sam Sirry    schedule 17.01.2021


Отговори (4)


Midas е най-лесният начин да го направите, но не е безплатен. (Повече от струва парите като общо спестено време, но ако вашата организация е нещо подобно на тези, за които съм работил, цялата цена на инструмента ще бъде прехвърлена на единицата за фактуриране, която притежава текущия проект, а по-скоро отколкото да се амортизира за цялата организация и е вероятно да променят изискванията си, преди да се съгласят с разходите.) Има друг подход и той е да експортирате базата данни в DXL (Domino XML), като използвате опцията за експортиране ConvertNotesBitmapToGIF. Изображенията ще се появят в XML като <picture> елементи с данни, кодирани в Base64. Ако работите изцяло в средата на Notes, ще трябва да създадете временен документ с поле с форматиран текст, използвано като NotesMIMEEntity, за да трансформирате кодираната картина в двоична, преди да я стриймвате във файл (чрез NotesStream). Всичко това предполага, че работите с версия 6 или по-нова; ако сте на R5 или по-рано, Midas или директен достъп до CD записите с помощта на C API са единственият начин да летите.

person Stan Rogers    schedule 08.11.2010

Седем години по-късно си скубях косата заради това. Отговорът на Rod H е за прикачени файлове, но вградените изображения са съвсем друго нещо.

Най-големият ми късмет дойде от кода на LotusScript Gold Collection на @andre-guirard, намиращ се тук: https://www.openntf.org/main.nsf/project.xsp?r=project/LotusScript%20Gold%20Collection Това обаче не получава всичко, защото не обработва документи, в които вградените изображения са били вградени по стария начин. (Бележките промениха начина, по който съхранява вградени изображения.)

Опитах се много да го комбинирам с информацията на AGECOM, представена тук: https://www.agecom.com.au/support/agecomkb.nsf/0/58cbf10f0ab723c9ca25803e006c7de8?OpenDocument, като промените обекта EmbeddedImage на Андре, за да работи безпроблемно и с двата формата, като гледате дали вграденото изображение в поле с форматиран текст е всъщност просто указател към поле $FILE и след това, ако е така, получаване на обект FileItem, но в крайна сметка изчерпах разбирането и опциите си до степен, че не можех да оправдая изразходването на ресурсите на моя работодател (моето време) върху него.

Така че, ако имате вградени изображения, които се съдържат по новия начин, мисля, че кодът на Андре ще работи необезпокоявано. Иначе направих всичко възможно, но Нямам отговор... Имам това, което (за мен) е задънена улица, представено с надеждата, че вие ​​или някой друг, който се натъкне на него, можете засрамете ме, като обяснявате какво правя грешно!

По принцип започнах с кода на Андре и го промених по следните начини...

В DOMUtils добавете следния метод:

%REM
    Function DU_GetMeOrNextSiblingWithAttr
    Description: Starting with a particular node, return that node or the next sibling with an attribute that has a particular value.
        Does not recurse into the tree; looks only at the node passed and later siblings. 
    Parameters:
        nodeStart: node to start your search with.
        targetElement: element name of desired node.
        attrName: attribute name you want to check.
        attrValue: attribute value of element you're looking for.
        flags: string-matching flags to compare attribute, e.g. 1 for case insensitive.
%END REM
Function DU_GetMeOrNextSiblingWithAttr(nodeStart As NotesDOMNode, ByVal targetElement$, ByVal attrName$, ByVal attrValue$, ByVal flags%) As NotesDOMElementNode
    Dim node As NotesDOMNode, elTmp As NotesDOMElementNode
    Set node = nodeStart
    Do Until node.Isnull
        If node.Nodetype = DOMNODETYPE_ELEMENT_NODE Then
            If node.Nodename = targetElement Then
                Set elTmp = node
                If StrComp(elTmp.Getattribute(attrName), attrValue, flags) = 0 Then
                    Set DU_GetMeOrNextSiblingWithAttr = elTmp
                    Exit Function
                End If
            End If
        End If
        Set node = node.Nextsibling
    Loop
End Function

Заменете FileItem.New със следния код:

    %REM
    Sub New
    Description: Arguments are the parsed DOM node of the element representing a
        design element, and the name of the composite item you would like to read,
        modify or create.
%END REM
Sub New(parent As FileItemParent, elNote As NotesDOMElementNode, itemName$, fileName$)
    Set m_elNote = elNote
    
    SetItem elNote, itemName$, fileName$
    

    Dim node As NotesDOMNode
    Set node = m_elNote.Parentnode
    While node.Nodetype <> DOMNODETYPE_DOCUMENT_NODE
        Set node = node.Parentnode
    Wend
    Set m_domd = node
    parent.RegisterFileItem Me ' make sure the design element knows about us.
        ' (in case someone gets smart and invokes the constructor directly
        ' instead of using the nice methods we've provided).
End Sub

%REM
    Sub SetItem
<!-- Created Dec 6, 2017 by JSmart523 -->
    If fileName$ is blank, returns the XPath equivalent of elNote/ancestor::document/item[@name=itemName$][position()=1]
    If fileName$ is not blank, returns the XPath equivalent of elNote/ancestor::document/item[@name=itemName$][object/file/@name=fileName$][position()=1]
    
    Case insensitive. Changes itemName$ and fileName$ to the correct case if found.

    Also sets Me.m_elItem to the returned NotesDOMElementNode
    Also sets Me.m_elRawData to the file contents
%END REM
Sub SetItem(elNote As NotesDOMElementNode, itemName$, fileName$)
    Dim elFile As NotesDOMElementNode
    Dim node As NotesDOMNode
    
    'set node to ancestor::document
    Set node = elNote
    Do Until node.NodeName = "document"
        Set node = node.ParentNode
    Loop
    
    'If fileName$ = "", get the first ancestor::document/item[@name=itemName$]
    'Otherwise,         get the first ancestor::document/item[@name=itemName$][/object/file/@name=fileName$]
    Set m_elItem = DU_GetChildOfType(node, DOMNODETYPE_ELEMENT_NODE)
    QualifyingItem m_elItem, itemName$, m_elRawData, fileName$
    m_itemName = itemName$
    m_fileName = fileName$
End Sub

%REM
    Sub QualifyingItem
<!-- Created Dec 8, 2017 by JSmart523 -->
    Starting with incoming elItem node, ensures it's an item we want or changes elItem to the first sibling that qualifies.
%END REM
Sub QualifyingItem(elItem As NotesDOMElementNode, itemName$, elRawData As NotesDOMElementNode, fileName$)
    Dim elFile As NotesDOMElementNode
    Dim node As NotesDOMNode
    Dim elObject As NotesDOMElementNode

    If Not elItem Is Nothing Then
        'Initially, elItem is just a starting point, not necessarily the item we want.
        'If it's an item with the right name, great, otherwise change elItem to the next sibling item with the right name. 
        Set elItem = DU_GetMeOrNextSiblingWithAttr(elItem, "item", "name", itemName$, 1)
        
        If Not elItem Is Nothing Then
            If fileName$ = "" Then
                'we have the right item, and aren't looking for a file node, which means we want the rawitemdata node
                Set elRawData = DU_getChildNamed("rawitemdata", elItem)
            Else
                'We are looking for a $FILE item that contains a file.
                'There are possibly several $FILE items within a document, one for each file. We've got the right one if ./object/file/@name = fileName$
                Do
                    Set elObject = DU_GetChildNamed("object", elItem)
                    If Not elObject Is Nothing Then
                        Set elFile = DU_GetChildWithAttr(elObject, "file", "name", fileName$, 1)
                        If Not elFile Is Nothing Then
                            'Yay! We have the right elItem node!
                            Set elRawData = DU_GetChildNamed("filedata", elFile)
                            fileName$ = elFile.GetAttribute("name")
                            Exit Do
                        End If
                    End If
                    Set elItem = DU_GetMeOrNextSiblingWithAttr(elItem.NextSibling, "item", "name", itemName$, 1)
                Loop Until elItem Is Nothing
                'At this point, either we jumped out of the loop with a valid elItem and elRawData, or elItem is Nothing
            End If
        End If
    End If
    
    If elItem Is Nothing Then
        'we didn't find the correct item
        'make sure elRawData is changed to Nothing, too.
        Set elRawData = Nothing
    Else
        itemName$ = elItem.GetAttribute("name")
    End If
End Sub

Също така в библиотеката със скриптове FileItem добавете нов клас, FileItemParent

    %REM
    Class FileItemParent
<!-- Created Dec 5, 2017 by JSmart523 -->
    This is a base class for objects that use FileItem objects
%END REM
Class FileItemParent
    m_elElRoot As NotesDOMElementNode
    m_elFD As NotesDOMElementNode
    Public m_fileItem As FileItem
    m_fItems List As FileItem ' list of FileItems we've created and returned to caller.
    m_iMode As Integer

    %REM
        Property Get DOMElement
        Description: Return the element node representing the design element.
    %END REM
    Public Property Get DOMElement As NotesDOMElementNode
        Set DOMElement = m_elElRoot
    End Property

    %REM
        Sub New
        Arguments:
            db: the database containing the design element.
            elElement: the DOM element corresponding to the design note (e.g. the <note>
                element).
            domp: The DOM parser object containing elElement.
    %END REM
    Sub New(elElement As NotesDOMElementNode)
        Set m_elElRoot = elElement
    End Sub
    
    Sub Delete
        On Error Resume Next
        ForAll thing In m_fItems
            Delete thing
        End ForAll
    End Sub
    
    %REM
        Function HasItem
        Description: Determine whether there's an item element in the note DXL with a
            given item name.
            Note that the presence of an item doesn't guarantee it's formatted as a file
            CD record.
    %END REM
    Function HasItem(ByVal itemName$) As Boolean
        HasItem = Not (DU_GetChildWithAttr(m_elElRoot, "item", "name", itemName, 1) Is Nothing)
    End Function

    
    %REM
        Function RegisterFileItem
        Description: For internal use -- lets the FileItem class notify us that it's
            referencing our DOM tree so that we can delete the object if we erase the
            corresponding item element.
    %END REM
    Sub RegisterFileItem(x As FileItem)
        Set m_fItems(LCase(x.itemName)) = x
        If m_FileItem Is Nothing Then
            Set m_FileItem = x
        End If
    End Sub
    
    %REM
        Function GetFileItem
        Description: Retrieve the FileItem object associated with a CD-record item.
            An object will be returned even if the item doesn't exist, which you can
            use to create the item via UpdateFile method.
    %END REM
    Function GetFileItem(itemName$, fileName$) As FileItem
        Set GetFileItem = New FileItem(Me, m_elElRoot, itemName, fileName)
    End Function
    
End Class

Класът FileItemParent е предимно код, взет от класа FileResource на Andre, така че и FileResource, и EmbeddedImage да могат да го използват. Променете FileResource, за да разширите FileItemParent, като премахнете всеки дублиран код.

Сега искаме да променим EmbeddedImage, така че дори възелът на вграденото изображение да съдържа връзка към $FILE елемент, а не действителното съдържание, да върне действителното съдържание.

Така че, променете EmbeddedImage, за да разширите FileItemParent

Добавете/заменете следните методи към EmbededImage

%REM
    Sub InitFileItem
<!-- Created Dec 6, 2017 by JSmart523 -->
    Called by New
%END REM
Sub InitFileItem()
    Dim buffer As Variant 'byte array
    Dim iFileNameLen As Integer
    Dim sFileName As String
    Dim sItemName As String
    Dim stream As NotesStream
    
    If Len(m_b64) < 30000 Then
        'If content is short then maybe it's a link to a $FILE item instead of the actual content?
        Dim session As New NotesSession
        Set stream = session.CreateStream()
        Base64ToBinary m_b64, stream
        stream.Position = 0
        buffer = stream.Read(1)
        If buffer(0) = 196 Then
            'this is a link to a $FILE, not the actual image contents!
            
            stream.Position = 10
            buffer = stream.Read(2)
            iFileNameLen = ConvertWordByteArray(buffer)
            
            stream.Position = 24
            buffer = stream.Read(iFileNameLen)
            sFileName = BytesToString(buffer)
            sItemName = "$FILE"
            
            GetFileItem sItemName, sFileName 'sets m_fileItem to a FileItem object
        End If
    End If
End Sub

%REM
    Property Get SuggestedFileName
%END REM
Public Property Get SuggestedFileName As String
    If m_fileItem Is Nothing Then
        SuggestedFileName = "Embedded-" + ItemName + "." + SuggestedFileType
    Else
        SuggestedFileName = m_fileItem.FileName
        If InStr(SuggestedFileName, ".") = 0 Then
            SuggestedFileName = SuggestedFileName + "." + SuggestedFileType
        End If
    End If
End Property

%REM
    Property Get SuggestedFileType
%END REM
Public Property Get SuggestedFileType As String
    If ImageType = "notesbitmap" Then
        SuggestedFileType = "bmp"
    Else
        SuggestedFileType = ImageType
    End If
End Property

%REM
    Sub ReadFileToStream
%END REM
Sub ReadFileToStream(streamOut As NotesStream)
    If m_FileItem Is Nothing Then
        ReadToStream streamOut
    Else
        Set m_FileItem.Stream = streamOut
        m_FileItem.Load
    End If
End Sub

и след това променете EmbeddedItem.New, за да накрая извикате InitFileItem, така че ако това е връзка, получаването на съдържанието връща съдържанието, а не връзката.

Добре, дотук добре, доколкото знам, но проблемът е, че CD записи на вградени изображения, съхранени в $FILE елементи (т.е. възелът на вграденото изображение на полето с богат текст просто съдържа връзка, а не действителното изображение) са/са документирани по начин, който за мен беше непроницаем, въпреки кода и обясненията на AGECOM. Бих могъл да използвам горния код и обекта EmbeddedImageList на Андре, за да взема всяко едно вградено изображение, но просто не можах да накарам метода ConvertOldCDToNew да работи, така че не можах да конвертирам стария формат на CD Record в твърди, неповредени файлове! Не знам дали премахвах твърде много байтове, не премахвах правилните, или може би просто забравих да нося двете!

person JSmart523    schedule 22.01.2018

Предлагам ви да разгледате продукта Genii Software MidasLSX. Те предлагат пакет от разширения на LotusScript, които улесняват справянето със сложността на елементите с богат текст на Lotus Notes.

http://www.geniisoft.com/showcase.nsf/MidasHelp

В противен случай можете да експериментирате с класа NotesRichTextNavigator, за да получите достъп до изображението в елемента с форматиран текст (на теория). Има много малко документация за подобни неща. Не можех да кажа точно какво изображение ще изглежда като използвайки този клас, но ако приемем, че навигирате през елемента с форматиран текст и сте в състояние да управлявате изображението като NotesEmbeddedObject, знам, че има начин да запишете обекта на диск от този клас.

Друга (луда) мисъл е да изпратите документа по имейл и той да бъде получен от друга програма, която може по-лесно да обработва тялото на имейла. Бележките просто не са много полезни при обработката на собствените си полета с форматиран текст.

person Ken Pespisa    schedule 25.10.2010

Ето агент, който използвам за отделяне на файлове от поле с богат текст на моите документи.

Option Public
Dim uidoc As notesuidocument
Dim doc As NotesDocument
Dim db As NotesDatabase
Dim obj As NotesEmbeddedObject
Dim collection As NotesDocumentCollection
Dim rt As Variant
Dim attachNames As Variant
Dim i As Integer, x As Integer
Dim j As Integer
' Agent  - Detach Attachments to C drive for later reattachment
' Copies all attachment in richtext field to personal directory.

Sub Initialize
    Dim ws As New notesuiworkspace
    Dim ses As New NotesSession
    Set db = ses.CurrentDatabase
    Set collection = db.UnprocessedDocuments
    '  get first doc in collection
    For j = 1 To collection.Count
        Set doc = collection.GetNthDocument( j )    
' ---  create array of filenames of all the attachments in the document
        i = 0
        Redim attachNames(i)
        Forall x In doc.items
            If x.name = "$FILE" Then
                attachNames(i) = x.values(0)
                i = i + 1
                Redim Preserve attachNames(i)
            End If
        End Forall

        If i > 0 Then
            Redim Preserve attachNames(i-1)
        End If

' ---  for all of the filenames in attachNames, if it exists in the rich text field, detatch them
        If doc.hasItem("richtextfieldname") Then
            Set rt = doc.GetFirstItem("richtextfieldname")
        End If
        If attachNames(0) <> "" Then
            Forall x In attachNames 
                Set obj = rt.GetEmbeddedObject( x )
                If Not( obj Is Nothing ) Then
                    Call obj.ExtractFile( "C:\path\" & Cstr(x) )
                End If
            End Forall
        End If
        Call doc.save(True, False)
    Next
End Sub
person Rod H    schedule 05.12.2012