Jump to content

Copy Text from the dbgrid column to Clipboard


Fábio Matte

Recommended Posts

I need to copy the text that was selected in the UnidbGrid, through the option of a PopUp menu.
I am using the following code:

var
   col: Integer;
   TextCopy: string;
begin
   col: = gridSenhasLiberadas.CurrCol;
   Clipboard.AsText: = gridSeedLibrary.Columns.Items [col] .Field.AsString;
   TextCopy: = Clipboard.AsText;

If I give a ShowMessage, I see the Clipboard, however I can not paste it anywhere else.
Apparently it's not on the clipboard.

How do I then get that dbGrid value and actually put it in the clipboard through a popup menu?

Link to comment
Share on other sites

37 minutes ago, Fábio Matte said:

If I give a ShowMessage, I see the Clipboard, however I can not paste it anywhere else.

Hi,

You are using "Uses Clipbrd", It works on the server side, not on the client.

You need JS solution.

Please try to search on the forum.

Link to comment
Share on other sites

6 minutes ago, Sherzod said:

Hi,

You are using "Uses Clipbrd", It works on the server side, not on the client.

You need JS solution.

Please try to search on the forum.

As I speak Portuguese, I already researched several terms but I could not reach a link to help me.
Is there a forum link to tell me or give me a direction?

Link to comment
Share on other sites

  • 2 years later...
  • 10 months later...
  • 4 months later...
  • 2 months later...

 

Hello, I have the following code to paste an image from the clipboard. It works perfectly, but I can't copy the image to a file on the server. I don't know JS, so I appreciate any help you can give me.

 

<script>

function retrieveImageFromClipboardAsBlob(pasteEvent, callback){
    if(pasteEvent.clipboardData == false){
        if(typeof(callback) == "function"){
            callback(undefined);
        }
    };

    var items = pasteEvent.clipboardData.items;

    if(items == undefined){
        if(typeof(callback) == "function"){
            callback(undefined);
        }
    };

    for (var i = 0; i < items.length; i++) {
        // Skip content if not image
        if (items[i].type.indexOf("image") == -1) continue;
        // Retrieve image on clipboard as blob
        var blob = items[i].getAsFile();

        if(typeof(callback) == "function"){
            callback(blob);
        }
    }
}

window.addEventListener("paste", function(e){

    // Handle the event
    retrieveImageFromClipboardAsBlob(e, function(imageBlob){
        // If there's an image, display it in the canvas
        if(imageBlob){
            var canvas = document.getElementById("mycanvas");
            var ctx = canvas.getContext('2d');
            
            // Create an image to render the blob on the canvas
            var img = new Image();

            // Once the image loads, render the img on the canvas
            img.onload = function(){
                // Update dimensions of the canvas with the dimensions of the image
                canvas.width = this.width;
                canvas.height = this.height;

                // Draw the image
                ctx.drawImage(img, 0, 0);
            };

            // Crossbrowser support for URL
            var URLObj = window.URL || window.webkitURL;

            // Creates a DOMString containing a URL representing the object given in the parameter
            // namely the original Blob
            img.src = URLObj.createObjectURL(imageBlob);
            
            //
            // Generar un archivo y grabarlo en disco
            //
            // Obtener el src de la imagen              
            var src = img.src;
            // Crear un elemento <a>
            var a = document.createElement("a");
            // Crear una URL para el src
            var url = window.URL.createObjectURL(src);
            // Asignar la URL al atributo href del elemento <a>
            a.href = url;
            // Asignar el nombre del archivo al atributo download del elemento <a>
            a.download = "C:\TEMP\imagen.jpg";
            // Añadir el elemento <a> al documento
            document.body.appendChild(a);
            // Simular un clic en el elemento <a>
            a.click();
            // Remover el elemento <a> del documento
            document.body.removeChild(a);

        }
    });
}, false);


</script>  

<p>
Focus this tab and press <kbd>CTRL</kbd> + <kbd>V</kbd>. The image on your clipboard will be rendered on the canvas !
</p>

<canvas style="border:1px solid grey;" id="mycanvas">

Link to comment
Share on other sites

An apology for the writing format. I have tried with ajaxRequest and other options, but I have not been able to get the image file to be generated and saved to the local disk. What I want to do is retrieve the image copied to the Clipboard and save it to the DB.
Link to comment
Share on other sites

I want to save in a DB an image that was previously copied to the clipboard of the client's browser.

I have a uniHTMLFrame where I put the code to do the Paste from Clipboard.

This code to make the Paste works OK.

The part of the code in bold is the one that does NOT work for me. This part is the one with which I intend to record the image I get in img.src on the server's local disk.

With the image saved on the server, I intend to upload it to the DB later.

Link to comment
Share on other sites

A tip for those who want to copy text with few codes, I believe this could be implemented natively in unigui

ServerModule -> CustomMeta

<script language="JavaScript">

function addslashes(str) {
    return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
};

async function copyText(texto) {
    try {
        await navigator.clipboard.writeText(texto);
    } catch (err) {
        console.error('Failed to copy: ', err);
    }
};

async function pasteText(jsName) {
    navigator.clipboard.readText().then(texto => {
        let txt = addslashes(texto);
        txt = txt.replace(/(?:\r\n|\r|\n)/g, '\\n');
        let cmd = jsName + ".setValue('" + txt + "');";
        eval(cmd);
    });
};
</script>
procedure TUniMainModule.Copy(Control : TUniFormControl; MsgSucess : Boolean);
begin
  var lTexto := String(Control.Text);
  Self.CopyStr(lTexto, MsgSucess);
end;

procedure TUniMainModule.CopyStr(Text: String; MsgSucess: Boolean);
begin
  try
    var lTexto := TStringUtils.JsEncode(Text);
    var lJsString := 'copyText(' + QuotedStr(lTexto) + ');';

    UniSession.JSCode(lJsString);

    if MsgSucess then
      TToastUtils.Sucess('Copiado!',True,'Sucesso',1000);
  except
    on E: Exception do
      TMessageUtils.Error(E.Message);
  end;
end;

procedure TUniMainModule.Paste(Control : TUniFormControl);
begin
  try
    var lJsName := Control.JSName;
    var lJsString := 'pasteText(' + QuotedStr(lJsName) + ');';
    UniSession.JSCode(lJsString);
  except
    on E: Exception do
      TMessageUtils.Error(E.Message);
  end;
end;
class function TStringUtils.JsEncode(const Src: String; const useNumericReference: boolean): String;
var
  i, l: integer;
  Buf, P: PAnsiChar;
  ch: integer;
begin
  Result := '';

  l := Length(Src);

  if l = 0 then Exit;

  if useNumericReference then
    GetMem(Buf, l * 6) // to be on the *very* safe side
  else
    GetMem(Buf, l * 2); // to be on the *very* safe side

  try
    P := Buf;
    for i := low(Src) to high(Src) do
    begin
      ch := Ord(Src[i]);
      case ch of
        8:
          begin // Backspace
            if useNumericReference then
            begin
              ALStrMove('\u0008', P, 6);
              Inc(P, 6);
            end
            else
            begin
              ALStrMove('\b', P, 2);
              Inc(P, 2);
            end;
          end;
        9:
          begin // Tab
            if useNumericReference then
            begin
              ALStrMove('\u0009', P, 6);
              Inc(P, 6);
            end
            else
            begin
              ALStrMove('\t', P, 2);
              Inc(P, 2);
            end;
          end;
        10:
          begin // New line
            if useNumericReference then
            begin
              ALStrMove('\u000A', P, 6);
              Inc(P, 6);
            end
            else
            begin
              ALStrMove('\n', P, 2);
              Inc(P, 2);
            end;
          end;
        11:
          begin // Vertical tab
            if useNumericReference then
            begin
              ALStrMove('\u000B', P, 6);
              Inc(P, 6);
            end
            else
            begin
              ALStrMove('\v', P, 2);
              Inc(P, 2);
            end;
          end;
        12:
          begin // Form feed
            if useNumericReference then
            begin
              ALStrMove('\u000C', P, 6);
              Inc(P, 6);
            end
            else
            begin
              ALStrMove('\f', P, 2);
              Inc(P, 2);
            end;
          end;
        13:
          begin // Carriage return
            if useNumericReference then
            begin
              ALStrMove('\u000D', P, 6);
              Inc(P, 6);
            end
            else
            begin
              ALStrMove('\r', P, 2);
              Inc(P, 2);
            end;
          end;
        34:
          begin // Double quote
            if useNumericReference then
            begin
              ALStrMove('\u0022', P, 6);
              Inc(P, 6);
            end
            else
            begin
              ALStrMove('\"', P, 2);
              Inc(P, 2);
            end;
          end;
        38:
          begin // & ... we need to encode it because in javascript &#39; or &amp; will be converted to ' and error unterminated string
            ALStrMove('\u0026', P, 6);
            Inc(P, 6);
          end;
        39:
          begin // Apostrophe or single quote
            if useNumericReference then
            begin
              ALStrMove('\u0027', P, 6);
              Inc(P, 6);
            end
            else
            begin
              ALStrMove('\''', P, 2);
              Inc(P, 2);
            end;
          end;
        60:
          begin // < ... mostly to hide all </script> tag inside javascript.
            // http://www.wwco.com/~wls/blog/2007/04/25/using-script-in-a-javascript-literal/
            ALStrMove('\u003C', P, 6);
            Inc(P, 6);
          end;
        62:
          begin // > ... mostly to hide all HTML tag inside javascript.
            ALStrMove('\u003E', P, 6);
            Inc(P, 6);
          end;
        92:
          begin // Backslash character (\).
            if useNumericReference then
            begin
              ALStrMove('\u005C', P, 6);
              Inc(P, 6);
            end
            else
            begin
              ALStrMove('\\', P, 2);
              Inc(P, 2);
            end;
          end;
      else
        Begin
          P^ := AnsiChar(ch);
          Inc(P);
        end;
      end;
    end;
    SetString(Result, Buf, P - Buf);
  finally
    FreeMem(Buf);
  end;
end;





 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...