尝试创建PDF文件时出现UnicodeError

时间:2020-04-08 11:31:44

标签: python python-3.x pdf encoding decoding

我正在研究一个Python脚本,该脚本使用 NewsAPI (下面的链接)基于关键字从各种来源获取文章。我的目标是创建一个包含有关每篇文章的一些信息的pdf文件,然后通过电子邮件将pdf发送给我。

我使用for循环遍历从NewsAPI获得的文章,并在其中选择一些我想要的PDF信息。我将数据存储在每个变量中,然后将其作为字符串写入pdf。 pdf看起来不是很好,但是我暂时无法提供更好的解决方案。请随时提出其他替代解决方案。

现在,我可以将前三个变量写入pdf,但遇到第四个变量的编码问题,在这种情况下称为描述。我收到 UnicodeEncodeError。见下文

UnicodeEncodeError: 'latin-1' codec can't encode character '\u2026' in position 1723: ordinal not in range(256)

现在有人可以帮助我了解问题所在吗?我尝试了以下方法来解决该问题,但没有成功。

pdf.output('tuto1.pdf','F').encode('latin-1', 'replace').decode('latin-1')

这里是完整的代码,以防万一。如前所述,请随时提出任何建议。

pdf = FPDF()
pdf.add_page()
count = 0
cell_pos = 40

for article in all_articles['articles']:
    count += 1
    print(f'Article number: {count}')

    published=('Article published : ', article['publishedAt'])
    pdf.set_font('Arial', '', 8)
    pdf.cell(cell_pos, 10, str(published), ln = 1)

    source=('Source : ',article['source']['name'])
    pdf.set_font('Arial', '', 8)
    pdf.cell(cell_pos, 10, str(source), ln = 1)

    artic=('Title : ',article['title'])
    pdf.set_font('Arial', '', 8)
    pdf.cell(cell_pos, 10, str(artic), ln = 1)

    #descrition.encode('latin-1', 'ignore') 
    descrition=('Description : ',article['description'])

    pdf.set_font('Arial', '', 8)
    pdf.cell(cell_pos, 10, str(descrition), ln = 1)
    '''

    link=('Link to the article : ', article['url'],'\n\n')
    pdf.set_font('Arial', '', 8)
    pdf.cell(cell_pos, 10, str(link), ln = 1)
    '''
    cell_pos += 20

#pdf.output('tuto1.pdf','F').encode('latin-1', 'replace').decode('latin-1')
pdf.output('tuto1.pdf', 'F').encode('latin-1')

0 个答案:

没有答案
相关问题