Python3实现自动翻译并生成PDF-DEMO
2024/01/02 15:27 投稿
基于ChatGPT 3.5 开发!
转载请注明源地址:https://www.latiao.org/1474.html
目录架构
-
- —templates
- ——index.html
- —app.py
- —templates
app.py:
from flask import Flask, render_template, request, send_file
from reportlab.pdfgen import canvas
from io import BytesIO
from googletrans import Translator
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
app = Flask(__name__)
translator = Translator()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/generate_pdf', methods=['POST'])
def generate_pdf():
content = request.form['content']
# 翻译中文内容为日语
translated_content = translate_to_japanese(content)
# 使用reportlab创建PDF
pdf_bytes = generate_pdf_reportlab(translated_content)
# 将生成的PDF文件发送给用户下载
return send_file(
BytesIO(pdf_bytes),
as_attachment=True,
download_name='output.pdf',
mimetype='application/pdf'
)
def translate_to_japanese(text):
# 使用googletrans进行翻译
translation = translator.translate(text, src='zh-cn', dest='ja')
return translation.text
def generate_pdf_reportlab(content):
# 创建一个PDF文件并添加内容
pdf_buffer = BytesIO()
# 指定中文字体文件路径,这里假设你有一个中文字体的ttf文件,比如SimSun.ttf
chinese_font_path = 'HarmonyOS_Sans_SC_Medium.ttf'
# 注册中文字体
pdfmetrics.registerFont(TTFont('HarmonyOS_Sans_SC_Medium', chinese_font_path))
pdf = canvas.Canvas(pdf_buffer)
# 设置字体
pdf.setFont('HarmonyOS_Sans_SC_Medium', 12)
# 设置每行的最大字符数
max_chars_per_line = 30
# 添加内容,自动换行
lines = [content[i:i+max_chars_per_line] for i in range(0, len(content), max_chars_per_line)]
y_position = 800
for line in lines:
pdf.drawString(100, y_position, line)
y_position -= 12 # Adjust this value based on your line height
pdf.save()
# 获取PDF内容的字节表示
pdf_bytes = pdf_buffer.getvalue()
pdf_buffer.close()
return pdf_bytes
if __name__ == '__main__':
app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PDF Generator</title>
</head>
<body>
<form action="/generate_pdf" method="post">
<label for="content">输入内容:</label>
<textarea name="content" id="content" rows="10" cols="30"></textarea>
<br>
<input type="submit" value="生成PDF">
</form>
</body>
</html>
效果:
nice,学习下