如何在Python中使用reportlab,rtl和bidi创建包含波斯语(波斯语)文本的PDF [英] How to create PDF containing Persian(Farsi) text with reportlab, rtl and bidi in python

查看:177
本文介绍了如何在Python中使用reportlab,rtl和bidi创建包含波斯语(波斯语)文本的PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试根据可能是英语,波斯语,数字或它们的组合的内容创建PDF文件.

I've been trying to create a PDF file from content that can be English, Persian, digits or a combination of them.

波斯文字存在一些问题,例如:اینیکمتنفارسیاست"

there is some problems with Persian texts like: "این یک متن فارسی است"

۱-文本必须从右到左书写

۱- the text must be written from right to left

2-单词中不同位置的字符之间存在差异(这意味着字符会根据其周围的字符而改变形状)

2- there is a difference between characters in different positions in the word (meaning that characters change their shape according to their surrounding characters)

3-因为句子是从右到左阅读的,所以普通的自动换行无法正常工作.

3- because the sentence is read from right to left then the normal textwrap doesn't work correctly.

推荐答案

在使用Reportlab一段时间后,我们在组织和格式化它时遇到了一些问题.它花费了很多时间,而且有点复杂. 因此,我们决定使用pdfkit和jinja2.通过这种方式,我们可以在html和CSS中设置格式和组织格式,并且也不需要重新格式化波斯语文本.

After working for a while with Reportlab, we had some problems with organizing and formatting it. It took a lot of time and was kind of complicated. So we decided to work with pdfkit and jinja2. This way we can format and organize in html and CSS and we don't need to reformat Persian text too.

首先,我们可以设计一个类似于以下内容的html模板文件:

first we can design an html template file like the one below:


    <!DOCTYPE html>
        <html>
        <head lang="fa-IR">
            <meta charset="UTF-8">
            <title></title>
        </head>
        <body >
            <p dir="rtl">سوابق کاری</p>
            <ul dir="rtl">
                {% for experience in experiences %}
                <li><a href="{{ experience.url }}">{{ experience.title }}</a></li>
                {% endfor %}
            </ul>
        </body>
        </html>

然后我们使用jinja2库将数据渲染到Template中,然后使用pdfkit从渲染结果创建pdf:

and then we use jinja2 library to render our data into Template, and then use pdfkit to create a pdf from render result:

    from jinja2 import Template
    from pdfkit import pdfkit

    sample_data = [{'url': 'http://www.google.com/', 'title': 'گوگل'},
                   {'url': 'http://www.yahoo.com/fa/', 'title': 'یاهو'},
                   {'url': 'http://www.amazon.com/', 'title': 'آمازون'}]

    with open('template.html', 'r') as template_file:
        template_str = template_file.read()
        template = Template(template_str)
        resume_str = template.render({'experiences': sample_data})

        options = {'encoding': "UTF-8", 'quiet': ''}
        bytes_array = pdfkit.PDFKit(resume_str, 'string', options=options).to_pdf()
        with open('result.pdf', 'wb') as output:
            output.write(bytes_array)

这篇关于如何在Python中使用reportlab,rtl和bidi创建包含波斯语(波斯语)文本的PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆