1

I am creating PDF files when FPDF. The content is written in Traditional Chinese. So I have added a snippet :

pdf.add_font('TC', '', '/Users/yeung/Library/Fonts/TaipeiSansTCBeta-Regular.ttf', uni=True)

and when I do:

pdf.set_font('TC', '', 12)
pdf.write(8, "你好嗎?")

It successfully displays the characters, and a pdf file is successfully produced.

But a problem comes when I load an external txt file which is written in utf-8(same font as I set above TaipeiSansTCBeta-Regular). I load it with this function:

   def session_body(self, name):
        # Read text file
        with open(name, 'r') as t:
            txt = t.read()
        # Times 12
        self.set_font('TC', '', 12)
        # Output justified text
        self.multi_cell(0, 5, txt)
        # Line break
        self.ln()
        # Mention in italics
        self.set_font('TC', 'L')
        self.cell(0, 5, '(end of session)')

the entire error code is as follows:

---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
/Users/yeung/01_alltime_report_final_202203/major_report.ipynb Cell 40' in <cell line: 106>()
    104 pdf.print_session(1, title, f'./txt/{transaction_count_txt}.txt')
    105 # pdf.print_session(2, title, f'{filename}.txt')
--> 106 pdf.output(f'./output/{title}.pdf', 'F')
    107 os.remove(f'./txt/{transaction_count_txt}.txt')
    108 print("PDF has been created...")

File ~/miniforge3/envs/xgboost/lib/python3.8/site-packages/fpdf/fpdf.py:1084, in FPDF.output(self, name, dest)
   1081     self.error('Unable to create output file: '+name)
   1082 if PY3K:
   1083     # manage binary data as latin1 until PEP461 or similar is implemented
-> 1084     f.write(self.buffer.encode("latin1"))
   1085 else:
   1086     f.write(self.buffer)

UnicodeEncodeError: 'latin-1' codec can't encode characters in position 90578-90591: ordinal not in range(256)

I have tried this:

pdf.set_doc_option('core_fonts_encoding', 'utf-8')

But the error says AttributeError: 'PDF' object has no attribute 'set_doc_option'. I have tried many methods, like change it to rb and rb+ instead of r. I have put # coding: utf-8 at the top of my notebook.

Would anyone please help?

yts61
  • 1,142
  • 2
  • 20
  • 33

0 Answers0