How to create file from byte array and send it to TelegramBot

Viewed 576

In Service1 I create a byte array and send it to Kafka.

In Service2 I receive a message from Service1, create a PDF file using this byte array and send it to TelegramBot, which sends it to the user.

Service 1

And that's how I send a byte array to Kafka

byte[] file = _pdfBuilder
.AddObject(o =>
{
o.HtmlContent = html;
})
.Convert();

var result = await producer.ProduceAsync(_producerTopic, new Message<Null, string>()
{
Value = Encoding.Unicode.GetString(file)
}, cancelToken.Token);

Service 2

That's how I tried to create PDF file and send it to Telegram Bot

using (var fs = new FileStream("FileName.pdf", FileMode.Create))
{
    foreach (var bt in bytes)
    {
        fs.WriteByte(bt);
    }

    fs.Seek(0, SeekOrigin.Begin);
    var document = new InputOnlineFile(fs, "file.pdf");
    await _client.SendDocumentAsync(id, document);
}

Or this

await using var memoryStream = new MemoryStream(bytes);
var doc = new InputOnlineFile(memoryStream, "file.pdf");
await _client.SendDocumentAsync(id, doc);

Or

var memoryStream = new MemoryStream(bytes);
var doc = new InputOnlineFile(memoryStream, "file.pdf");
await _client.SendDocumentAsync(id, doc);

So the problem is: in a chat with Telegram Bot I receive an empty PDF file.

That's also how I used to create a file in the controller (the file wasn't empty)

 byte[] file = _pdfBuilder
                .AddObject(o =>
                {
                    o.HtmlContent = html;
                })
                .Convert();

 return File(file, "application/pdf");
1 Answers

Unicode encoding and decoding breaks the pdf file.
If you need send file as string use Base64 convert

var byteArray = new byte[] {1,2,3,4,5,6,7,8,9};
var encString = System.Convert.ToBase64String(byteArray);
var decBytes = System.Convert.FromBase64String(encString);
//result: byte[9] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }
Related