简体   繁体   English

UnicodeEncodeError: 'latin-1' 编解码器无法编码字符 'μ'

[英]UnicodeEncodeError: 'latin-1' codec can't encode character '\u03bc'

I am creating a pdf using python library PyFPDF and one of my data string contains a "Greek small letter μ" known as mu.我正在使用 python 库PyFPDF创建一个 pdf,我的数据字符串之一包含一个称为 mu 的“希腊小写字母 μ”。 I am getting the above mentioned error.我收到上述错误。 If we remove this greek letter from the data string, the code works perfect.如果我们从数据字符串中删除这个希腊字母,代码就可以完美运行。 I need help parsing this greek letter into pdf output. My code is given below:我需要帮助将这个希腊字母解析为 pdf output。我的代码如下:


    str = "2-3 μg/day"
    pdf = FPDF('P', 'mm', 'A4')
    
    # Add a page  
    pdf.add_page()
    
    # Set fonts and color
    pdf.set_font("Times", "B", size = 24)
    pdf.set_text_color(0, 0, 0)
    
    # insert the texts in pdf
    pdf.write(h = 10, txt = str)
    
    # save the pdf with name .pdf
    pdf.output("output.pdf")

Thanks in advance.提前致谢。

Unsure why PyFPDF is more pedantic than FPDF editor , however your text in theory requires 2 Fonts (Times and Symbol).不确定为什么 PyFPDF 比FPDF 编辑器更迂腐,但是理论上您的文本需要 2 Fonts(时间和符号)。

"Symbol" is normally used for Greek alphabets and some symbols like: Ω, φ, ≠, ©...... “符号”通常用于希腊字母和一些符号,如:Ω、φ、≠、©......
pdf.set_font("Symbol",....

Here using Demo shows one common text insert works with both in tandem by substituting Arial.这里使用 Demo 显示了一种常见的文本插入,通过替换 Arial 可以与两者协同工作。

在此处输入图像描述

<?PHP

require('fpdf.php');

$pdf = new FPDF();
$pdf->AddPage('P', 'A4');
$pdf->SetAutoPageBreak(true, 10);
$pdf->SetFont('Arial', '', 12);
$pdf->SetTopMargin(10);
$pdf->SetLeftMargin(10);
$pdf->SetRightMargin(10);


/* --- Text --- */
$pdf->SetFont('', 'B', 12);
$pdf->Text(21, 31, '2-3 μg/day');


$pdf->Output('created_pdf.pdf','I');
?>

For Times and symbol use (with your own desired offsets)对于时间和符号使用(使用您自己想要的偏移量)

在此处输入图像描述

/* --- Text --- */
$pdf->SetFont('Times', '', 12);
$pdf->Text(19, 32, '2-3');
/* --- Text --- */
$pdf->SetFont('Symbol', '', 12);
$pdf->Text(28, 32, 'μ');
/* --- Text --- */
$pdf->SetFont('Times', '', 12);
$pdf->Text(35, 32, 'g/day');

Thus in your case因此在你的情况下

str = "2-3 μg/day"
pdf = FPDF('P', 'mm', 'A4')

# Add a page  
pdf.add_page()

# Set fonts and color
pdf.set_font("Times", "B", size = 24)
pdf.set_text_color(0, 0, 0)
# insert the texts in pdf
pdf.write(h = 10, txt = "2-3")

# Set font
pdf.set_font("Symbol", "B", size = 24)
# insert the texts in pdf
pdf.write(h = 15, txt = "μ")

# Set font
pdf.set_font("Times", "B", size = 24)
# insert the texts in pdf
pdf.write(h = 20, txt = "g/day")

# save the pdf with name .pdf
pdf.output("output.pdf")

Otherwise use a font that includes text and symbols like 'Arial' or 'DejaVu'否则使用包含文本和符号的字体,如“Arial”或“DejaVu”

pdf.set_font('Arial', 'B', 24)
pdf.write(h = 10, txt = "2-3 μg/day")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM