Transform text from string to image

1
Hello, I'm developing an app, and at some point I need to get a string that contains data from a voucher and turn that text into an image of the voucher and then share that image via whatsapp. I've never done anything like that and after some time researching I have not come up with a satisfactory solution. The voucher would have the format below:

  

"##########################
Central Games
############ ##############
Bookmaker: test
Amount Bet: R $ 5
Return Value: R $ 6.15
Bet on: 02/21/2017 15:07
Matches Matches: 1
--------------------------------------- -
Vasco X Flamengo
Draw: 1.23
10/03/2017 15:30
= =
Currency Converter: Currency Converter Test Phone: (82) 9977-8877 "

    
asked by anonymous 19.02.2017 / 19:26

2 answers

3

You can use the canvas element to generate the image, as in the example below:

var canvas = document.getElementById("receipt");
var context = canvas.getContext("2d");

const messages = [
  "################################",
  "Central Jogos",
  "################################",
  "Apostador: test",
  "Valor apostado: R$ 5,00",
  "Valor de retorno: R$ 6,15",
  "Data da aposta: 19/02/2017 15:07",
  "Quantidade de jogos: 1",
  "--------------------------------",
  "Vasco X Flamengo",
  "Empate: 1.23",
  "10/03/2017 15:30",
  "================================",
  "Cambista: Cambista Teste",
  "Telefone: (82) 9977-8877"
];

context.font = "12px Courier new";

y = 12;
for (var i in messages) {
  context.fillText(messages[i], 0, y);
  y += 18;
}

document.getElementById("result").src = context.canvas.toDataURL();
h1 {
  font-size: 16px
}

div {
  float: left;
  padding: 20px;
}
<div>
  <h1>Canvas:</h1>
  <canvas id="receipt" width="230" height="270"></canvas>
</div>
<div>
  <h1>Resultado:</h1>
  <img id="result" alt="Receipt" />
</div>
  

Note : Running the above code will output the console output in data:image/png;base64,... format. To test, you can copy this message and paste directly into the browser. If all went well, you'll see the receipt image in PNG format.

Basically it is a list with messages, which can be generated dynamically. The canvas element and its context is set, defined as the Courier New 12px source, because it is monospace and it generates a better result visually, traversed the list and added to the canvas at the (0, y) position, where y is incremented by 18 to maintain a small spacing between the lines. At the end, it recovers the value of context.canvas.toDataURL which is nothing more than the generated image.

However, I owe you how to send it to WhatsApp, as this has already come to my attention. If anyone knows and would like to edit the answer, feel free to do so.

    
19.02.2017 / 20:17
0

The first part of my question was answered by Anderson, already the part of sending base64 to WhatsApp I found the solution with the phonegap plugin Social Sharing . You can share PDF, image, links and etc.

    
23.02.2017 / 02:33