Search code examples
pythonpython-3.xdiscorddiscord.py

discord.py - Sending virtual PDF file


Is there any way to upload a virtual PDF file onto Discord (I do not want files to be created on my computer). I already know I can send virtual txt files with io.StringIO like this:

import discord, asyncio
from discord.ext import commands
from io import StringIO

bot = commands.Bot()

@bot.command()
async def send(ctx, *, string):
    await ctx.send(file=discord.File(
        fp=StringIO("This is a test"),
        filename="Test.txt"
    )

But this doesn't work with PDF files. I tried using io.BytesIO instead but I got no result. Does anyone please know how to solve this problem?


Solution

  • Here's an example using FPDF:

    import discord
    from discord.ext import commands
    from io import BytesIO
    from fpdf import FPDF
    
    bot = commands.Bot("!")
    
    @bot.command()
    async def pdf(ctx, *, text):
        pdf = FPDF()
        pdf.add_page()
        pdf.set_font('Arial', 'B', 16)
        pdf.cell(40, 10, text)
        bstring = pdf.output(dest='S').encode('latin-1')
        await ctx.send(file=discord.File(BytesIO(bstring), filename='pdf.pdf'))
    
    bot.run("token")