About Encoder Problem of Printing Chinese

I am going to output a PDF file with some data correlated on the PDF file, in django.
so the thing here is I will have some chinese data from database and render on the PDF file, but turns out the encoder reflects that it couldnt read Chinese (cause Chinese word is out of bound)
the error was like,

‘latin-1’ codec can’t encode characters in position 3029-3048: ordinal not in range(256)

I searched alot on google and it gives me the answer is going to alter that corresponding Chinese String.
I am curious that any methods for me to read all Chinese for the whole page, but not just one single string, which means correcting the encoder to uft-8 but not latin. It will be useful for all other views for me.

Thank you so much, really appreciate :grinning:

Are you saying that you are encountering this issue while you are trying to output the PDF? If so, what library are you using to build those PDF files?
Specifically, is there a setting in that library allowing you to identify the encoding, character sets, and fonts available?

I used the following to make the render PDF function, which I copy from other source.

from io import BytesIO

from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa

def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode(“ISO-8859-1”)), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type=‘application/pdf’)
return None

The thing is the encoder is in latin-1 but not uft-8, so I am curious that how I change the char type for it.
Really appreciate again.

I’m not familiar with the xhtml2pdf library, so I can’t address any specifics regarding it, but the “ISO-8859-1” parameter in the encode statement above is the reference to the latin-1 encoding. You might try changing that to UTF-8.

Thanks Ken sir, I changed the “ISO-8859-1” to “UFT-8”
It works, but all the chinese is Garbled.

What are the possible factors cause this

Unfortunately, you’re now well past the point where I can help.

Even if you were to give me some sample data to look at, I don’t know Chinese and wouldn’t be able to tell if it were right or wrong.

The only suggestion I would have at this point would be to dig more deeply into the xhtml2pdf library to see if there are some settings there needing to be adjusted. (I would start with the basic questions - can you generate any pdf with Chinese characters using xhtml2pdf, and have it come out “right”? Is it a font-selection issue in the PDF?)