@dani22023

Как сделать перевод DOCX в PNG в python/js?

У меня 2 кода, совмещенные друг с другом. Задача следующая - сделать так, чтобы готовый документ, который создается когда пользователь ввел ответы на вопросы бота и сгенерировался документ по шаблону, переводился в PNG и бот это отправил?
from flask import Flask, request, jsonify, send_file
from io import BytesIO
import os
import datetime
from docx import Document
import win32com.client as win32
import win32com.client
import win32api
from docx2pdf import convert

app = Flask(__name__)

def fill_template(template_path, data):
    doc = Document(template_path)

    for paragraph in doc.paragraphs:
        for key, value in data.items():
            if key in paragraph.text:
                paragraph.text = paragraph.text.replace(key, str(value))

    return doc

def save_document(document, output_directory):
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    output_path = os.path.join(output_directory, f"document_{timestamp}.docx")
    document.save(output_path)
    return output_path

@app.route('/generate_document', methods=['POST'])
def generate_document():
    data = request.json
    category = data['category']
    template_path = get_template_path(category)

    if not template_path:
        return jsonify({"result": "Ошибка: Неверная категория"}), 400

    filled_document = fill_template(template_path, data['data'])
    saved_document_path = save_document(filled_document, "C:\\Users\\SonicMaster\\Downloads")
    
    return jsonify({"result": f"Создан новый документ для категории {category}"})


def get_template_path(category):
    if category == '1':
        return "C:\\Users\\SonicMaster\\Downloads\\shablon.docx"
    elif category == '2':
        return "C:\\Users\\SonicMaster\\Downloads\\shablon2.docx"
    else:
        return None

if __name__ == '__main__':
    app.run(port=5000)

const { Client, GatewayIntentBits, ActionRowBuilder, ButtonBuilder } = require('discord.js');
const axios = require('axios');
const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.DirectMessages,
    ],
});

const questions = [
    "Введите Имя и Фамилию:"
];

const answers = {};
client.on('ready', () => {
    console.log('Запущен!');
	const channel = client.channels.cache.get('1043428536616230972');
	 sendStartMessage(channel);
});



client.on('interactionCreate', async (interaction) => {
    if (interaction.isButton()) {
        const { customId } = interaction;

        switch (customId) {

            case 'start_interaction':
                askQuestions(interaction.user.id, interaction.channel, 0);
                break;
            case 'generate_document':
                if (!answers[interaction.user.id]) {
                    interaction.reply('Вы еще не ответили на все вопросы.');
                    return;
                }

                const response = await axios.post('http://localhost:5000/generate_document', {
                    category: '1',
                    data: answers[interaction.user.id],
                });

                interaction.reply(response.data.result);
                break;
            default:
                break;
        }
    }
});


async function askQuestions(userId, channel, index) {
    if (index < questions.length) {
        const question = questions[index];

        channel.send(question).then(() => {
            const filter = (response) => response.author.id === userId;
            channel.awaitMessages({ filter, max: 1, time: 60000, errors: ['time'] })
                .then(collected => {
                    const answer = collected.first().content;
                    answers[userId] = answers[userId] || {};
                    answers[userId][question] = answer;
                    askQuestions(userId, channel, index + 1);
                })
                .catch(() => {
                    channel.send('Время вышло. Попробуйте снова командой !button.');
                });
        });
    } else {
        const row = new ActionRowBuilder()
            .addComponents(
                new ButtonBuilder()
                    .setCustomId('generate_document')
                    .setLabel('Документ 1')
                    .setStyle(1),
            );

        channel.send({
            content: 'Все вопросы заданы. Выберите действие:',
            components: [row],
        });
    }
}

function sendStartMessage(channel) {
    const row = new ActionRowBuilder()
        .addComponents(
            new ButtonBuilder()
                .setCustomId('start_interaction')
                .setLabel('Начать создание документа')
                .setStyle(1),
        );

    channel.send({
        content: 'Выберите действие:',
        components: [row],
    });
}
client.login('код');
  • Вопрос задан
  • 169 просмотров
Пригласить эксперта
Ответы на вопрос 1
@calculator212
Напрямую не уверен, что такое получается, на практике чаще видел схему docx -> pdf -> png/jpg, если преобразование нужно для любого документа то обычно используется обертка над тулзами libre office или popler utils, некоторые либы умеют напрямую делать преобразование docx->pdf, но там обычно список документов ограничен, под виндой часто юзают апи ворда для конвертации.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы